=default關(guān)鍵字使用的地方
The "default" mechanism can be used for any function that has a default. C++11FAQ
也就是說下面這6個函數(shù)都可以跟著=default
關(guān)鍵字.
class A{
public:
A() = default; // Default constructor
A(const A&) = default; // Copy constructor
A(A&&) = default; // Move constructor(since C++11)
A& operator=(const A&) = default; // Copy assignment operator
A& operator=(A&&) = default; // Move assignment operator (since C++11)
~A() = default; // Destructor
};
PS: VS2013暫時不支持Move constructor
和Move assignment operator
使用=default
關(guān)鍵字.
For defaulted functions, using =default to request memberwise move constructors and move assignment operators is not supported. New In VS2013
=default關(guān)鍵字的作用:顯式的要求編譯器生成函數(shù)的一個默認版本两入。
比如說下面的代碼悲靴,如果用戶寫了一個構(gòu)造函數(shù)A(int){};
,那么就不會為class A
生成一個默認的構(gòu)造函數(shù)皿哨。這個時候如果用戶還需要一個和編譯器自動生成的一模一樣的默認的構(gòu)造函數(shù)剃执,那么就可以使用=default
關(guān)鍵字,顯式的讓編譯器生成一個。
class A{
public:
A(int){};
A() = default;
//A(){}; // old way to get an empty constructors like default one.
};
按照Bjarne的說法肉盹,=default
的好處在于。這些好處在default constructor上效果不大疹尾,但是在Move constructor和Move assignment operator上好處比較大了上忍,因為這兩個函數(shù)都比較難實現(xiàn)骤肛。
Leaving it to the compiler to implement the default behavior is simpler, less error-prone, and often leads to better object code. C++11FAQ
寫一個=default和寫一個空的構(gòu)造函數(shù)有什么區(qū)別?
從執(zhí)行效果上,=default
和一個空的構(gòu)造函數(shù)沒有什么區(qū)別窍蓝,都是什么都不做腋颠。但是一旦某個類有了一個用戶定義的構(gòu)造函數(shù),那這個類就不再是aggregate類型吓笙,和不再是trivial類型淑玫,和不再是POD類型了。
比如說下面這段拷貝至[StackOverflow]的代碼所演示的面睛。
#include <type_traits>
struct X {
X() = default;
};
struct Y {
Y() {};
};
int main() {
static_assert(std::is_trivial<X>::value, "X should be trivial");
static_assert(std::is_pod<X>::value, "X should be POD");
static_assert(!std::is_trivial<Y>::value, "Y should not be trivial");
static_assert(!std::is_pod<Y>::value, "Y should not be POD");
}
另外的不同是絮蒿,使用=default
定義的函數(shù),其constexpr
和 exception specification
保證了和編譯器生成的函數(shù)是一致的叁鉴。而如果要手寫的話土涝,就要顯式的把constexpr
和 exception specification
的信息加上。就如下面的代碼所示幌墓,直接寫的A(){}
不帶有constexpr
屬性但壮,會導(dǎo)致編譯錯誤。而struct C
顯式的加上了constexpr
就沒有編譯錯誤了常侣。
PS:這代碼在VS3013下面沒效果茵肃,最好用其他編譯器來驗證。
struct A{
A(){};
};
struct B{
B() = default;
};
struct C{
constexpr C(){};
};
constexpr int f(A s){ return 0; } // compiling error here
constexpr int f(B s){ return 0; }
constexpr int f(C s){ return 0; }
寫一個=default和直接不寫構(gòu)造函數(shù)有什么區(qū)別袭祟。
第一眼看到=default
的感覺就是验残,這是多余的嘛,和直接不寫也沒有區(qū)別嘛巾乳。后來想了下您没,在下面的這種情況下,=default
還是有用處的胆绊。
class A{
public:
static A* CreateA() { return new A; }
private:
A() = default;
};
在這個類中氨鹏,我們希望使用類的某個默認函數(shù),但是需要控制這個函數(shù)的訪問權(quán)限压状。 在這里的代碼使用默認的構(gòu)造函數(shù)為例子仆抵。這個時候=default
就有用了,如果什么都不寫的話种冬,這些默認函數(shù)的作用域是public
镣丑。使用=default
可以很方面的想編譯器在public
作用域下生成這個函數(shù)。在沒有=default
的C++03時代娱两,處理這種問題莺匠,就需要程序員自己寫個完整的實習(xí)出來,對于默認構(gòu)造函數(shù)來說十兢,還比較簡單趣竣,如果對于寫個Copy assignment operator摇庙,還是不小的工作量的,也容易出錯遥缕。
[StackOverflow]:http://stackoverflow.com/questions/20828907/the-new-keyword-default-in-c11