Learn a little trick to improve yourself C++ clause 06 every day: If you don't want to use the function automatically generated by the compiler, you should definitely reject it.

This blog post and this series are my thoughts on watching "Effective C++", and I learn a little trick to improve my C++ every day.

Item 06: If you don't want to use the functions automatically generated by the compiler, you should explicitly reject it.

The previous blog post mentioned that if you did not declare the compiler will declare the default constructor, destructor, assignment operation, and copy constructor for you.

In some cases, you want the objects you produce to be unique and don’t want to assign or copy to others; you can do this

class MySelt
{
    
    
public:
	MySelt() {
    
    
		//..
	}
	
	~MySelt() {
    
    
		//..
	}
private:										//将拷贝其构造函数和赋值函数声明为private。
	//...										
	MySelt(const MySelt&) {
    
    
		//...
	}
	MySelt& operator= (const MySelt&)
	{
    
    
		//...
	}
};

But this is not the best practice, because its member functions and friend functions (friend) can still access its copy and assignment functions.

The best practices are as follows:

class MySeltBase {
    
    
protected:
	MySeltBase(){
    
    
		//...
	}
	~MySeltBase() {
    
    
		//...
	}
private:
	MySeltBase(const MySeltBase&) {
    
    
		//...
	}
	MySeltBase& operator= (const MySeltBase&) {
    
    
		//..
	}
};

class MySeltDerive:private MySeltBase {
    
    
//...
};

int main()
{
    
    
	MySeltDerive msd;
	//MySeltDerive msd1(msd);   //报错,无法拷贝
	//MySeltDerive msd2 = msd;  //报错,无法赋值
}

The MySeltDerive class no longer declares copy construction and assignment operation functions.

remember

In order to cope with the function of the compiler automatically providing the function, the corresponding member function can be declared as private and not implemented. Use the same as above.

Guess you like

Origin blog.csdn.net/weixin_50188452/article/details/111241138