被忽略的C++11规则 : 如果显示定义了析构函数, 就不会生成默认拷贝构造函数

本文讨论了在C++11中,如果类显示定义了析构函数,将不会自动生成默认拷贝构造函数。这可能导致某些依赖默认拷贝构造函数的老代码无法编译。作者认为这个规则有助于提升代码的严谨性,防止意外错误,类似于虚函数上的`override`和`final`关键字。

在C++.Programming.Language.The.4th.Edition (http://download.youkuaiyun.com/detail/salmonrun/5831855) 中,  Bjarne说(44.2.3):

Generation of the copy constructor and the copy assignment is deprecated for a class with a destructor

如果显示定义了 destructor, 那么 copy constructor 和 copy assignment 就不会被生成, 和标记成 delete 是一样的.  查了下标准, 也有这样的说法:
ISOIEC 14882 C++11  12.8 7
If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted; otherwise, it is defined as defaulted ( 8.4 ). The latter case is deprecated if the class has a user-declared copy assignment operator or a user-declared destructor.

写了如下的测试代码, 在 vs2013 preview, g++ 4.8.1, xcode 4.6.3 (clang 4.2) 测试, 结果都能通过编译,无错误提示, 都不支持. 后两个可是号称全实现C++11啊.

    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, 让代码更严格, 防止出现不经意的错误.



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值