在C++.Programming.Language.The.4th.Edition (http://download.youkuaiyun.com/detail/salmonrun/5831855) 中, Bjarne说(44.2.3):
class A
{
public:
A() : a(new int(5)) {}
~A() { delete a; }
//A(const A&) = delete;
//A(const A & right)
//{
// a = new int(*right.a);
//}
//A & operator=(A && right)
//{
// a = right.a;
// right.a = nullptr;
// return *this;
//}
A & operator++()
{
++*a;
return *this;
}
int value() const { return *a; }
private:
int * a;
};
template<typename elem_t>
std::basic_ostream<elem_t> & operator<<(std::basic_ostream<elem_t> & out, const A & a)
{
out << a.value();
return out;
}
int main()
{
A a;
// 应该有错误提示, 没有copy constructor
A b = a;
++a;
std::cout << "C2:no_default_copy_assignment_test\n"
<< "value of a is " << a << "\n"
<< "value of b is " << b << "\n\n";
return 0;
}
貌似这个规则被无视了. 此规则可能会造成一些老代码无法编译通过, 例如老代码定义了 destrcutor, 并同时依赖默认的 copy constructor, 至少我写过这类code. 我个人觉得这是个被需要的规则, 就像虚函数上新添加的 override 和 final, 让代码更严格, 防止出现不经意的错误.
本文讨论了在C++11中,如果类显示定义了析构函数,将不会自动生成默认拷贝构造函数。这可能导致某些依赖默认拷贝构造函数的老代码无法编译。作者认为这个规则有助于提升代码的严谨性,防止意外错误,类似于虚函数上的`override`和`final`关键字。
2959

被折叠的 条评论
为什么被折叠?



