Copy elision when creating object inside emplace()

后端 未结 4 881
无人共我
无人共我 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:41

    is the compiler able to optimize this and skip the create and copy?

    There is not necessarily a copy involved. If a move constructor is available, there will be a move. This cannot be optimized away, as the direct initialization case will just call the init constructor, while in the other case, the move constructor will be called additionally (including its side-effects).

    Therefore, if possible, you should refactor those codes.

提交回复
热议问题