unexpected copy constructor

C

ciccio

Hi,

I recently stumbled upon something rather annoying. When doing a quick
return in a function, it is possible that a copy constructor is called.
This is rather surprising.

The code below demonstrates this and outputs the word "copy".
Is this a bug in the compiler or something from C++? Such a copy
constructors are often really not wanted.

Thanks for the help.

This was compiled with g++ version 4.4.3.

#include <iostream>

class foo {
public:
foo() {}
foo(const foo&f) {std::cout << "copy" << std::endl;}
};

foo function(int i) {
if (i > 0) return foo();
foo f;
return f;
}

int main(void) {
function(-1);
}
 
J

Jonathan Lee

I recently stumbled upon something rather annoying. When doing a quick
return in a function, it is possible that a copy constructor is called.
This is rather surprising.

Actually, it's the normal behavior. How else is your "f" object
supposed to get from the function scope to the containing scope?
At least conceptually, it supposed to be destroyed at the end of
its own scope. So a copy is made and the original destroyed.
The code below demonstrates this and outputs the word "copy".
Is this a bug in the compiler or something from C++? Such a copy
constructors are often really not wanted.

You're right, they're not. C++ compilers are allowed to elide
the copy, i.e., skip it. I guess it depends on the compiler, but
basically they construct the value to be returned in the place
where it is going to be returned to. Thus eliminating the copy
(and destruction).

You'll probably want to look into return value optimization
(or just RVO). Also, check out the FAQ at parashift.com

Whether or not RVO is performed seems to depend a lot on your
compiler. One thing that can sometimes throw it off is if
you are not returning the same object at all points in your
function. Like, if every return statement returned "f" then
you'd probably be okay. The fact that one place returns "f"
and the other "foo()" might cause a problem.

You gotta sorta test things yourself, or find your compiler's
documentation that says specifically what triggers or blocks
RVO.

--Jonathan
 

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,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top