Why is it okay to satisfy an explicit constructor argument using member initialization in the constructor?

I apologize for the incredibly mysterious title.

I read "More Exceptional C ++" from Herb Sutter, and I came across an example of a "counted pointer", I will not paste all the code, but it uses an explicit constructor with a signature:

explicit countedPointer(P* obj): p(new impl(obj) ) {} 

Next, it declares a class that has a counted pointer object as a private member of the class, in the constructor of this class, it initializes its counted pointer like this:

 flagNth(n):pimpl_(new flagNthImpl(n)) {} 

where, pimpl_ is the object of the counter pointer, i.e.

 countedPointer<flagNthImpl>pimpl_; 

I tried to run this code and inside main.cpp, if I try to do the following, I get an error (obviously, since the constructor is explicit)

 int main(int argc, const char * argv[]) { countedPointer<int> cp = new int(5); } 

My question is: why is it ok to do this inside the initialization list of a constructor member? Is initialization something different than regular initialization, and if so, how?

Thanks!

+5
source share
1 answer

This will work for you in main :

 countedPointer<int> cp(new int(5)); 

Direct initialization will call the constructor as usual.

However, you do this:

 countedPointer<int> cp = new int(5); 

This copy initialization, and this does not work with explicit constructors. To successfully use copy initialization with an explicit constructor, you need the following:

 countedPointer<int> cp = countedPointer<int>(new int(5)); 

Of course, you'd better use direct initialization (as the first example) or direct list initialization:

 countedPointer<int> cp{new int(5)}; 
+6
source

Source: https://habr.com/ru/post/1259242/


All Articles