c++ - What are copy elision and return value optimization? -
what copy elision? (named) return value optimization? imply?
in situations can occur? limitations?
- if referenced question, you're looking the introduction.
- for technical overview, see the standard reference.
- see common cases here.
introduction
for technical overview - skip answer.
for common cases copy elision occurs - skip answer.
copy elision optimization implemented compilers prevent (potentially expensive) copies in situations. makes returning value or pass-by-value feasible in practice (restrictions apply).
it's form of optimization elides (ha!) as-if rule - copy elision can applied if copying/moving object has side-effects.
the following example taken wikipedia:
struct c { c() {} c(const c&) { std::cout << "a copy made.\n"; } }; c f() { return c(); } int main() { std::cout << "hello world!\n"; c obj = f(); }
depending on compiler & settings, following outputs are valid:
hello world!
copy made.
copy made.
hello world!
copy made.
hello world!
this means fewer objects can created, can't rely on specific number of destructors being called. shouldn't have critical logic inside copy/move-constructors or destructors, can't rely on them being called.
if call copy or move constructor elided, constructor must still exist , must accessible. ensures copy elision not allow copying objects not copyable, e.g. because have private or deleted copy/move constructor.
Comments
Post a Comment