Direct initialization and replication initialization

Source: Internet
Author: User
This is the two forms of initialization supported in C + +.
Copy initialization uses the = symbol, and direct initialization places the initialization in parentheses.
(1) For general built-in types, there is basically no difference between the two types of initialization.
int a (5);//Direct initialization
int a=5;//Copy Initialization
int A=int (5);//Direct initialization
(2) When used for class-type objects, the form of initialization differs from the direct form: direct initialization directly invokes the constructor that matches the argument, and replication initialization always calls the copy constructor. Replication initialization first creates a temporary object with the specified constructor, and then uses the copy constructor to copy that temporary object to the object being created.
String null_book = "9-999-99999-9";//copy-initialization
String dots (10, '. ");//direct-initialization
String empty_copy = string ();//First Direct, then copy-initialization
String empty_direct;//direct-initialization
For class-type objects, replication initialization is used only when a single argument is specified or when an explicit creation of a temporary object is used for replication.
When dots are created, the calling argument is a number and a string constructor of one character and directly initializes the members of the dots. When Null_book is created, the compiler first invokes a string constructor that accepts a C-style string parameter, creates a temporary object, and then initializes the Null_book to a copy of that temporary object using the string copy constructor.
The initialization of both Empty_copy and Empty_direct calls the default constructor. When initialized for the former, the default constructor creates a temporary object, and then the copy constructor initializes the empty_copy with that object. When initializing the latter, the default constructor for the Empty_direct is run directly.

Initialization-enabled forms of replication are primarily intended to be compatible with C usage. When circumstances permit, the compiler can be allowed to bypass the copy constructor to create objects directly, but the compiler is not obligated to do so.
Typically, direct initialization and replication initialization differ only in low-level optimizations. However, they are essentially different for types that do not support replication, or when using explicit constructors:
Ifstream file1 ("filename");//ok:direct initialization
Ifstream file2 = "filename";//error:copy constructor is private
This initialization are okay only if the Sales_item (const string&) constructor are not explicit
Sales_item item = string ("9-999-99999-9");
...
The initialization of the item is correct, depending on which version of the Sales_item class is being used. Some versions define the constructor of the parameter as a string as explicit. If the constructor is displayed, initialization fails, and if the constructor is not displayed, the initialization succeeds.

For replication initialization, the most visible means of invocation is to use the "=" symbol (which should be the copy initialization symbol). Then there are many other places that are implicitly called. When the function returns when the parameter is passed, when the container is initialized.
1 for parameter passing: we know that unless it is a reference parameter, it is a process that uses the top-level object to copy the initialization function arguments.
2 for function return value: We know that unless the reference is returned, the return statement is to use the object within the function, copying the initialization of a top-level object (usually temporary, and then immediately available)
3 in some container initialization process, such as:
Vect<string> Svec (5);
The procedure here is to construct an instance object using string default, and then use this object to replicate the initialization of other elements. This process is the implementation details of the container, actually from the outside look, can be understood as direct initialization.
4) array initialization, sometimes using this syntax:
Sales_item primer_eds[]={string ("1231231"),
String ("3123123")
}
This process is one that invokes the direct initialization generation string, and then continues the implicit invocation of the direct initialization generation Sales_item. Finally, initialize the elements of that array using replication initialization. Here's an introduction to replication constructors and replication initialization: Http://www.cnblogs.com/xkfz007/archive/2012/03/01/2376376.html The following is a class that tests the constructor:
#include <iostream> using namespace std;
    Class a{friend ostream& operator<< (ostream& os,const a&);
            public:a (int a=10): M_a (A) {id=count++;
        cout<< "A (int a): id=" <<id<<endl;
            } A (const a& RHS): M_a (rhs.m_a) {id=count++;
        cout<< "A (const A&AMP;RHS): id=" <<id<<endl;
                } a& operator= (const a& RHS) {if (this!=&rhs) {id=count++;
            M_a=rhs.m_a;
        return *this;
        } ~a () {cout<< "~a:id=" <<id<<endl;
        } Private:int M_a;
        int id;
static int count;
};
int a::count=0; ostream& operator<< (ostream& os,const a& rhs) {os<< "<a:m_a=" <<rhs.m_a<< ", id=
    "<<rhs.id<<" > ";
return OS;
    int main1 () {A A1;
    cout<<a1<<endl; A A2=A1;
    cout<<a2<<endl;
    A A3;
    cout<<a3<<endl;
    A3=A2;
    cout<<a3<<endl;
    A A4 (A3);
cout<<a4<<endl;
return 0;
    int main () {A a1,a2 (5), A3 (200);
    A b=a (8000);
    cout<<b<<endl; 
    A ARR[]={A1,A2,A3};
    int I (5), j=5;
    int K=int ();
cout<<i<<j<<k<<endl; }
assignment Operator (operator=)And copy constructor: A (a& a) {}is to create another object B with an object that already exists. The difference is that the assignment operator handles two existing objects, that is, before the assignment B should be present; The copy constructor generates an entirely new object, i.e. B does not exist until the copy constructor is invoked.
Exp:
Ctemp B (A); Copy constructors, C + + style initialization
Ctemp B=a; is still a copy constructor, but this style is just for compatibility with C, as the above effect
Before that, B does not exist, or is not yet constructed.

Ctemp B;
B = A; Assignment operator
Before this, B has been constructed by default constructor constructs. --------------------------------------------------------------------------------------------------------------- --------1, why there is a copy constructor, which is different from the constructor.
A: The copy constructor is actually a constructor, except that its arguments are references to objects of the Const class itself. It is not necessary to write a copy constructor if there is no pointer member in the class (the pointer member is pointing to the space of the dynamic request). We know that if there is a class cobj, it has produced an object Obja and now uses CObj to create OBJB, if the program uses the statement OBJB = Obja, that is, directly using OBJA data to assign values to OBJB. This is not a problem for the general class, but if CObj has a char* PSTR member that holds the address of the string for the dynamic request, use the new method in the Obja to dynamically request the memory and let the obja.pstr point to the space for the application, after OJBB = Ojba, Obja.pstr and Objb.pstr will point to the space at the same time, so that no one knows who is responsible for releasing the space, it is likely to cause the same memory to be released two times. Using the copy constructor, you first apply for the space that the obja.pstr points to, and then copy the contents of the space, so that you do not point to the same memory at the same time, each has its own application of memory, each responsible for releasing the memory of their application, so as to solve the problem just now. So the "copy" here copies the content of the dynamically requested space, not the data for the class itself. Also note that the parameter of the copy constructor is a reference to the object, not a pointer to the object. As for why to use the reference, not enough pointers for the moment have not figured out, and so understand.
2, why the = assignment operator to overload.
Answer: The above example, the user in the use of the statement OBJB = Obja, perhaps Objb Pstr has pointed to the dynamic application of the space, if the direct and simple to cover the address, it will lead to memory leaks, so need to the = assignment operator to overload, To judge Pstr in overloaded functions if it has already pointed to the dynamic application space, it is released first.
3, copy constructor and = assignment operator overload relationship.
A: As you can see from the original example, the assignment operator overload is more than the copy constructor, and it frees up the memory space that it has requested, in addition to the data that copies the dynamically requested memory that the copy constructor completes. So the implementation of the copy constructor given at the end of the original text can be done using the overload of the assignment operator.
4. When the copy constructor is invoked.
A. The direct assignment of an object also invokes the copy constructor (now that you have the = assignment operator overload, why call the copy constructor). );
B. function parameter passing calls the copy constructor as long as it is passed by value;
C. function return calls the copy constructor as long as it is returned by value.
5, as asked in answer to question 4, since there is a = assignment operator overload, why call the copy constructor.
Answer: Write a small program to test.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.