Why isn't the copy-constructor being called?

closed account (jwC5fSEw)
I'm learning about copy-constructors, and I have a test program with two functions: one to take an object of a class by value and show that its copy-constructor is called, and another to show that the copy-constructor is called when returning by value. Here's the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;

class CopyConst {
  public:
    CopyConst(){}
    CopyConst(const CopyConst&);
};

inline CopyConst::CopyConst(const CopyConst& x){
    cout << "CopyConst copy-constructor called\n";
}

void passByVal(CopyConst x){}

CopyConst localObj(){
    CopyConst x;
    return x;
}

int main(){
    CopyConst test;
    passByVal(test);
    localObj();
    return 0;
}


The first function uses the copy-constructor as it should, but the second doesn't. The instructions for that function are to create a local object of the class and return it by value; isn't that what I've done?
Last edited on
The returned object doesn't get copied unless it has somewhere to get copied to.

try this:

 
CopyConst obj( localObj() );


Of course.... the compiler is free to optimize away copies it finds are unnecessary. Both of these functions, for example, could have the copy ctor calls optimized away.
closed account (jwC5fSEw)
Yeah, I guess that might be what's happening. I tried that and also CopyConst obj = localObj();, but that didn't work either. It's not really important to have this working, and at least I know why it's not.
Topic archived. No new replies allowed.