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);
}
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);
}