一段小程式碼秒懂C++右值引用和RVO(返回值優化)的誤區

Binfun發表於2020-12-18

關於C++右值引用的參考文件裡面有明確提到,右值引用可以延長臨時變數的週期。如:

std::string&& r3 = s1 + s1; // okay: rvalue reference extends lifetime

看到這裡的時候,Binfun有點崩潰,就這就能延長生命週期?這個和以下的這樣的命令有啥本質的區別嗎?

std::string r3 = s1 + s1

所以Binfun寫了一段小程式碼來測試一下右值引用的延長生命週期的特性,如:

#include <stdio.h>
#include <utility>//std::move

class result {
public:
  int val;
  result() { printf("constructor() [%p]\n", this); }
  result(result& r): val(r.val) { printf("copying from [%p] to [%p]\n", &r, this); }
  result(result&& r): val(r.val) { printf("moving from [%p] to [%p]\n", &r, this); }
  result(int i): val(i) { printf("constructor(%d) [%p]\n", val, this); }
  ~result() { printf("destructor() [%p]\n", this); }
};

result process(int i)
{
  printf("In process function\n");
  return result(i);
}

int main()
{
  printf("---step1---\n");
  result s1 = process(1);
  printf("---step2---\n");
  result &&s2 = process(2);

  printf("---vals:---\n");
  printf("s1 addr:[%p], val:[%d]\n", &s1, s1.val);
  printf("s2 addr:[%p], val:[%d]\n", &s2, s2.val);
}

然後Binfun自信滿滿地敲了編譯並執行命令:

g++ new_move.cpp -std=c++11 -O2 && ./a.out

看到列印的時候Binfun再一次崩潰了:

---step1---
In process function
constructor(1) [0x7ffd94c8aca0]
---step2---
In process function
constructor(2) [0x7ffd94c8acb0]
---vals:---
s1 addr:[0x7ffd94c8aca0], val:[1]
s2 addr:[0x7ffd94c8acb0], val:[2]
destructor() [0x7ffd94c8acb0]
destructor() [0x7ffd94c8aca0]

這……沒有任何區別啊,C++國際標準委員會逗我玩呢?

RVO和右值引用

其實是有區別的,先聽我解釋一下RVO這個概念:返回值優化

返回值優化(Return value optimization,縮寫為RVO)是C++的一項編譯優化技術。即刪除保持函式返回值的臨時物件。這可能會省略多次複製建構函式

在呼叫process函式的時候竟然沒有臨時變數產生(可以看到建構函式只執行了一次),那應該是被RVO了。既然是編譯優化技術,那麼應該有編譯選項關閉,RVO優化在C++裡面也叫copy_elision(複製消除)優化。使用以下命令即可取消RVO:

g++ new_move.cpp -std=c++11 -fno-elide-constructors -O2 && ./a.out

編譯後列印如下:

---step1---
In process function
constructor(1) [0x7ffe849b8a70]
moving from [0x7ffe849b8a70] to [0x7ffe849b8ab0]
destructor() [0x7ffe849b8a70]
moving from [0x7ffe849b8ab0] to [0x7ffe849b8aa0]
destructor() [0x7ffe849b8ab0]
---step2---
In process function
constructor(2) [0x7ffe849b8a70]
moving from [0x7ffe849b8a70] to [0x7ffe849b8ab0]
destructor() [0x7ffe849b8a70]
---vals:---
s1 addr:[0x7ffe849b8aa0], val:[1]
s2 addr:[0x7ffe849b8ab0], val:[2]
destructor() [0x7ffe849b8ab0]
destructor() [0x7ffe849b8aa0]

可以看到在step1中呼叫process函式的時候,構造產生了一個變數(地址為0x7ffe849b8a70),然後函式返回時將這個變數移動構造到了另一個臨時變數(地址為0x7ffe849b8ab0),接著賦值給s2(地址為0x7ffe849b8aa0)時再一次呼叫了移動建構函式。

之所以以上呼叫的都是移動構造,這是因為編譯器識別出這些變數都是“將亡值”,也就是說編譯器知道這個變數接下來都會離開它的作用域,即將會被析構掉,此時認定它是一個右值&&,所以也就呼叫的是移動建構函式。列印中也體現了這一點,0x7ffe849b8a70和0x7ffe849b8ab0被move constructor之後立馬就被析構掉了。

而step2就不一樣了,我們看到了移動建構函式只被呼叫了一次。而這一次0x7ffe849b8ab0並沒有被析構掉,這一次它被保留了下來,它的生命週期被延長了,直到main函式結束時它才會析構掉。

以上可以看到右值引用的確可以延長右值變數的生命週期。當然儘管在RVO的光環下,只需要構造一次就已經到位了,就沒必要去延長生命週期了-。-|||

std::move和右值引用的坑

另外Binfun進一步理解移動語義的時候,發現了一個坑,希望大家關注一下。這個坑會導致奇怪的問題發生……也會導致很隱蔽的bug……

在說這個例子的時候,我們先介紹一下std::move(懂的可以略過-。-)

文章最下面的參考連結裡面的文章有一段寫得特別棒,如下:

關於move函式內部到底是怎麼實現的,其實std::move函式並不“移動”,它僅僅進行了型別轉換。下面給出一個簡化版本的std::move:

template <typename T>
typename remove_reference<T>::type&& move(T&& param)
{
    using ReturnType = typename remove_reference<T>::type&&;
    return static_cast<ReturnType>(param);
}

程式碼很短,但是估計很難懂。首先看一下函式的返回型別,remove_reference在標頭檔案中,remove_reference有一個成員type,是T去除引用後的型別,所以remove_reference::type&&一定是右值引用,對於返回型別為右值的函式其返回值是一個右值(準確地說是xvalue)。所以,知道了std::move函式的返回值是一個右值。然後,我們看一下函式的引數,使用的是通用引用型別(&&),意味者其可以接收左值,也可以接收右值。但是不管怎麼推導,ReturnType的型別一定是右值引用,最後std::move函式只是簡單地呼叫static_cast將引數轉化為右值引用。

還是同樣的result類和同樣的process函式,我們修改一下main函式為:

int main()
{
  printf("---step1---\n");
  result &&s1 = std::move(process(1));
  printf("---step2---\n");
  process(2);

  printf("---vals:---\n");
  printf("s1 addr:[%p], val:[%d]\n", &s1, s1.val);
}

猜猜最後列印中s1.val的值是1還是2?

g++ new_move.cpp -std=c++11 -O2 && ./a.out

以上的編譯選項的列印如下:

---step1---
In process function
constructor(1) [0x7ffdf1352db0]
destructor() [0x7ffdf1352db0]
---step2---
In process function
constructor(2) [0x7ffdf1352db0]
destructor() [0x7ffdf1352db0]
---vals:---
s1 addr:[0x7ffdf1352db0], val:[2]

g++ new_move.cpp -std=c++11 -fno-elide-constructors -O2 && ./a.out

以上的編譯選項,列印結果如下:

---step1---
In process function
constructor(1) [0x7ffe7d59f350]
moving from [0x7ffe7d59f350] to [0x7ffe7d59f380]
destructor() [0x7ffe7d59f350]
destructor() [0x7ffe7d59f380]
---step2---
In process function
constructor(2) [0x7ffe7d59f350]
moving from [0x7ffe7d59f350] to [0x7ffe7d59f380]
destructor() [0x7ffe7d59f350]
destructor() [0x7ffe7d59f380]
---vals:---
s1 addr:[0x7ffe7d59f380], val:[2]

很可惜都是2,不管有沒有RVO優化都是2。

Binfun的理解是,因為std::move的顯式宣告的關係,result &&s1 = 這種讓右值生命值延長的方法失效了,最終s1指向的是已經被析構掉的右值地址(如上的0x7ffe7d59f380),而因為編譯器優化等級的關係,編譯器會重新回收並利用這個地址。所以在呼叫process(2)的時候會重新使用0x7ffe7d59f380這個地址。

如果編譯選項的優化等級沒那麼高的話(以下把優化等級降為O1),會暫時避免這個問題:

g++ new_move.cpp -std=c++11 -O1 -fno-elide-constructors && ./a.out

列印如下:

---step1---
In process function
constructor(1) [0x7ffca4276e50]
moving from [0x7ffca4276e50] to [0x7ffca4276e80]
destructor() [0x7ffca4276e50]
destructor() [0x7ffca4276e80]
---step2---
In process function
constructor(2) [0x7ffca4276e50]
moving from [0x7ffca4276e50] to [0x7ffca4276e90]
destructor() [0x7ffca4276e50]
destructor() [0x7ffca4276e90]
---vals:---
s1 addr:[0x7ffca4276e80], val:[1]

可以看到以上0x7ffca4276e80雖然被析構了,但是沒有那麼快被重新利用起來,第二次使用的是0x7ffca4276e90,所以結果是正確的1。但是result &&s1 = std::move(process(1))這樣的使用方式應該堅決不要用!

所以記住啊,這樣可以:

result s1 = std::move(process(1)); //OK

這樣也可以:

result &&s1 = process(1); //OK

這樣不可以哦!:

result &&s1 = std::move(process(1)); //Error sometimes

參考連結

  1. https://www.cnblogs.com/tianfang/archive/2013/01/26/2878356.html
  2. https://zhuanlan.zhihu.com/p/107445960
  3. https://www.yhspy.com/2019/09/01/C-編譯器優化之-RVO-與-NRVO/
  4. https://zhuanlan.zhihu.com/p/54050093
  5. http://stupefydeveloper.blogspot.com/2008/10/c-rvo-and-nrvo.html
  6. https://en.cppreference.com/w/cpp/language/reference
  7. https://zh.wikipedia.org/wiki/返回值優化
  8. https://en.wikipedia.org/wiki/Copy_elision
  9. https://zh.wikipedia.org/wiki/值_(電腦科學)
  10. 極客時間專欄《現代C++實戰30講》 03 | 右值和移動究竟解決了什麼問題?

相關文章