H
hfinster
Hello,
could somebody please shed light on the following problem with g++
(4.03 and 3.3.6 as well)?
Obviously, the copy constructor is not executed, if I assign the
result of a function call to a (new) variable. Instead the memory
location (address) of a temporary result variable from the function is
used.
This is my test code:
#include <iostream>
class Foo {
public:
Foo() {
std::cerr << "Foo:ctor\n";
}
Foo( const Foo& f ) {
std::cerr << "Foo:cctor\n";
}
};
class Bar {
public:
const Foo f() {
Foo res;
std::cerr << " r " << &res << "\n";
return res;
}
};
int main() {
Bar b;
//
// copy constructor not used
// why?
// the address of f1 is identical to the temporary result object in
f()
//
Foo f1 = b.f();
std::cerr << " f1 " << &f1 << std::endl;
/// result:
/// Foo::ctor
/// r address1
/// f1 address1 (identical)
/// the compiler simply uses 'res' as 'f1'
///
Foo f2;
//
// copy constructor used as expected
//
Foo f3 = f2;
std::cerr << " f2 " << &f2 << std::endl; // different objects
std::cerr << " f3 " << &f3 << std::endl; // (as expected)
///
/// Foo::cctor
/// f2 address2
/// f3 address3 (different)
///
}
Of course, this behaviour is 'optimal' in some sense, as it does not
require copying the contents of the result variable 'res' to 'f1'.
However, there is a problem, if Foo has pointers and f1 requires a
deep copy of data.
Thanks for any hint.
Harald
BTW: if I compile the same code with Embedded Visual C , the behaviour
is as expected (as I expect).
could somebody please shed light on the following problem with g++
(4.03 and 3.3.6 as well)?
Obviously, the copy constructor is not executed, if I assign the
result of a function call to a (new) variable. Instead the memory
location (address) of a temporary result variable from the function is
used.
This is my test code:
#include <iostream>
class Foo {
public:
Foo() {
std::cerr << "Foo:ctor\n";
}
Foo( const Foo& f ) {
std::cerr << "Foo:cctor\n";
}
};
class Bar {
public:
const Foo f() {
Foo res;
std::cerr << " r " << &res << "\n";
return res;
}
};
int main() {
Bar b;
//
// copy constructor not used
// why?
// the address of f1 is identical to the temporary result object in
f()
//
Foo f1 = b.f();
std::cerr << " f1 " << &f1 << std::endl;
/// result:
/// Foo::ctor
/// r address1
/// f1 address1 (identical)
/// the compiler simply uses 'res' as 'f1'
///
Foo f2;
//
// copy constructor used as expected
//
Foo f3 = f2;
std::cerr << " f2 " << &f2 << std::endl; // different objects
std::cerr << " f3 " << &f3 << std::endl; // (as expected)
///
/// Foo::cctor
/// f2 address2
/// f3 address3 (different)
///
}
Of course, this behaviour is 'optimal' in some sense, as it does not
require copying the contents of the result variable 'res' to 'f1'.
However, there is a problem, if Foo has pointers and f1 requires a
deep copy of data.
Thanks for any hint.
Harald
BTW: if I compile the same code with Embedded Visual C , the behaviour
is as expected (as I expect).