Home > Back-end >  Transition initialization what's going on?
Transition initialization what's going on?

Time:12-03

Copy the initialization is to use an equal sign initialize an lvalue method:
 
A, A.
A, b=A.

B is actually calls the copy constructor created objects,
There is a kind of implicit type conversion characteristics, called conversion constructors, condition was introduced into a single class has a need arguments constructor, will allow a parameter of type conversion to a class type:
 
# include
using namespace std;
Class A {
Public:
(A)=default;
{A (int A) cout<" A (int) called "& lt; A (const A& A);
~ (A) {cout<" ~ (A) called "& lt; };
A: : A (const A& A) {
cout<" A (const A&) Called "& lt; }
Int main () {
A, A=1.
}

G + + compiler and MSVC compiler (vs2017) seems to have different treatment methods,
First compiled using g + +, use the parameter - fno - elide - constructors to cancel return value optimization, enter the following:
reference
A (int) called
A (const A&) Called
~ (A) called
~ (A) called

Process seems to be like this: the first step is to call A (int) to build A temporary object; The second call A (const A&) Copy constructor copies the temporary object,
The sense that gives a person is like this:
 
A. A=A (1);

But not entirely, the copy constructor as explicit:
 
# include
using namespace std;
Class A {
Public:
(A)=default;
{A (int A) cout<" A (int) called "& lt; The explicit A (const A& A);
~ (A) {cout<" ~ (A) called "& lt; };
A: : A (const A& A) {
cout<" A (const A&) Called "& lt; }
Int main () {
//A A=A (1);//error: no suitable copy constructor
A, b=1.//ok
}

Seems to be
 A, b=1. 
should be directly shown as
 A, b (A) (1). 


VS2017 is not the case, it seems that copy constructor does not participate in the structure of the object, I set it as explicit or=delete, still can perform conversion structure,
Exactly which conform to the standard?

CodePudding user response:

https://en.cppreference.com/w/cpp/language/copy_initialization
If T is a class type, and the cv-unqualified version of the type of other is not T or derived from T, or if T is non-class type, but the type of other is a class type, user-defined conversion sequences that can convert from the type of other to T (or to a type derived from T if T is a class type and a conversion function is available) are examined and the best one is selected through overload resolution. The result of the conversion, which is a prvalue temporary (until C++17)prvalue expression (since C++17) if a converting constructor was used, is then used to direct-initialize the object. The last step is usually optimized out and the result of the conversion is constructed directly in the memory allocated for the target object, but the appropriate constructor (move or copy) is required to be accessible even though it's not used. (until C++17)

Your g + + may be in the range of the c + + 17 VS2017 May 17 after the c + +,
  • Related