Pass by value or reference, to a C++ constructor that needs to store a copy?

前端 未结 8 2186
刺人心
刺人心 2020-12-11 19:50

Should a C++ (implicit or explicit) value constructor accept its parameter(s) by value or reference-to-const, when it needs to store a copy of the argument(s) in its object

8条回答
  •  长情又很酷
    2020-12-11 20:29

    I haven't checked what the standard says, but by trying this empirically I can tell you that GCC does not optimize the copy away, regardless of whether the constructor accepts the argument by value or by const reference.

    If, however, the constructor takes a const reference, it manages to avoid an unnecessary copy when you create foo from an existing bar object.

    To summarize:

    Bar b = makeBar();         // No copy, because of RVO
    FooByValue f1 = makeBar(); // Copy constructor of Bar called once
    FooByRef f2 = makeBar();   // Copy constructor of Bar called once
    FooByValue f3(b);          // Copy constructor of Bar called twice
    FooByRef f4(b);            // Copy constructor of Bar called only once
    

    Not that I am a compiler expert, but I guess it makes sense that it generally can't RVO a return value into an arbitrary place (such as the member field of the foo object). Instead, it requires the target to be on the top of the stack.

提交回复
热议问题