Look at the following two ways to create a new object of class Y:
X x; Y y(x);//explicit conversion
X x; Y y = x;//implicit conversion
The first way uses explicit conversion and another uses implicit conversion.But,I don't very understand how they work.What is their difference?Could someone interpret for me?The more detailed,the better.Thanks a lot.
The first is called direct-initialization while the second is called copy-initialization. Assuming that
Y has a constructor that takes a
X (or reference to it), direct-initiazliation will call that constructor directly and regardless of whether the constructor is marked as implicit. copy-initialization semantically is equivalent to:
Y y( implicit_conversion<Y>(x) );
That is, the argument is converted by means of an implicit conversion to the destination type and then the copy constructor is called to initialize the variable. In real life, the compiler will remove the copy and convert in place of the destination variable, but the compiler must check that there is an implicit conversion from
Y, and the copy constructor is accessible.
Actually, both are implicit conversions assuming that your class "Y" has a constructor like:
public: Y(X &x)
A class constructor with a single argument will perform the conversion for you.
To avoid implicit construction, use one of the following (one may be better for you based on your situation):
explicitkeyword on the constructor declaration
Y y(x)is direct-initialization, and it will convert the types even if the constructor is marked explicit, as it performs an explicit conversion - David Rodríguez - dribeas 2012-04-04 02:43