Copy constructor?

Possible duplicate:
Why is the copy constructor not called in this case?

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

+3
source share
3 answers

I assume that they refer to return value optimization implemented in many compilers, where the code is:

CThing DoSomething();

turns into

void DoSomething(CThing& thing);

when an item is declared on the stack and passed to DoSomething:

CThing thing;
DoSomething(thing);

which does not allow CThing to be copied.

+5
source

, . . , . , :

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

big_type a = foo(b);

:

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

big_type a;
foo(b, a);

" " (RVO) , !

+5

, . ( copy elision), , . , ++ FAQ LITE.

:

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 a compiler that allows you to build barfrom line (2) directly in line (1) without any overhead for creating temporary objects Foo.

+1
source

Source: https://habr.com/ru/post/1734318/


All Articles