Is this an example of using the C ++ keyword correctly?

In a GoogleTechTalks video on Youtube , Bjarne Stroustrup talks about the upcoming C ++ 0x standard. In the video, he mentions the following example:

#include <iostream> struct Sick { Sick(double d) { std::cout << d << "\n"; } explicit Sick(int i) { std::cout << i << "\n"; } }; int main() { Sick s1 = 2.1; Sick s2(2.1); } 

Did he want to put the explicit keyword before Sick(double) , rather than Sick(int) , to highlight the problems associated with implicit conversions in certain contexts?

+7
source share
1 answer

Straustup mentions in his discussion that direct initialization, such as

 Sick s2(2.1); 

will only consider constructors with the explicit label if there are any explicit constructors. This is not my experience working with multiple compilers (including GCC 4.6.1 and MSVC 16 / VS 2010), and I cannot find such a requirement in the standard (although I would be interested if someone could point to it).

However, if ints are used in initializers, I think the example will show what Straustrup wanted to demonstrate:

 #include <iostream> struct Sick { Sick(double d) { std::cout << "double " << d << "\n"; } explicit Sick(int i) { std::cout << "int " << i << "\n"; } }; int main() { Sick s1 = 2; Sick s2(2); } 

The launch above will display:

 double 2 int 2 

Shows that two apparently equivalent initializations actually select different constructors.

(Or like the Truncheon mentioned in the question, and I missed that the explicit keyword should be in the Sick(double d) constructor).

+9
source

All Articles