C 11中delete的使用

NO IMAGE

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;”,就可將該函式禁用。

deleted函式特性還可用於禁用類的某些轉換建構函式,從而避免不期望的型別轉換。

deleted函式特性還可以用來禁用某些使用者自定義的類的new操作符,從而避免在自由儲存區建立類的物件。

必須在函式第一次宣告的時候將其宣告為deleted函式,否則編譯器會報錯。即對於類的成員函式而言,deleted函式必須在類體裡(inline)定義,而不能在類體外(out-of-line)定義。

雖然defaulted函式特性規定了只有類的特殊成員函式才能被宣告為defaulted函式,但是deleted函式特性並沒有此限制。非類的成員函式,即普通函式也可以被宣告為deleted函式。

下面是從其他文章中copy的測試程式碼,詳細內容介紹可以參考對應的reference:

#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_
{
public:
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;
};

GitHubhttps://github.com/fengbingchun/Messy_Test