Copy elision when creating object inside emplace()

后端 未结 4 838
无人共我
无人共我 2021-02-12 19:00

I see a lot of code at work where people use emplace and emplace_back with a temporary object, like this:

struct A {
    A::A(int, int);
};

vector v;
v         


        
4条回答
  •  失恋的感觉
    2021-02-12 19:46

    My question is: is the compiler able to optimize this and skip the create and copy? Or should I really try to fix these occurrences?

    It can't avoid a copy, in the general case. Since emplace_back accepts by forwarding references, it must create temporaries from a pure standardese perspective. Those references must bind to objects, after all.

    Copy elision is a set of rules that allows a copy(or move) constructor to be avoided, and a copy elided, even if the constructor and corresponding destructor have side-effects. It applies in only specific circumstances. And passing arguments by reference is not one of those. So for non-trivial types, where the object copies can't be inlined by the as-if rule, the compiler's hands are bound if it aims to be standard conformant.

提交回复
热议问题