copy constructor is not called?

Y

Yan

Here is the code:

#include <iostream>

class A {
public:
A(){
std::cout << "constructor" << std::endl;
}
A(const A&) {
std::cout << "copy_constuctor" << std::endl;
}
~A() {
std::cout << "destructor" << std::endl;
}
};

A foo() {
return A();
}

int main() {
A a = foo();
return 0;
}


The output on the console is:

constructor
destructor

I would expect it to be:
constructor
copy_constructor
destructor
destructor

why isn't the second object being created? I thought the compiler
(Cygwin version of gcc and Visual C++ ver 7.1) makes some optimizations
that result in creating only one object, but even after disabling the
optimization the result was the same. Can anyone please tell me what's
happening here?

Thanks!


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
 
P

Phlip

Yan said:
A a = foo();

Google for "Return Value Optimization". (And don't cross-post the easy
questions to the moderated newsgroup, because you can get a simple answer
faster than their moderation turnaround.)
 
P

Phlip

Phlip said:
Google for "Return Value Optimization".

Oh, and that's not an "optimization", which just means the compiler takes
longer to emit opcodes. It is a language feature, and is specifically
defined as you shall not depend on the number of times a return value
copy-constructs.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top