vector.push_back rvalue and copy-elision

前端 未结 2 696
轮回少年
轮回少年 2020-12-20 15:53

I push_back a temporary object into a vector like this,

vector vec;
vec.push_back(A(\"abc\"));

will the

2条回答
  •  时光取名叫无心
    2020-12-20 16:29

    If you have a compiler that supports rvalue references, it will be moved into the vector, which is sometimes quite cheap.

    An alternative to that is to directly construct the object in the vector, which can be done with vec.emplace_back("abc");. This only invokes one constructor.

    Both of these are C++11 features. Copy elision is not allowed here, so without those features the copy will still be made.

    However, if the copy constructor has no observable side-effects (which it shouldn't have anyway), a smart compiler may still perform that optimisation, because the "as-if" rule allows any optimisation that results in the same observable behaviour. I don't know if any current compiler does that, though. If not, I doubt anyone will spend the effort to add such an optimisation because rvalue references put an end to that need.

提交回复
热议问题