Spirit Spirit - 1 month ago 7
C++ Question

c++ explicit specifier generate safer code

Ive been looking into the explicit specifier and I was hoping I could have some feedback (small examples would be perfect) on the following:


  1. How does an explicit constructor prevent copy initialization?

  2. Can you provide a small example of how explicit has a great benefit over implicit constructors in terms of generating safer code?



Im not so concerned about explicit conversion functions (C++11), just the general ctor principles

Any feedback would be greatly appreciated

Thanks in advance

Answer

My example:

class MyClass {
public:
    MyClass() = default;
    // copy constructor
    explicit MyClass(const MyClass& other) = default; 
    // conversion constructor
    explicit MyClass(int val) : val_(val) {}; // constructor that creates a MyClass object from an int.. in other words this 'converts' an int into a MyClass object

private:
    int val_;
};


void foo(MyClass n) {};

int main() {

    MyClass obj;

    MyClass obj2 = obj; // implicit use of the copy constructor - does not compile if the copy ctor is marked explicit
    MyClass obj3(obj); // explicit call to the copy ctr... always works

    foo(obj); // regular call to foo, copy ctor called
    foo(2); // implicit use of the conversion ctr - does not compile if the conversion ctor is marked explicit.
            // this automatic conversion could be risky/undesired in some cases.. therefore the need for the explicit keyword.
    return 0;
}
Comments