"Go" c++11 standard new features: defaulted and Deleted functions

Source: Internet
Author: User

Original link http://www.ibm.com/developerworks/cn/aix/library/1212_lufang_c11new/

This article introduces two new features of the C++11 standard: the defaulted and deleted functions. For the defaulted function, the compiler automatically generates a default function definition body for it, which results in higher code execution efficiency, and eliminates the programmer's effort to manually define the function. For the deleted function, the compiler disables it, avoiding some illegal function calls or type conversions, which can improve the security of your code. This article explains in detail the usage and benefits of the defaulted and deleted functions through code examples.

defaulted function Background problem

C + + classes have four special member functions, namely: Default constructors, destructors, copy constructors, and copy assignment operators. The special member functions of these classes are responsible for creating, initializing, destroying, or copying the objects of the class. If a programmer does not explicitly define a special member function for a class and needs to use that special member function, the compiler implicitly generates a default special member function for the class. For example:

Listing 1
Class x{  private:   int A;  };  x x;

In Listing 1, the programmer does not define a default constructor for a class, X but when creating an object of the class, it is X x necessary to use the default constructor for the class, X at which point the compiler implicitly X generates a default constructor for the class. The auto-generated default constructor has no parameters and contains an empty function body, that is X::X(){ } . Although the auto-generated default constructor has only one empty function body, it can still be used to successfully create X the object of the class x , and listing 1 can be compiled.

However, if a programmer explicitly customizes a non-default constructor for class X without defining a default constructor, listing 2 will have a compilation error:

Listing 2
Class x{public  :   X (int i) {     a = i;   }      Private:   int A;  };  x x;  Error, default constructor x::x () does not exist

Listing 2 compiles an error because the class X already has a user-defined constructor, so the compiler will no longer implicitly generate a default constructor for it. If you need to use the default constructor to create an object for a class, the programmer must explicitly define the default constructor yourself. For example:

Listing 3
Class x{public  :   X () {};  Manually define the default constructor  X (int i) {     a = i;   }      Private:   int A;  };  x x;   Correct, the default constructor x::x () exists

As you can see from listing 3, the default constructor that was expected to be automatically generated by the compiler requires the programmer to write manually, which means that the programmer's workload increases. In addition, the Code execution efficiency of the manually written default constructor is lower than the default constructor generated automatically by the compiler. Other types of special member functions of the class are also the same as the default constructors, when there are user-defined special member functions, the compiler will not implicitly automatically generate default special member functions, and requires the programmer to write manually, increasing the workload of the programmer. Similarly, the Code execution efficiency of a special member function that is written manually is lower than the special member function that the compiler automatically generates.

The defaulted of the function

In order to resolve the two issues as shown in Listing 3:1. Reduce programmer's programming workload; 2. Obtaining the high Code execution efficiency of the default special member function generated automatically by the compiler, the C++11 standard introduces a new feature: the defaulted function. The programmer simply adds "" After the function declaration to =default; declare the function as a defaulted function, and the compiler will automatically generate the function body for the explicitly declared defaulted function. For example:

Listing 4
Class x{public  :   X () = default;   X (int i) {     a = i;   }      Private:   int A;  };  x x;

In Listing 4, the compiler automatically generates a default constructor that X::X(){} can achieve higher code efficiency than a user-defined default constructor.

defaulted function definition syntax

The defaulted function is a new syntax for function definitions introduced by the C++11 standard, as shown in Syntax 1 of the defaulted function definition:

Figure 1. defaulted function definition syntax diagram defaulted function usage and examples

The defaulted function attribute applies only to special member functions of a class, and the special member function has no default parameters. For example:

Listing 5
Class X {public  :   int f () = default;      Error, function f () Non-class X special member function  x (int) = default;       Error, constructor x (int, int) non-X Special member function  x (int = 1) = default;   Error, default constructor X (int=1) contains default arguments};

The defaulted function can be defined either in the class body (inline) or outside the class body (out-of-line). For example:

Listing 6
Class x{public  :     x () = default,//inline, defaulted, constructor   x (const x&);    x& operator = (const x&);    ~x () = default;  Inline defaulted destructor};  X::X (const x&) = default;  Out-of-line defaulted copy constructor x& X::operator = (const x&) = default;     Out-of-line defaulted       //Copy assignment operator

During C + + code compilation, if the programmer does not define a destructor for the class, but when the class object is destroyed and the destructor of the X X class needs to be called, the X compiler automatically generates a destructor for the class implicitly. The auto-generated destructor has no parameters and contains an empty function body, that is X::~X(){ } . For example:

Listing 7
Class X {  private:   int x;  };  Class Y:public X {  private:   int Y;  };  int main () {   x* X = new Y;   Delete x;  }

In Listing 7, the programmer does not define destructors for base class X and derived class Y, and when you delete the base class pointer x in the main function, you need to call the base class's destructor. As a result, the compiler implicitly automatically generates a destructor for class X that can successfully destroy the base class sub-object (that is, the INT member variable x) in the derived class object that x points to.

However, there is a memory leak in this code, and when delete you use a statement to delete a pointer to a derived class object x , the system calls the destructor of the base class, not Y the destructor of the derived class, so the compiler cannot deconstruct the int type member variable y of the derived class.

Therefore, in general, we need to define the destructor of the base class as a virtual function, and when you delete a base class pointer to a derived class object by using the DELETE statement, the system invokes the destructor of the corresponding derived class (to achieve polymorphism), thus avoiding memory leaks. However, the compiler implicitly automatically generates destructors that are non-virtual, which requires the programmer to manually define a virtual destructor for the base class X , for example:

Listing 8
Class X {public  :   virtual ~x () {};     To manually define a virtual destructor private:   int x;  };  Class Y:public X {  private:   int Y;  };  int main () {   x* X = new Y;   Delete x;   }

In Listing 8, because the programmer manually X defines a virtual destructor for the base class, when a statement is used to delete delete a base-class pointer to a derived class object x , the system invokes the destructor of the corresponding derived class Y (which is implicitly generated automatically by the compiler) and X the analysis of the base class To eliminate the memory leaks by destroying the derived class objects completely.

However, in Listing 8, the programmer needs to manually write the definition of the fictional function of the base class (even if the function body is empty), increasing the programmer's programming effort. It is also worth mentioning that the code execution of a manually defined destructor is less efficient than the compiler automatically generated destructors.

To solve the above problem, we can declare the virtual destructor of the base class as the defaulted function, so that the compiler can be explicitly specified to automatically generate the function body for the function. For example:

Listing 9
Class X {public  :   virtual ~x () = defaulted;//compiler automatically generates defaulted function definition body private:   int X;  };  Class Y:public X {  private:   int Y;  };  int main () {   x* X = new Y;   Delete x;

}

In Listing 9, the compiler automatically generates a virtual destructor virtual X::X(){} that has higher code execution efficiency than a user-defined virtual destructor.

Back to top of page

Deleted function Background problem

For C + + classes, if a programmer does not define a special member function for it, the compiler implicitly automatically generates a default special member function, such as a copy constructor or a copy assignment operator, when a special member function is needed. For example:

Listing 10
Class x{public  :   X ();  };  int main () {   X x1;   X x2=x1;   Correct, call the compiler implicitly generated default copy constructor  X x3;   x3=x1;     Correct, invoke the compiler implicitly generated default copy assignment operator}

In Listing 10, programmers do not need to manually write copy constructors and copy assignment operators, and rely on the compiler's auto-generated default copy constructor and the copy assignment operator to implement the copy and assignment of class objects. This can be very convenient in some cases, but in some cases it is a problem to assume that we do not allow copying and assignment between class objects, but it is not possible to prevent the compiler from implicitly automatically generating default copy constructors and copy assignment operators.

The Deleted of the function

To enable programmers to explicitly disable a function, the C++11 standard introduces a new feature: the deleted function. The programmer simply adds "" After the function declaration to =delete; disable the function. For example, we can declare the copy constructor of a class and the X copy assignment operator as the deleted function, which can prohibit X copying and assigning values between class objects.

Listing 11
Class x{public     :        X ();        X (const x&) = delete;  The declaration copy constructor is the deleted function       x& operator = (const X &) = delete;//Declaration copy assignment operator is deleted function     };  int main () {   X x1;   X x2=x1;   Error, copy constructor is disabled for  X X3;   x3=x1;     Error, copy assignment operator disabled}

In Listing 11, although only one copy constructor and one copy assignment operator are explicitly disabled, because the compiler detects that the class X has a user-defined copy constructor and a declaration of the copy assignment operator, the copy constructor or copy assignment operator of the other parameter type is no longer implicitly generated. It is also equivalent X to a class without any copy constructors and copy assignment operators, so copies and assignments between objects are completely forbidden.

Deleted function definition Syntax

The Deleted function is a new syntax for function definitions introduced by the C++11 standard, as shown in Syntax 2 of the Deleted function definition:

Figure 2. Deleted function definition syntax diagram Deleted function usage and examples

The Deleted function attribute can also be used to disable some conversion constructors of a class, thus avoiding undesirable type conversions. In Listing 12, it is assumed that the class only supports a conversion constructor with a double-precision floating-point number double, X and does not support a conversion constructor with a parameter of type int, you can declare a conversion constructor of type int as the deleted function.

Listing 12
Class x{public  :   X (double);                X (int) = delete;      };  int main () {   X x1 (1.2);          X X2 (2); Error, conversion constructor with parameter integer int type disabled           }

The Deleted function attribute can also be used to disable the operators of certain user-defined classes new , thereby avoiding the creation of objects in the free-store class. For example:

Listing 13
#include <cstddef>  using namespace std;  Class x{public  :   void *operator new (size_t) = delete;   void *operator new[] (size_t) = delete;  };  int main () {   X *pa = new X;  Error, the new operator is disabled for  X *PB = new X[10];  Error, new[] operator disabled}

It must be declared as the deleted function the first time the function is declared, or the compiler will give an error. That is, for member functions of a class, the deleted function must be defined in the class body (inline) and not outside the class body (out-of-line). For example:

Listing 14
Class X {public  :    x (const x&);  };  X::X (const x&) = delete;   Error, the deleted function must be declared at the first declaration of the function

Although the defaulted function attribute specifies that only special member functions of a class can be declared as defaulted functions, the deleted function attribute does not have this limitation. Non-class member functions, that is, ordinary functions can also be declared as deleted functions. For example:

Listing 15
int Add (int,int) =delete; int main () {     int A, b;     Add (A, b); Error, function add (int, int) is disabled     }

It is worth mentioning that, in Listing 15, although the add(int, int) function is disabled, but only the definition of the function is disabled, that is, the function cannot be called. But the function identifier is still valid, and the function identifier is add still found when the name lookup and the function overload are resolved. If the compiler resolves an overloaded function and resolves the result to a deleted function, a compilation error occurs. For example:

Listing 16
#include <iostream>   using namespace std;   int Add (int,int) = delete;      Double Add (double a,double b) {   return a+b;  }   int main () {    cout << Add (1,3) << Endl;    Error, called the deleted function add (int, int)   cout << Add (1.2,1.3) << Endl;   return 0;  }
Conclusion

This paper describes in detail the new c++11 features defaulted and deleted functions. This feature subtly expands the syntax of the existing keyword default and delete for C + +, introducing two new ways of defining functions: adding =default and =delete after function declarations. By declaring a special member function of a class as a defaulted function, you can explicitly specify that the compiler automatically generates the default function body for the function. By declaring a function as a deleted function, you can disable some undesirable conversions or operators. The defaulted and deleted function features are simple and functional, and are a very valuable extension of the C + + standard.

"Go" c++11 standard new features: defaulted and Deleted functions

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.