C ++ implicit conversion constructor call

Why does gcc require a copy constructor to invoke an implicit conversion constructor?

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&)' 

More interesting here, even if I write a copy constructor, it is not called. The 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; } 

Fingerprints ~X()

This is mistake? Is there any workaround?

The gcc version on my locaL machine is 4.6.3, this also works on a different version of gcc (online)

http://ideone.com/ustDRj

+7
c ++ gcc constructor copy-constructor implicit-conversion
source share
2 answers

X x = 1; is the syntax for copy initialization. If the initializer does not have type X (as here), this is semantically equivalent to this:

 X x(X(1)); 

That is, it creates ins from argument 1 , and then copies-initializes X from this instance.

Like any other initialization of a copy, the copy can be deleted. This probably happens in your case, so the copy constructor is not actually called. However (again, as with any other instance), it should be available.

+5
source share

you are trying to initialize a value for a class object here that invokes a copy constructor.

 int main() { X x = 1; } 

change the code to

 X x(1); 
+2
source share

All Articles