简体   繁体   中英

When does the compiler creates the copy-constructor in C++?

For example in the code below :

class HowMany {
    static int objectCount;
    public:
        HowMany() { 
            objectCount++; 
        }
        static void print(const string& msg = "") {
             if(msg.size() != 0) 
                 cout << msg << ": ";

             cout << "objectCount = " << objectCount << endl;
        }
        ~HowMany() {
            objectCount--;
            print("~HowMany()");
        }
};

int HowMany::objectCount = 0;

// Pass and return BY VALUE:
HowMany f(HowMany x) {
    x.print("x argument inside f()");
    return x;
}

int main() {
    HowMany h;
    HowMany::print("after construction of h");
    HowMany h2 = f(h);
    HowMany::print("after call to f()");
}

Why does the compiler doesn't create the copy-constructor automatically for the class HowMany, and bit-wise copy takes place when the call to f(h) takes place ?

In what cases the compiler creates the default copy-constructor and in what cases it doesn't create?

It gives output as:

after construction of h: objectCount = 1

x argument inside f(): objectCount = 1

~HowMany(): objectCount = 0

after call to f(): objectCount = 0

~HowMany(): objectCount = -1

~HowMany(): objectCount = -2

Many many thanks in advance

In C++98 and C++03 the compiler always creates a copy constructor, that performs a memberwise copy of your fields, unless you specify explicitly that you wrote your own 1 .

This is what happens in your code: the compiler-generated copy constructor doesn't do anything particular - in particular, it doesn't increment objectCount - so you end up with a negative object count (all the copied objects didn't increment the counter, but they did decrement it).

To obtain the result you expected, you would have to write something like:

HowMany(const HowMany &) { 
        objectCount++; 
}

  1. the default copy constructor is not created even if you write the copy constructor prototype but don't implement it, and/or mark it as private - actually, that's how you create a noncopyable class. C++11 also supports a special syntax to tell the compiler not to generate any copy constructor.

for every object compiler should create copy constructor, here also copy constructor created for all object h, x and h2. But for h object copy constructor is no need. And next you are calling a function f with input argument as h. Here copy constructor invokes and it copies the content in h to x object. And for the next object h2 also same thing (here also copy constructor invokes and copies x to h2). Becuase of this reason only objectcount not incremented. thank you.

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