C + + NOTES: Replication control __c++

Source: Internet
Author: User
Tags modifier

Replication Control

When defining a new type, you need to explicitly or implicitly specify what happens when you copy, assign, and undo objects of that type by defining special members: Copy constructors, assignment operators, and destructors. If you do not explicitly define a copy constructor or an assignment operator, the compiler (usually) defines it for us.
Replication constructors, assignment operators, and destructors are always referred to as replication control. The compiler implements these actions automatically, but the class can also define its own version.
Compiler-synthesized copy control functions are very concise, and they do only the necessary work. However, for some classes, relying on the default definition can lead to disaster. The most difficult part of implementing replication control operations is often to identify when the default version needs to be overwritten. A particularly common situation requires that a class define its own replication control members: A class has pointer members.


Copy Constructors

A copy constructor is a special constructor that has a single parameter, which is a reference to the class type, which is commonly used by the const modifier. As with the default constructor, a copy constructor can be invoked implicitly by the compiler.using the copy constructorInitializes an object explicitly or implicitly based on another object of the same type. Copy an object to pass it as an argument to a function. Copies an object when returned from a function. Initializes the elements in the sequential container. [Code3] Initializes an array element based on an element initializer list. [Code4]the definition form of an objectC + + supports two forms of initialization: direct initialization and replication initialization. Copy initialization uses the "=" symbol, while direct initialization places the initialization in parentheses. When used with a class type object, the initialization form differs from the direct form. [CODE1] Direct initialization direct invocation constructor copy initialization that matches the argument first creates a temporary object using the specified constructor, and then copies the temporary object to the object being created with the copy constructor. 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. For types that do not support replication, or use the explicit constructor, replication initialization is not possible. [Code2]a composite copy constructorWithout a copy constructor defined, the compiler will synthesize one for us. Unlike a composite default constructor, a copy constructor is synthesized even if we define other constructors. The behavior of the composite copy constructor is to perform a member-by-class initialization that initializes the new object to a copy of the original object. The compiler will now copy each of the non-static members of the object to the object being created. With only one exception, the type of each member determines the meaning of copying that member. The composite copy constructor replicates the values of the built-in type members directly, and the class type member uses the copy constructor of the class to replicate. The replication of an array member is an exception. Although it is not generally possible to copy an array, if a class has an array member, the composite copy constructor copies each element of the array.to define your own copy constructorA copy constructor is a constructor Foo (const foo&) that accepts a single class type reference parameter (usually a const modifier) because it is used to pass an object to a function and return an object from a function, the constructor should generally not be set to explicit the synthetic copy constructor to complete only the necessary work. A class that contains only members of a class type or a built-in type (but not a pointer type), and can be replicated without explicitly defining a copy constructor. Some classes must define how the copy constructor controls what happens when the object is replicated. A class has a data member that is a pointer, or a member that represents another resource that is allocated in the constructor. Class must do some specific work when creating a new object. If you define a copy constructor, you must also define a default constructor.Prohibit copyingTo prevent replication, a class must explicitly declare its copy constructor private. If you do not define a copy constructor, the compiler will synthesize one. However, friends and members of the class can still be replicated. If you want to prohibit replication in friends and members, you can declare a (private) copy constructor but not define it. It is legal to declare without defining a member function, but any attempt to use an undefined member will cause the link to fail. By declaring (but not defining) private copy constructors, you can prevent any attempt to replicate a class type object: Replication attempts in user code will be marked as errors at compile time, and replication attempts in member functions and friends will cause errors when linked.Assignment Operation House

As with constructors, assignment operators can be overloaded by specifying different types of right-hand operands. The right operand is a special version of the class type: If we do not write this version, the compiler will synthesize one for us. Sales_item trans, accum;trans = Accum; The synthetic assignment operator is similar to the operation of the composite copy constructor. It performs a member assignment: Each member of the right-hand operand object is assigned to the corresponding member of the left operand object. In addition to the divisor group, each member is assigned a normal way of owning the type. For arrays, assign values to each array element. [CODE5] In general, if a class needs to copy a constructor, it also requires an assignment operator. destructor

is the complement of constructors: destructors are automatically applied when an object exceeds the scope or dynamically allocated object is deleted. A destructor can be used to construct or acquire resources during the life of an object when the object is disposed. Regardless of whether the class defines its own destructor, the compiler automatically executes the destructor of a class of non-static data members.

When a destructor calls an Undo class object, the object dynamically allocated by the destructor is automatically invoked only if the pointer to the object is deleted when the object's reference or pointer goes out of scope, the destructor is not run. Destructors are run only if you delete a pointer to a dynamically assigned object or an actual object (not a reference to an object) beyond the scope. When you undo a container (either a standard or a built-in array), the destructor of the class type element in the container is also run, and the elements in the container are always reversed in reverse order.

When you need to write an explicit destructor to free a resource or an action that the designer wants to perform after the use of the class object if the class requires a destructor, it also requires an assignment operator and a copy constructor, which is a useful rule of thumb. Unlike a copy constructor or assignment operator, a synthetic destructor always synthesizes a destructor for us. A synthetic destructor revokes each non-static member by the reverse order in which it was created, so it revokes the member by its members in the reverse sequence in which it is declared in the class. A synthetic destructor does not delete the object to which the pointer member is pointing. Writing a destructor destructor is a member function whose name is preceded by a tilde (~), it has no return value, and no formal parameters. Destructors cannot be overloaded because no formal parameters can be specified. Although multiple constructors can be defined for a class, only one destructor is provided, and an important difference between all object destructors for the class and the copy constructor or assignment operator is that, even if we write our own destructor, the synthetic destructor is still running. [Code6] Code Code1: Direct initialization and replication initialization of class types

String null_book = "9-999-99999-9"; Copy-initialization  
String dots (Ten, '. ');//Direct-initialization  

string empty_copy = string (); Copy-initialization  
string empty_direct;//Direct-initialization

CODE2: Replication Initialization to example not supported
Ifstream file1 ("filename"); Ok:direct initialization 
ifstream file2 = "filename";//Error:copy constructor is private 
//This Initializa tion is okay only if the Sales_item (const string&) constructor are not explicit 
sales_item item = string ("9-999-999 99-9 ");

Code3: Initializing container elements
/* Copy constructors can be used to initialize elements in a sequential container. For example, you can initialize a container with a single parameter representing the capacity. This construction of the container uses the default constructor and the copy constructor
 ///default string constructor and five string copy constructors invoked
 vector< String> Svec (5);
/* The compiler first creates a temporary value using the string default constructor to initialize the Svec, and then uses the copy constructor to copy the temporary values to each element of the Svec. */

Code4: Copy constructors and array elements
/* If an element initializer is not provided for an array of class types, each element is initialized with the default constructor. However, if you use regular curly braces to enclose an array initialization list (4th. 1.1) to provide an explicit element initializer, you use replication initialization to initialize each element. Creates an element of the appropriate type, based on the specified value, and then copies the value to the corresponding element with the copy constructor: */
sales_item primer_eds[] = {string ("0-201-16487-6"),
                             string (" 0-201-54848-8 "),
                             string (" 0-201-82470-1 "),
                             Sales_item ()
                           };
/* As shown in the initialization of the first three elements, you can specify a value directly to invoke the single argument constructor of the element type. If you want to not specify an argument or specify more than one argument, you need to use the complete constructor syntax, just as the last element is initialized. */

CODE5: Synthetic assignment operator
Equivalent to the synthesized assignment operator
sales_item& sales_item::operator=
(const Sales_item &RHS)
{
ISBN = RHS.ISBN;//calls string::operator= 
units_sold=rhs.units_sold;//uses built-in int Assignment 
revenue = rhs.revenue//uses built-in double assignment return
*this;
}
/* The synthetic assignment operator assigns values to each member by using the appropriate built-in or class-defined assignment operator based on the member type, which returns *this, which is a reference to the left operand object. */

Code6: destructor
Class Sales_item {public
     :
     //empty. No work to does other than destroying the Members,which happens 3/>~sales_item () {}
     //other members as before
};
/* When you undo an object of type Sales_item, the destructor that does nothing is run, and when it is done, the composite destructor is run to undo the members of the class. The composite destructor calls the string destructor to undo a string member, and the string destructor releases the memory that holds the ISBN. Units_sold and revenue members are built-in types, so synthetic destructors undo what they don't need to do. */

From:
http://blog.csdn.net/liufei_learning/article/details/21312701

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.