C++11 中值得關注的幾大變化

http://blog.jobbole.com/1281/

Lambda 表達式

Lambda表達式來源於函數式編程,說白就了就是在使用的地方定義函數,有的語言叫“閉包”,如果 lambda 函數沒有傳回值(例如 void ),其回返類型可被完全忽略。 定義在與 lambda 函數相同作用域的變量參考也可以被使用。這種的變量集合一般被稱作 closure(閉包)。我在這裏就不再講這個事了。表達式的簡單語法如下,

1
[capture](parameters)->return_type {body}

原文的作者給出了下面的例子:

1
2
3
4
5
6
7
8
9
10
int main()
{
   char s[]="Hello World!";
   int Uppercase = 0; //modified by the lambda
   for_each(s, s+sizeof(s), [&Uppercase] (char c) {
    if (isupper(c))
     Uppercase++;
    });
 cout << Uppercase << " uppercase letters in: " << s <<endl;
}


 

<span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">在傳統的STL中for_each() 這個玩意最後那個參數需要一個“函數對象”,所謂函數對象,其實是一個class,這個class重載了operator(),於是這個對象可以像函數的式樣的使用。實現一個函數對象並不容易,需要使用template,比如下面這個例子就是函數對象的簡單例子(實際的實現遠比這個複雜):</span>
1
2
3
4
5
6
7
8
9
template <class T>
class less
{
public:
    bool operator()(const T&l, const T&r)const
    {
        return l < r;
    }
};


 

<span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">所以,</span><strong style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">C++引入Lambda的最主要原因就是1)可以定義匿名函數,2)編譯器會把其轉成函數對象</strong><span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">。相信你會和我一樣,會疑問爲什麼以前STL中的ptr_fun()這個函數對象不能用?(ptr_fun()就是把一個自然函數轉成函數對象的)。原因是,ptr_fun() 的侷限是其接收的自然函數只能有1或2個參數。</span>

那麼,除了方便外,爲什麼一定要使用Lambda呢?它比傳統的函數或是函數對象有什麼好處呢?我個人所理解的是,這種函數之年以叫“閉包”,就是因爲其限制了別人的訪問,更私有。也可以認爲他是一次性的方法。Lambda表達式應該是簡潔的,極私有的,爲了更易的代碼和更方便的編程。

自動類型推導 auto

在這一節中,原文主要介紹了兩個關鍵字 auto 和 deltype,示例如下:

1
2
3
4
auto x=0; //x has type int because 0 is int
auto c='a'; //char
auto d=0.5; //double
auto national_debt=14400000000000LL;//long long


 

<span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">auto 最大的好處就是讓代碼簡潔,尤其是那些模板類的聲明,比如:STL中的容器的迭代子類型。</span>
1
vector<int>::const_iterator ci = vi.begin();

可以變成:

1
auto ci = vi.begin();

模板這個特性讓C++的代碼變得很難讀,不信你可以看看STL的源碼,那是一個亂啊。使用auto必需一個初始化值,編譯器可以通過這個初始化值推導出類型。因爲auto是來簡化模板類引入的代碼難讀的問題,如上面的示例,iteration這種類型就最適合用auto的,但是,我們不應該把其濫用。

比如下面的代碼的可讀性就降低了。因爲,我不知道ProcessData返回什麼?int? bool? 還是對象?或是別的什麼?這讓你後面的程序不知道怎麼做。

1
auto obj = ProcessData(someVariables);

但是下面的程序就沒有問題,因爲pObject的型別在後面的new中有了。

1
auto pObject = new SomeType<othertype>::SomeOtherType();

自動化推導 decltype

關於 decltype 是一個操作符,其可以評估括號內表達式的類型,其規則如下:

  1. 如果表達式e是一個變量,那麼就是這個變量的類型。
  2. 如果表達式e是一個函數,那麼就是這個函數返回值的類型。
  3. 如果不符合1和2,如果e是左值,類型爲T,那麼decltype(e)是T&;如果是右值,則是T。

原文給出的示例如下,我們可以看到,這個讓的確我們的定義變量省了很多事。

1
2
3
const vector<int> vi;
typedef decltype (vi.begin()) CIT;
CIT another_const_iterator;

還有一個適合的用法是用來typedef函數指針,也會省很多事。比如:

1
2
3
decltype(&myfunc) pfunc = 0;
 
typedef decltype(&A::func1) type;

auto 和 decltype 的差別和關係

Wikipedia 上是這麼說的(關於decltype的規則見上)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <vector>
 
int main()
{
    const std::vector<int> v(1);
    auto a = v[0];        // a 的類型是 int
    decltype(v[0]) b = 1; // b 的類型是 const int&, 因爲函數的返回類型是
                          // std::vector<int>::operator[](size_type) const
    auto c = 0;           // c 的類型是 int
    auto d = c;           // d 的類型是 int
    decltype(c) e;        // e 的類型是 int, 因爲 c 的類型是int
    decltype((c)) f = c;  // f 的類型是 int&, 因爲 (c) 是左值
    decltype(0) g;        // g 的類型是 int, 因爲 0 是右值
}


 

<span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">如果auto 和 decltype 在一起使用會是什麼樣子?能看下面的示例,下面這個示例也是引入decltype的一個原因——讓C++有能力寫一個 “ </span><a style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;" href="http://en.wikipedia.org/wiki/Wrapper_function">forwarding function</a><span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;"> 模板”,</span>
1
2
3
template< typename LHS, typename RHS>
  auto AddingFunc(const LHS &lhs, const RHS &rhs) -> decltype(lhs+rhs)
{return lhs + rhs;}


 

<span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">這個函數模板看起來相當費解,其用到了auto 和 decltype 來擴展了已有的模板技術的不足。怎麼個不足呢?在上例中,我不知道AddingFunc會接收什麼樣類型的對象,這兩個對象的 + 操作符返回的類型也不知道,老的模板函數無法定義AddingFunc返回值和這兩個對象相加後的返回值匹配,所以,你可以使用上述的這種定義。</span>

統一的初始化語法

C/C++的初始化的方法比較,C++ 11 用大括號統一了這些初始化的方法。
比如:POD的類型。

1
2
int arr[4]={0,1,2,3};
struct tm today={0};

關於POD相說兩句,所謂POD就是Plain Old Data,當class/struct是極簡的(trivial)、屬於標準佈局(standard-layout),以及他的所有非靜態(non-static)成員都是POD時,會被視爲POD。如:

1
2
3
struct A { int m; }; // POD
struct B { ~B(); int m; }; // non-POD, compiler generated default ctor
struct C { C() : m() {}; ~C(); int m; }; // non-POD, default-initialising m


 

<span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">POD的初始化有點怪,比如上例,new A; 和new A(); 是不一樣的,對於其內部的m,前者沒有被初始化,後者被初始化了(不同 的編譯器行爲不一樣,VC++和GCC不一樣)。而非POD的初始化,則都會被初始化。</span>

從這點可以看出,C/C++的初始化問題很奇怪,所以,在C++ 2011版中就做了統一。原文作者給出瞭如下的示例:

1
2
3
4
5
6
7
8
9
C c {0,0}; //C++11 only. 相當於: C c(0,0);
 
int* a = new int[3] { 1, 2, 0 }; /C++11 only
 
class X {
    int a[4];
    public:
        X() : a{1,2,3,4} {} //C++11, member array initializer
};


 

<span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">容器的初始化:</span>
1
2
3
4
5
// C++11 container initializer
vector<string> vs={ "first", "second", "third"};
map singers =
{ {"Lady Gaga", "+1 (212) 555-7890"},
{"Beyonce Knowles", "+1 (212) 555-0987"}};


 

<span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">還支持像Java一樣的成員初始化:</span>
1
2
3
4
5
6
class C
{
   int a=7; //C++11 only
 public:
   C();
};
<strong style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;"> </strong>
<strong style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">Delete 和 Default 函數</strong>

我們知道C++的編譯器在你沒有定義某些成員函數的時候會給你的類自動生成這些函數,比如,構造函數,拷貝構造,析構函數,賦值函數。有些時候,我們不想要這些函數,比如,構造函數,因爲我們想做實現單例模式。傳統的做法是將其聲明成private類型。

在新的C++中引入了兩個指示符,delete意爲告訴編譯器不自動產生這個函數,default告訴編譯器產生一個默認的。原文給出了下面兩個例子:

1
2
3
4
5
struct A
{
    A()=default; //C++11
    virtual ~A()=default; //C++11
};

再如delete

1
2
3
4
5
6
7
struct NoCopy
{
    NoCopy & operator =( const NoCopy & ) = delete;
    NoCopy ( const NoCopy & ) = delete;
};
NoCopy a;
NoCopy b(a); //compilation error, copy ctor is deleted


 

<span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">這裏,我想說一下,爲什麼我們需要default?我什麼都不寫不就是default嗎?不全然是,比如構造函數,因爲只要你定義了一個構造函數,編譯器就不會給你生成一個默認的了。所以,爲了要讓默認的和自定義的共存,才引入這個參數,如下例所示:</span>
1
2
3
4
5
struct SomeType
{
 SomeType() = default; // 使用編譯器生成的默認構造函數
 SomeType(OtherType value);
};


 

<span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">關於delete還有兩個有用的地方是</span>

1)讓你的對象只能生成在棧內存上:

1
2
3
struct NonNewable {
    void *operator new(std::size_t) = delete;
};

2)阻止函數的其形參的類型調用:(若嘗試以 double 的形參調用 f(),將會引發編譯期錯誤, 編譯器不會自動將 double 形參轉型爲 int 再調用f(),如果傳入的參數是double,則會出現編譯錯誤)

1
2
void f(int i);
void f(double) = delete;

nullptr

C/C++的NULL宏是個被有很多潛在BUG的宏。因爲有的庫把其定義成整數0,有的定義成 (void*)0。在C的時代還好。但是在C++的時代,這就會引發很多問題。你可以上網看看。這是爲什麼需要 nullptr 的原因。 nullptr 是強類型的。

1
2
3
4
5
6
void f(int); //#1
void f(char *);//#2
//C++03
f(0); //二義性
//C++11
f(nullptr) //無二義性,調用f(char*)

所以在新版中請以 nullptr 初始化指針。

委託構造

在以前的C++中,構造函數之間不能互相調用,所以,我們在寫這些相似的構造函數裏,我們會把相同的代碼放到一個私有的成員函數中。

1
2
3
4
5
6
7
8
9
10
class SomeType {
private:
  int number;
  string name;
  SomeType( int i, string& s ) : number(i), name(s){}
public:
  SomeType( )               : SomeType( 0, "invalid" ){}
  SomeType( int i )         : SomeType( i, "guest" ){}
  SomeType( string& s ) : SomeType( 1, s ){ PostInit(); }
};


 

<span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">但是,爲了方便並不足讓“委託構造”這個事出現,最主要的問題是,基類的構造不能直接成爲派生類的構造,就算是基類的構造函數夠了,派生類還要自己寫自己的構造函數:</span>
1
2
3
4
5
6
7
8
9
10
11
class BaseClass
{
public:
  BaseClass(int iValue);
};
 
class DerivedClass : public BaseClass
{
public:
  using BaseClass::BaseClass;
};

上例中,派生類手動繼承基類的構造函數, 編譯器可以使用基類的構造函數完成派生類的構造。 而將基類的構造函數帶入派生類的動作 無法選擇性地部分帶入, 所以,要不就是繼承基類全部的構造函數,要不就是一個都不繼承(不手動帶入)。 此外,若牽涉到多重繼承,從多個基類繼承而來的構造函數不可以有相同的函數簽名(signature)。 而派生類的新加入的構造函數也不可以和繼承而來的基類構造函數有相同的函數簽名,因爲這相當於重複聲明。(所謂函數簽名就是函數的參數類型和順序不)

右值引用和move語義

在老版的C++中,臨時性變量(稱爲右值”R-values”,位於賦值操作符之右)經常用作交換兩個變量。比如下面的示例中的tmp變量。示例中的那個函數需要傳遞兩個string的引用,但是在交換的過程中產生了對象的構造,內存的分配還有對象的拷貝構造等等動作,成本比較高。

1
2
3
4
5
6
void naiveswap(string &a, string &b)
{
 string temp = a;
 a=b;
 b=temp;
}

C++ 11增加一個新的引用(reference)類型稱作右值引用(R-value reference),標記爲typename &&。他們能夠以non-const值的方式傳入,允許對象去改動他們。這項修正允許特定對象創造出move語義。

舉例而言,上面那個例子中,string類中保存了一個動態內存分存的char*指針,如果一個string對象發生拷貝構造(如:函數返回),string類裏的char*內存只能通過創建一個新的臨時對象,並把函數內的對象的內存copy到這個新的對象中,然後銷燬臨時對象及其內存。這是原來C++性能上重點被批評的事

能過右值引用,string的構造函數需要改成“move構造函數”,如下所示。這樣一來,使得對某個stirng的右值引用可以單純地從右值複製其內部C-style的指針到新的string,然後留下空的右值。這個操作不需要內存數組的複製,而且空的暫時對象的析構也不會釋放內存。其更有效率。

1
2
3
4
5
class string
{
    string (string&&); //move constructor
    string&& operator=(string&&); //move assignment operator
};


 

<span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">The C++11 STL中廣泛地使用了右值引用和move語議。因此,很多算法和容器的性能都被優化了。</span>

C++ 11 STL 標準庫

C++ STL庫在2003年經歷了很大的整容手術 Library Technical Report 1 (TR1)。 TR1 中出現了很多新的容器類 (unordered_setunordered_mapunordered_multiset, 和 unordered_multimap) 以及一些新的庫支持諸如:正則表達式, tuples,函數對象包裝,等等。 C++11 批准了 TR1 成爲正式的C++標準,還有一些TR1 後新加的一些庫,從而成爲了新的C++ 11 STL標準庫。這個庫主要包含下面的功能:

線程庫

這們就不多說了,以前的STL飽受線程安全的批評。現在好 了。C++ 11 支持線程類了。這將涉及兩個部分:第一、設計一個可以使多個線程在一個進程中共存的內存模型;第二、爲線程之間的交互提供支持。第二部分將由程序庫提供支持。大家可以看看promises and futures,其用於對象的同步。async() 函數模板用於發起併發任務,而 thread_local 爲線程內的數據指定存儲類型。更多的東西,可以查看 Anthony Williams的 Simpler Multithreading in C++0x.

新型智能指針

C++98 的知能指針是 auto_ptr, 在C++ 11中被廢棄了。C++11 引入了兩個指針類: shared_ptr和 unique_ptr。 shared_ptr只是單純的引用計數指針,unique_ptr 是用來取代auto_ptrunique_ptr 提供 auto_ptr 大部份特性,唯一的例外是 auto_ptr 的不安全、隱性的左值搬移。不像 auto_ptrunique_ptr 可以存放在 C++0x 提出的那些能察覺搬移動作的容器之中。

爲什麼要這麼幹?大家可以看看《More Effective C++》中對 auto_ptr的討論。

新的算法

定義了一些新的算法: all_of()any_of() 和 none_of()。

1
2
3
4
5
6
7
8
#include <algorithm>
//C++11 code
//are all of the elements positive?
all_of(first, first+n, ispositive()); //false
//is there at least one positive element?
any_of(first, first+n, ispositive());//true
// are none of the elements positive?
none_of(first, first+n, ispositive()); //false


 

<span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">使用新的copy_n()算法,你可以很方便地拷貝數組。</span>
1
2
3
4
5
#include <algorithm>
int source[5]={0,12,34,50,80};
int target[5];
//copy 5 elements from source to target
copy_n(source,5,target);


 

<span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">使用 </span><code style="font-size: 13px; line-height: 19px; white-space: normal;">iota()</code><span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;"> 可以用來創建遞增的數列。如下例所示:</span>
1
2
3
4
5
include <numeric>
int a[5]={0};
char c[3]={0};
iota(a, a+5, 10); //changes a to {10,11,12,13,14}
iota(c, c+3, 'a'); //{'a','b','c'}


 

<span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">
</span>
<span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">總之,看下來,C++11 還是很學院派,很多實用的東西還是沒有,比如: XML,sockets,reflection,當然還有垃圾回收。看來要等到C++ 20了。呵呵。不過C++ 11在性能上還是很快。參看 Google’s </span><a style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;" href="http://www.itproportal.com/2011/06/07/googles-rates-c-most-complex-highest-performing-language/">benchmark tests</a><span class="Apple-style-span" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px; white-space: normal;">。原文還引用Stroustrup 的觀點:C++11 是一門新的語言——一個更好的 C++。</span>

如果把所有的改變都列出來,你會發現真多啊。我估計C++ Primer那本書的厚度要增加至少30%以上。C++的門檻會不會越來越高了呢?我不知道,但我個人覺得這門語言的確是變得越來越令人望而卻步了。(想起了某人和我說的一句話——學技術真的是太累了,還是搞方法論好混些?)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章