Reputation: 2371
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)
Upvotes: 7
Views: 1175
Reputation: 1286
you are trying to initialize a value to the class object here which calls the copy-constructor.
int main()
{
X x = 1;
}
change the code to
X x(1);
Upvotes: 2
Reputation: 171117
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.
Upvotes: 5