C 11中delete的使用


In C 11, defaulted and deleted functions give you explicit control over whether the special member functions are automatically generated.

The opposite of a defaulted function is a deleted function.

Deleted functions are useful for preventing object copying, among the rest. Recall that C automatically declares a copy constructor and an assignment operator for classes. To disable copying, declare these two special member functions “=delete”.

The delete specifier can also be used to make sure member functions with particular parameters aren’t called.

=default: it means that you want to use the compiler-generated version of that function, so you don’t need to specify a body.

=delete: it means that you don’t want the compiler to generate that function automatically.

C 11中,對於deleted函式,編譯器會對其禁用,從而避免某些非法的函式呼叫或者型別轉換,從而提高程式碼的安全性。

對於 C 的類,如果程式設計師沒有為其定義特殊成員函式,那麼在需要用到某個特殊成員函式的時候,編譯器會隱式的自動生成一個預設的特殊成員函式,比如預設的建構函式、解構函式、拷貝建構函式以及拷貝賦值運算子。

為了能夠讓程式設計師顯式的禁用某個函式,C 11標準引入了一個新特性:deleted函式。程式設計師只需在函式宣告後加上”=delete;”,就可將該函式禁用。






#include "delete.hpp"
#include <iostream>
// reference: http://www.learncpp.com/cpp-tutorial/b-6-new-virtual-function-controls-override-final-default-and-delete/
class Foo
Foo& operator=(const Foo&) = delete; // disallow use of assignment operator
Foo(const Foo&) = delete; // disallow copy construction
class Foo_1
Foo_1(long long); // Can create Foo() with a long long
Foo_1(long) = delete; // But can't create it with anything smaller
class Foo_2
Foo_2(long long); // Can create Foo() with a long long
template<typename T> Foo_2(T) = delete; // But can't create it with anything else
// reference: http://www.bogotobogo.com/cplusplus/C11/C11_default_delete_specifier.php
class A_
A_(int a){};
A_(double) = delete;         // conversion disabled
A_& operator=(const A_&) = delete;  // assignment operator disabled
int test_delete1()
A_ a_(10);     // OK
// A_ b(3.14);   // Error: conversion from double to int disabled
// a = b;       // Error: assignment operator disabled
return 0;
// reference: https://msdn.microsoft.com/zh-cn/library/dn457344.aspx
struct widget
// deleted operator new prevents widget from being dynamically allocated.
void* operator new(std::size_t) = delete;