C++ 11 default与delete函数

C++ 类型的基础函数

在C++中,声明自定义的类型之后,编译器会默认生成一些成员函数,这些函数被称为默认函数。其中包括

(1)(默认)构造函数

(2)拷贝构造函数

(3)拷贝赋值运算符

(4)移动构造函数

(5)移动赋值运算符

(6)析构函数

另外,编译器还会默认生成一些操作符函数,包括

(7)operator ,

(8)operator &

(9)operator &&

(10)operator *

(11)operator ->

(12)operator ->*

(13)operator new

(14)operator delete

显式缺省函数(=default)

如果类设计者又实现了这些函数的自定义版本后,编译器就不会去生成默认版本。
大多数时候,我们需要声明带参数的构造函数,此时就不会生成默认构造函数,这样会导致类不再是POD类型,从而影响类的优化。

显式删除函数(=delete)

另一方面,有时候可能需要限制一些默认函数的生成。
例如:需要禁止拷贝构造函数的使用。以前通过把拷贝构造函数声明为private访问权限,这样一旦使用编译器就会报错。
而在C++11中,只要在函数的定义或者声明后面加上”= delete”就能实现这样的效果(相比较,这种方式不容易犯错,且更容易理解)。

先举例不使用默认函数:

struct A
{
public:
    A() = default;
    A(const A &) { cout << "construction(const &)" << endl; }
    A(A &&) { cout << "construction(&&)" << endl; }
    A &operator=(const A &) { cout << "operator= (const &) " << endl; }
    A &operator=(A &&) { cout << "operator= (&&) " << endl; }
};

int main()
{
    A a;
    A b(a);       //拷贝构造函数 construction(const &)
    A c(move(a)); //移动构造函数 construction(&&)
    cout << endl;

    A d = a;       //拷贝构造函数 construction(const &)
    A e = move(a); //移动构造函数 construction(&&)
    cout << endl;

    c = a;       //拷贝赋值运算符 operator= (const &)
    d = move(a); //移动赋值运算符 operator= (&&)
    cout << endl;

    system("pause");
    return 0;
}

如果使用default与delete

struct A
{
public:
    A() = default;
    A(const A &) = default;           //{ cout << "construction(const &)" << endl; }
    A(A &&) = default;                // { cout << "construction(&&)" << endl; }
    A &operator=(const A &) = delete; //{ cout << "operator= (const &) " << endl; }
    A &operator=(A &&) = delete;      //{ cout << "operator= (&&) " << endl; }
};

int main()
{
    A a;
    A b(a);       //拷贝构造函数 construction(const &)
    A c(move(a)); //移动构造函数 construction(&&)
    cout << endl;

    A d = a;       //拷贝构造函数 construction(const &)
    A e = move(a); //移动构造函数 construction(&&)
    cout << endl;

    c = a;       //拷贝赋值运算符 operator= (const &),因为该函数设置为delete属性,无法编译
    d = move(a); //移动赋值运算符 operator= (&&),因为该函数设置为delete属性,无法编译
    cout << endl;

    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值