C++11中= delete;的使用
C++11中,對于deleted函數,編譯器會對其禁用,從而避免某些非法的函數調用或者類型轉換,從而提高代碼的安全性。
對于 C++ 的類,如果程序員沒有為其定義特殊成員函數,那么在需要用到某個特殊成員函數的時候,編譯器會隱式的自動生成一個默認的特殊成員函數,比如默認的構造函數、析構函數、拷貝構造函數以及拷貝賦值運算符。
為了能夠讓程序員顯式的禁用某個函數,C++11標準引入了一個新特性:deleted函數。程序員只需在函數聲明后加上”=delete;”,就可將該函數禁用。
deleted函數特性還可用于禁用類的某些轉換構造函數,從而避免不期望的類型轉換。
deleted函數特性還可以用來禁用某些用戶自定義的類的new操作符,從而避免在自由存儲區創建類的對象。
必須在函數第一次聲明的時候將其聲明為deleted函數,否則編譯器會報錯。即對于類的成員函數而言,deleted函數必須在類體里(inline)定義,而不能在類體外(out-of-line)定義。
雖然defaulted函數特性規定了只有類的特殊成員函數才能被聲明為defaulted函數,但是deleted函數特性并沒有此限制。非類的成員函數,即普通函數也可以被聲明為deleted函數。
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.
下面是從其他文章中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 operatorFoo(const Foo&) = delete; // disallow copy construction
};class Foo_1
{Foo_1(long long); // Can create Foo() with a long longFoo_1(long) = delete; // But can't create it with anything smaller
};class Foo_2
{Foo_2(long long); // Can create Foo() with a long longtemplate<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 disabledA_& 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 disabledreturn 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;
};
GitHub:https://github.com/fengbingchun/Messy_Test
總結
以上是生活随笔為你收集整理的C++11中= delete;的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Markdown语法简介
- 下一篇: C++11中default的使用