Does the compiler always call a copy constructor when it returns an object by value in C++?
            Asked
            
        
        
            Active
            
        
            Viewed 138 times
        
    -6
            
            
        - 
                    It's not a duplicate of the so far listed candidates. They do not consider move semantics. – Cheers and hth. - Alf Feb 17 '18 at 16:42
- 
                    7@Cheersandhth.-Alf - The consensus on meta is to improve canonical duplicate with up to date information. Not to spuriously reopen questions. – StoryTeller - Unslander Monica Feb 17 '18 at 16:44
1 Answers
1
            
            
        No. The compiler is allowed to elide the call to the copy constructor in some cases. Look up RVO (Return Value Optimization) and NRVO (Named Return Value Optimization). Also, since C++17, this optimization is guaranteed in some cases.
Additionally, if the returned type is movable, the compiler may do a move rather than a copy in some cases.
 
    
    
        Jesper Juhl
        
- 30,449
- 3
- 47
- 70
 
    