c++ - How to force the compiler to use explicit copy constructor? -
I have written a small test program with a sample self-defined creator, class containing disorder, copy maker and assignment operator . I was surprised when I realized that the copy maker was not called at all, even if I returned the return value of my class and "Code Object OA Object O2 (O1);
#include Class External Class {Public: External class ({{std :: cout << lt; & lt; "External Class Constructor "External class" ( innerclass.cpp:
#include "innerclass.hpp" int main (zero) {std :: court & lt; & Lt; Std :: endl & lt; & Lt; "First attempt:" & lt; & Lt; Std :: endl; OuterClass oc; OuterClass oc2 (oc); . Oc.innerClass () sayHello (); Std :: cout & lt; & Lt; Std :: endl & lt; & Lt; "Try another:" & lt; & Lt; Std :: endl; External Class :: Inner Class IC (OSIRClass ()); Ic = oc.innerClass (); } Output:
1 attempt: external class constructor OuterClass Copy InnerClass Constructor innerClass () method Hello! InnerClass Destructive 2 Try: InnerClass Maker innerClass () method InnerClass Maker innerClass () method InnerClass Assignment InnerClass Destroyers InnerClass Disposal OuterClass Destroyer OuterClass Destruction There is no guarantee that I have read some research after that The compiler will clearly use the prescribed copy constructor. I do not understand this behavior why copy maker still exists, if we do not know that it is called? How does the compiler decide that it uses it?
Or, better than this, is there a way to implement the compiler to use self-defined copy constructor?
For just completion with the other answer, the standard compiler is a copy creator in some situations (what other Answer: Allows the option of not mentioning "The return value optimization" or "name return value optimization" / NRVO):
12.8 Class items being copied, paragraph 15 (C ++ 98)
Whenever a temporary class object is copied using a copy creator and this text You and the copy are not the only CV-ineligible type, the original and the copy are allowed to be used as two different methods of reference to the same object and do not copy at all, even if the class copy constructor or district Have side effects. For the function with the class return type, if the expression in the return statement is the name of a local object, and the CV-unwanted type of local object function is similar to the return type, to allow the function to return the return value Temporary objects, even if the class copy constructor or the district has a side effect. In these cases, the object is destroyed several times later when the original and copy will have been deleted without optimization.
In your the innerClass () method, the copy constructor that you think will be said in return, can be customized:
InnerClass innerClass () {InnerClass ic; Std :: cout & lt; & Lt; "Innerclass () method" & lt; & Lt; Std :: endl; Return IC; // This copy may be copied ctor}
Comments
Post a Comment