Why isn't the copy constructor elided here?
Posted
by Jesse Beder
on Stack Overflow
See other posts from Stack Overflow
or by Jesse Beder
Published on 2010-04-26T22:26:02Z
Indexed on
2010/04/26
22:43 UTC
Read the original article
Hit count: 205
(I'm using gcc with -O2
.)
This seems like a straightforward opportunity to elide the copy constructor, since there are no side-effects to accessing the value of a field in a bar
's copy of a foo
; but the copy constructor is called, since I get the output meep meep!
.
#include <iostream>
struct foo {
foo(): a(5) { }
foo(const foo& f): a(f.a) { std::cout << "meep meep!\n"; }
int a;
};
struct bar {
foo F() const { return f; }
foo f;
};
int main()
{
bar b;
int a = b.F().a;
return 0;
}
© Stack Overflow or respective owner