简体   繁体   中英

Does copy-constructor or constructor work when we do copy initialization

#include <iostream>

using namespace std;

class ExClass
{
    int data;
    ExClass(const ExClass&);

public:
    ExClass() : data(0) {}
    ExClass(int d) : data(d) { cout<<"Constructor"<<endl; }
};

int main()
{
    ExClass var(2);
    ExClass var2=2;

    return 0;
}

To test whether it calls copy-constructor or constructor when I use copy-initialization, I made copy-constructor private. Although it works with visual c++ 2005, codeblocks 13.12 (compiling with C++11 standards) gives an error.

When I run it as it is, it gives:

Constructor 

Constructor

as an input.

Am I correct thinking that it means var(2) and var2=2 have the same meaning and they both call the same constructor?

If it is, why codeblocks gives an error? Since it doesn't use copy-constructor, it should not give an error.

This...

ExClass var2=2;

...is equivalent to this...

ExClass var2 = ExClass(2);

...which nominally invokes the copy-constructor, but the Standard has a special provision allowing for this to be elided into direct construction of var2 . That's an optional optimisation the compiler can choose to perform - only if the compiler doesn't elide will the missing definition for the copy constructor matter. Either way though, a the compiler must check that a copy-construction would be a legal operation (eg it's not deleted).

So, both compilers are right, and indeed the same compiler may get an error or not depending on the command-line optimisation flags it's invoked with.

ExClass var2 = 2;

converts 2 to an ExClass temporary (prvalue), then initializes var2 with that prvalue. This second step involves either a move- or a copy-constructor (typically). The call to that copy/move constructor can be elided, but it has to be possible/valid. (If the call is elided, the copy/move ctor is not odr-used and therefore no definition is required.)

The Standardese can be found in [dcl.init]/17 and [class.copy]/31ff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM