簡體   English   中英

如何在c ++ 11中返回類成員向量

[英]How to return a class member vector in c++11

我讀了幾篇關於如何從方法返回向量的帖子包括以下內容:

  1. c11 rvalues和移動語義混淆返回語句

  2. 希望速度超值

  3. 為什么visual studio不執行返回值優化rvo

  4. Wiki - 返回值優化

我仍然對如何在VS2013中以正確的方式傳遞向量感到困惑,以及此代碼中的以下方法之間的區別(問題在注釋中標記):

class Foo{
 private:
   std::vector<int> vect;

 public:
     //1 - classic way?
    void GetVect(std::vector<int>& v)
      {
         v = vect;// assignment with swap?
      }

    //2 - RVO?
    std::vector<int> GetVect()
      {
        return vect;
      } 

    //3 - RVO with const?
    std::vector<int> GetVect() const
      {
        return vect;
      }

    //4 - just move?
    std::vector<int> GetVect() 
      {
        return std::move(vect);
      }  

     //5 - move with {}?
    std::vector<int> GetVect() 
      {
        return { std::move(vect) };
      }  
 }

所以我不確定// 1是否是// 2的顯式形式,不確定3是否有效。 4和5之間有什么區別? 如果RVO適用於VS2013中的矢量,如何測試?

//1 - classic way?
void GetVect(std::vector<int>& v)
  {
     v = vect;// assignment with swap?
  }

這只是簡單的丑陋,你仍然需要一個副本,你使你的界面太復雜。

//2 - RVO?
std::vector<int> GetVect()
  {
    return vect;
  } 

//3 - RVO with const?
std::vector<int> GetVect() const
  {
    return vect;
  }

在功能上相同,但您可能希望3表示getVect不會更改您的類狀態,因此可以正確應用const語義。

//4 - just move?
std::vector<int> GetVect() 
  {
    return std::move(vect);
  }  

你似乎不太可能想要這個,在調用GetVect ,內部vect將不再包含任何元素。

 //5 - move with {}?
std::vector<int> GetVect() 
  {
    return { std::move(vect) };
  }  

這應該最終與4相同,您只需更明確地調用返回對象的移動構造函數。

對於性能您可能真正想要的是:

const std::vector<int>& GetVect() const
{
    return vect;
}

這樣您就可以在不需要復制的情況下讀取對象。 如果要寫入返回的向量,請顯式創建副本。 更多細節可以在這個問題中找到

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM