C ++ note construction/destructor/value assignment

Source: Internet
Author: User

1. copy constructor and copy assignment operator
The copy constructor is used to "initialize the self-object with the same type object", and the copy assignment operator is used to "copy its value from another same type object to the self-object ".

Class widget {widget (); // default const widget (const widget & RHs); // copy constructor widget & operator = (const widget & THS ); // copy assignment operator} widget W1; // call the default constructor widget W2; // call the copy constructor W1 = W2; // call the copy assigment Operator

Be careful when you see the value assignment symbol, because the "=" syntax can also be used to call the copy constructor:
Widget W3 = W2;
Copy constructor is a particularly important function. because it defines how an object is passed by value, pass-by-value indicates that the difference is "call copy constructor ".

2. Explain keywords
Explicit only applies to constructors and is used to prevent implicit conversion.

Class A {public: explicit a (int x) {}}; void dosomething (A aobject); // function, which accepts an object a A (20) of type ); dosomething (a); // The correct dosomething (20); // error. The constructor is declared using explicit and cannot be implicitly converted.

Note that explicit is only valid for the constructor of one parameter. In addition to the first parameter, default parameters are provided for other parameters.

3. If you do not want to use the function automatically generated by the compiler, you should explicitly reject it.
The compiler can secretly create default constructor, copy constructor, copy assignment operator, and analytic function for the class. To prevent compilation of such default behaviors, you can set the member functions to private and deliberately do not implement them:

Class homeforsale {public:... private:... homeforsal (const homeforsale &); // only declare homeforsale & operator = (const homeforsale );};

With the above class definition, the compiler will block the customer's attempt to copy the homeforsale object. If you accidentally do this in the member function or the friend function, the connector will complain. We can define a special base class to move connection errors to the compilation phase:

Class uncopyable {protected: uncopyable () {}// allow derived Object Construction and destructor ~ Uncopyable () {} PRIVATE: uncopyable (const uncopyable &); // but the copying uncopyable & operator = (const uncopyable &);}

To prevent the homeforsale object from being copied, the only thing we need to do is inherit uncopyable. When you try to copy the homeforsale object, the compiler will try to generate a copy constructor and a copy assignment operator. The "compiler version" of these functions will attempt to call the corresponding brother of their base class, those calls will be rejected by the compiler because the copy function of the base class is private. The base class named noncopyable is also provided in boost.

4. Pure virtual destructor
Sometimes I want to have an abstract class but no pure virtual function. What should I do? In this case, you can declare a pure vitual destructor. The following is an example:

Class awov {public: Virtual ~ Awov () = 0; // declare the pure virtual destructor}

Note that you must provide a definition for this pure virual destructor:
Awov ::~ Awov () // pure virtual destructor Definition
The compiler will create a pair in the destructor of the derived class of awov ~ Awov call action, so you must provide a definition for this function. Otherwise, the connector will complain.

5. Do not let exceptions escape the destructor
If an exception is thrown in the destructor, the resource may not be completely released. Do not spit out exceptions. If a function called by the Destructor may throw an exception, the Destructor should capture any exceptions, swallow them (not spread), or end the program. Another solution is to put an operation that may throw an exception into a common function, giving the customer the opportunity to call it.

6. Do not call virtual functions during the construction and analysis processes.
The implementation of the virtual function called during base class construction calls the version in base class, because the derived class has not yet been constructed. How can we call the function? Therefore, the object will not become a derived class object before the derived class constructor starts execution. The same principle applies to destructor.

7. Handle "self-assignment" in operator ="
"Self-assignment" occurs when an object is assigned to itself:
Class widget {...};
Widget W;
...
W = W; // assign a value to yourself
The above situation rarely happens, but some code may have potential self-assignment, for example:
A [I] = A [J]; // I and j may be equal.
* PX = * py;
Suppose you create a class to save a pointer pointing to a dynamically allocated bitmap:
Class widget {
...
PRIVATE:
Bitmap * pb;
};
The following is an insecure operator = implementation code:

Widget & Widget: Operator = (const widget & RHs) {Delete Pb; Pb = new Bitmap (* RHS. PB); // when you assign a value to yourself, PB has deleted return * This ;}

We can use the "Certification Test" to test the "self-assignment" purpose:

Widget & Widget: Operator = (cosnt widget & RHs) {If (this = & RHs) return * This; // same as the test Delete Pb; PB = new Bitmap (* RHS. PB); return * This ;}

This works, but there is trouble with exceptions. If "New bitmap" causes exceptions, the problem will occur. In fact, there is another way, we only need to note that do not delete the Pb before copying the content referred to by Pb:

Widget& Widget::operator=(cosnt Widget& rhs){    Bitmap* pOrig = pb;    pb = new Bitmap(*rhs.pb);    delete pb;    return *this;}

Save the pass verification test.

8. About the custom copy constructor and the copy assignment operator
When customizing the copy constructor and the copy assigment operator of the derived class, remember to call the corresponding functions of the base class. Otherwise, some of the base class will be incomplete.

From Objective C ++

PS:

1. When a class without a default constructor acts as a member of another class, it can only (required) be initialized in the constructor.

Related Article

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.