开发者

Copy Constructor? [duplicate]

开发者 https://www.devze.com 2022-12-20 23:47 出处:网络
This question already has answers here: 开发者_StackOverflow Closed 12 years ago. Possible Duplicate:
This question already has answers here: 开发者_StackOverflow Closed 12 years ago.

Possible Duplicate:

Why copy constructor is not called in this case?

When you pass an object to a function by value or return an object from a function by value, the copy constructor must be called. However, in some compilers this does not happen? Any explanation?


I assume they are referring to return-value optimization implemented in many compilers where the code:

CThing DoSomething();

gets turned into

void DoSomething(CThing& thing);

with thing being declared on the stack and passed in to DoSomething:

CThing thing;
DoSomething(thing);

which prevents CThing from needing to be copied.


It often doesn't happen because it doesn't need to happen. This is called copy elision. In many cases, the function doesn't need to make copies, so the compiler optimizes them away. For example, with the following function:

big_type foo(big_type bar)
{
  return bar + 1;
}

big_type a = foo(b);

Will get converted to something like:

void foo(const big_type& bar, big_type& out)
{
  out = bar + 1;
}

big_type a;
foo(b, a);

The removal of the return value is called the "Return Value Optimization" (RVO), and is implemented by most compilers, even when optimizations are turned off!


The compiler may call the copy constructor for pass-by-value or return-by-value, but it doesn't have to. The standard allows for optimizing it away (in standardese it's called copy elision) and in practice many compilers will do so, even if you don't have optimizations turned on. The explanation is pretty detailed, so I'll point you at C++ FAQ LITE.

Short version:

struct Foo
{
    int a, b;
    Foo(int A, int B) : a(A), b(B) {}
};

Foo make_me_a_foo(int x)
{
    // ...blah, blah blah...
    return Foo(x, x+1);  // (1)
}

Foo bar = make_me_a_foo(42);  // (2)

The trick here is the compiler is allowed to construct bar from line (2) directly in line (1) without incurring any overhead of constructing temporary Foo objects.

0

精彩评论

暂无评论...
验证码 换一张
取 消