3.条款之不使用默认生成的函数,应该明确拒绝
我们知道C++类会帮我们自动生成构造函数,析构函数函数,拷贝构造函数,和赋值函数
#include <iostream>
using namespace std;
class homeclass{};
int main(int argc,char *argv[])
{
homeclass h1,h2;
homeclass h3(h1);
h1 = h2;
return 0;
}
以下代码是可以通过,也符合C++准则,但是当我们不使用这些函数的时候
方法1.可以把他们声明为私有函数:
class homeclass{
public:
private:
homeclass(const homclass&);
homeclass & operator=(const homeclass&);
};
此处不加参数名,是因为我们本来就不想让他们实现,加参数名无意义
方法2.方法1虽然这样做,但是不足够安全,因为在member函数或frind函数还是可以调用我们的私有函数
class uncopy{
protected:
uncopy();
~uncopy();
private:
uncopy(const uncopy&)
uncopy & operator=(const uncopy&);
};
class homeclass:private uncopy{
};
此规则:为了驳回编译器自动生成的机能,可对成员函数声明为private不予实现。使用像uncpoy这样的base class也是一种做法。
参考文献《Effective C++》作者 Scott Meyers 翻译 候捷