Why does gcc required copy constructor for implicit conversion constructor call?
class X
{
public:
X(int q) {}
~X()
{
std::cout << "~X()" << std::endl;
}
X(const X&) = delete;
};
X x = 1; // gives error: use of deleted function ‘X::X(const X&)’
What is more interesting here that if I even write copy constructor it is not called. Destructor is called only once, so the following code
class X
{
public:
X(int q) {}
~X()
{
std::cout << "~X()" << std::endl;
}
X(const X&)
{
std::cout << "copy ctor" << std::endl;
}
};
int main()
{
X x = 1;
}
prints ~X()
Is it bug? Is there any workaround?
gcc version on my locaL PC is 4.6.3, this also works the same way on another gcc version (online)
http://ideone.com/ustDRj
implicit constructor is a term commonly used to talk about two different concepts in the language, the. implicitly declared constructor which is a default or copy constructor that will be declared for all user classes if no user defined constructor is provided (default) or no copy constructor is provided (copy).
The above example has the following two conversion constructors: Y(int i) which is used to convert integers to objects of class Y. Y(const char* n, int j = 0) which is used to convert pointers to strings to objects of class Y.
Implicit type conversion in C language is the conversion of one data type into another datatype by the compiler during the execution of the program. It is also called automatic type conversion.
In C++, if a class has a constructor which can be called with a single argument, then this constructor becomes conversion constructor because such a constructor allows automatic conversion to the class being constructed.
X x = 1;
is the syntax for copy initialisation. In case the initialiser is not of type X
(as here), this is semantically equivalent to this:
X x(X(1));
That is, it constructs an insance of X
from argument 1
, and then copy-initialises x
from that instance.
Just like any other copy initialisation, the copy can be elided. This probably happens in your case, so the copy constructor is not actually called. Still, (again, just like with any other copy elision), it must be available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With