Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ implicit conversion constructor call

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

like image 745
axe Avatar asked Oct 24 '13 09:10

axe


People also ask

What is implicit constructor call?

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).

How can we use constructor to convert types?

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.

What is implicit conversion in C?

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.

Which is true about conversion constructor?

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.


1 Answers

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.

like image 169
Angew is no longer proud of SO Avatar answered Oct 11 '22 08:10

Angew is no longer proud of SO