2 ms·
There are cases where copy elision doesn't work (don't know how important is that in practice). One representative example would be something like this (I thin
by matklad 7y ago
There are cases where copy elision doesn't work (don't know how important is that in practice).
One representative example would be something like this (I think this can't use copy-elision, but I am not an expert in C++, please correct me if I am wrong!)
void f(std::vector<Foo>& xs) {
xs.emplace_back(arg1, arg2);
}
Here, the semantics is that xs is resized first and then the constructor for Foo(arg1, arg2) is called. So, if resizing xs throws, no Foo is constructed at all. If we replace emplacement with push_back and a factory function, then the semantics becomes 1) construct Foo 2) extend the vector 3) copy/move Foo into the vector.
- Thorrez 7y agoI don't understand the emplace_back example. I don't see any copies (or moves) happening there at all, so yes, no copy elision can happen. But it doesn't make sense to want copy elision when you already have no copies. But yes, I don't think push_back can do full copy elision, but I don't think there's a real need, because it can use move instead of copying.