C++ copy constructor invocation

前端 未结 5 1684
轮回少年
轮回少年 2021-01-11 15:02

As far as i know, a copy constructor is invoked in the following scenarios :

1) Pass by value
2) Return by value
3) When you create and initialize a new obje         


        
5条回答
  •  旧时难觅i
    2021-01-11 15:38

    The part of the standard which tells you when compilers may elide copies is 12.8/15. It's always up to the compiler whether to do actually perform the elision. There are two legal situations, plus any combination of them:

    • "in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object with the same cv-unqualified type as the function return type"

    • "when a temporary class object that has not been bound to a reference would be copied to a class object with the same cv-unqualified type".

    The former is usually referred to as the "named return value optimization", and it's what permits the output you're seeing in your example. The latter in effect turns copy-initialization into direct initialization, and could occur for instance if your code did Example x = Example();.

    Other copy elisions are not permitted, except of course that the usual "as-if" rules apply. So if the copy constructor has tracing in, then the following code must call it:

    Example x;
    Example y = x;
    

    But if x were otherwise unused, and the cctor had no side-effects, then I think it could be optimized away, just like any other code that does nothing.

提交回复
热议问题