簡介
本文主要用于介紹編譯器幫我們默默的編寫了哪些函數(shù)以及當我們不需要這些函數(shù)的時候,應該如何禁止編譯器幫我們編寫這些函數(shù)。
本文是在閱讀《c++ primer》和《Effective c++》的總結(jié),所以部分內(nèi)容可能會與書中的相同
在閱讀本章之前,請先閱讀C++中編譯器默默生成的函數(shù)
C++如何禁止編譯器生成某些函數(shù)
對于某些類而言,對象的拷貝或賦值時不合法的,例如定義了一個學生類,但對于學生對象而言,只能有一個,世界上不存在兩個一樣的學生對象,我們應該明確阻止學生對象之間的拷貝或賦值,也就是說學生類是不支持拷貝或賦值的。
存在很多中方法來阻止 拷貝構(gòu)造函數(shù)及拷貝賦值運算符的生成,下面主要介紹三種:
- 在C++11標準下,將這些函數(shù)聲明為刪除的函數(shù),在函數(shù)參數(shù)的后面加上=delete來指示出我們定義的刪除的函數(shù)
- 將這些函數(shù)聲明為private,并且不提供函數(shù)定義
- 將待定義的類成為一個不支持copy的類的子類
例程
#include <iostream>
// 方法一
class Test {
public:
Test() = default; // use the default constructor
Test(const Test&) = delete;
Test& operator=(const Test&) = delete;
int value = 10;
};
//方法二
class NoCopy {
public:
NoCopy() = default;
int value = 10;
private:
NoCopy(const NoCopy&);
NoCopy& operator=(const NoCopy&);
};
// 方法三
//boost/noncopyable縮減版
class noncopyable
{
protected:
noncopyable() = default;
~noncopyable() = default;
noncopyable(const noncopyable&) = delete;
noncopyable& operator=(const noncopyable&) = delete;
};
class nocopy :noncopyable //默認繼承方式為私有繼承
{
//...
};
int main()
{
Test test; // default constructor
//[Error]:function "Test::Test(Test &)" cannot be referenced -- it is a deleted function
//Test test2(test); // copy constructor
//std::cout <<"test2.value: " <<test2.value << std::endl;
//test2.value = 300;
//[Error]:function "Test::operator=(Test &)" cannot be referenced -- it is a deleted function
//test = test2; // copy assignment
std::cout <<"test.value: " <<test.value << std::endl;
return 0;
}
//輸出:
test.value: 10