2

In C++, when initializing a class like

MyClass(myBigObject s):
  s_(s)
{
...
}

it looks as if s is copied once at function entry ("pass by value") and once when being assigned to s_.

Are compilers smart enough to strip out the first copy?

Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249

3 Answers3

3

Compilers are allowed to strip out the first copy iff

  1. The copy does not have observable behavior according to the as-if rule.
    For this rule to apply, your compiler must know neither constructor nor destructor of myBigObject have any observable side-effects when compiling the user of the MyClass ctor.

    1.9 Program Execution

    The semantic descriptions in this International Standard define a parameterized nondeterministic abstract machine. This International Standard places no requirement on the structure of conforming implementations. In particular, they need not copy or emulate the structure of the abstract machine. Rather, conforming implementations are required to emulate (only) the observable behavior of the abstract machine as explained below.

  2. or if they can use the copy-elision rule, which allows disregarding the as-if rule.
    For this to apply, you must feed the constructor an anonymous unbound object.

    12.8 Copying and Moving class objects §31

    When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects. In such cases, the implementation treats the source and target of the omitted copy/move operation as simply two different ways of referring to the same object, and the destruction of that object occurs at the later of the times when the two objects would have been destroyed without the optimization.123 This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):
    — in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cvunqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value
    — in a throw-expression, when the operand is the name of a non-volatile automatic object (other than a function or catch-clause parameter) whose scope does not extend beyond the end of the innermost enclosing try-block (if there is one), the copy/move operation from the operand to the exception object (15.1) can be omitted by constructing the automatic object directly into the exception object
    — when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move
    — when the exception-declaration of an exception handler (Clause 15) declares an object of the same type (except for cv-qualification) as the exception object (15.1), the copy/move operation can be omitted by treating the exception-declaration as an alias for the exception object if the meaning of the program will be unchanged except for the execution of constructors and destructors for the object declared by the exception-declaration.

Far easier to take the argument by movable-reference &&, which allows replacing the second copy with a move under any circumstances.
Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • You show some citations but wrong findings. Copy elision will not apply here and object will not be automatically moved. – Lol4t0 Jun 13 '14 at 17:23
  • @Lol4t0: He asked whether the first copy, which is to the argument passed to the `MyClass`-ctor, can be omitted. There I'm spot-on, methinks. – Deduplicator Jun 13 '14 at 17:28
1

compiler cannot optimize copying from argument to calss field in general case. Apparently your object can have complex copy constructor with side effects that cannot be omited.

But in your case you probably want to replace copying with moving.

You should write move constructor and use std::move to move s to _s:

myBigObject(myBigObject&&other);

MyClass(myBigObject s):
  s_(std::move(s))
{
...
}

In that case code like

MyClass obj((myBigObject()));

will end up with zero copyings as object will be first moved to constructor and then to class field.

Community
  • 1
  • 1
Lol4t0
  • 12,444
  • 4
  • 29
  • 65
1

First copy into s can be omitted for a temporary

An optimizing compiler will likely omit the first copy if you pass a temporary object:

MyClass x{ myBigObject() };

This is likely to invoke the copy constructor only once since the temporary myBigObject will be constructed directly into the constructor argument s.

Note that this can change the observable behaviour of your program.

#include <iostream>

struct myBigObject
{
  size_t x;
  myBigObject() : x() {}
  myBigObject(myBigObject && other)
  {
    std::cout << "Move myBigObject" << std::endl;
  }
  myBigObject(const myBigObject &other)
  {
    std::cout << "Copy myBigObject" << std::endl;
    x = 12;
  }
};

struct MyClass
{
    MyClass(myBigObject s)
      : s_(s) 
    { 
      std::cout << "x of s : " << s.x << std::endl;
      std::cout << "x of s_ : " << s_.x << std::endl;
    }
    myBigObject s_;
};

int main()
{
  std::cout << "A:" << std::endl;
  MyClass x{ myBigObject() };
  std::cout << "B:" << std::endl;
  myBigObject y;
  MyClass z{ y };
}

It prints (https://ideone.com/hMEv1W + MSVS2013,Toolsetv120)

A:
Copy myBigObject
x of s : 0
x of s_ : 12
B:
Copy myBigObject
Copy myBigObject
x of s : 12
x of s_ : 12

Second copy into s_ cannot be elided

The copy into s_ cannot be omitted since s and s_ need to be different objects.

If you want only one copy of myBigObject in your class you can go for:

MyClass(myBigObject const & s)
  : s_(s) 
{ 
}
MyClass(myBigObject && s)
  : s_(std::forward<myBigObject>(s))
{
}

This way you do not see any copies in case of the temporary and only one copy for non-temporary objects.

The altered code will print:

A:
Move myBigObject
B:
Copy myBigObject
Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249
Pixelchemist
  • 24,090
  • 7
  • 47
  • 71