C++11 new features = delete and = default

C++11 new features = delete and = default

From: http://www.wazhlh.com/?post=7

C++ classes have four types of special member functions, which are: default constructor, destructor, copy constructor, and copy assignment operator.

1. The default function in the class

Default constructor
Default destructor
Default copy constructor
Default copy assignment function
Default move constructor
Default move assignment function
2. Custom operation functions in the class

operator
operator&
operator&&
operator*
operator->
operator->*
operator new
operator delete
[= default] The keyword
C++ stipulates that once a class implements a custom version of these functions, the compiler will no longer automatically produce the default version. Note that the default version is not automatically generated. Of course, the default version can be generated manually. When we define the constructor with parameters, it is best to declare the version without parameters to complete the variable initialization without parameters. At this time, the compiler will no longer automatically provide the default version without parameters. We can control the generation of the default constructor by using the keyword default, and explicitly instruct the compiler to generate the default version of the function. E.g:

class Preson
{
    
    
public:
	Preson(int a);
	~Preson();
};
 
Preson A; // 就会报错 类不存在默认的构造函数

Note: Can only appear in the default constructor, copy and move constructor, copy and move copy operator and destructor

class Preson
{
    
    
public:
	Preson() = default;
	Preson(int a);
	~Preson();
};
 
Preson A; // ok

[= delete] Keywords
Sometimes we want to limit the generation of default functions. Typically, the use of copy constructors is prohibited. The past practice is to declare the copy constructor as private and not provide an implementation, so that when the object is copied, the compilation cannot pass, and C++11 uses the delete keyword to explicitly instruct the compiler The default version of the function is not generated.

class Preson
{
    
    
public:
	Preson() = default;
	Preson(int a) = delete;
	~Preson();
};
 
Preson a; // ok
Preson b = new Preson(10); // err 无法引用 Preson::Preson(int a)

Note: In C++11, the delete keyword can be used in any function, not just limited to class member functions

class Preson
{
    
    
public:
	Preson() = default;
	Preson(int a) = delete;
	~Preson();
 
	void sayHello(int a) = delete;
	void sayHello(char a);
	void sayHello(std::string a) = delete;
};
 
Preson* p = new Preson();
p->sayHello(10); // err
p->sayHello('a'); // ok
p->sayHello("hello"); // err

Guess you like

Origin blog.csdn.net/wowocpp/article/details/114255645