2013-07-10 98 views
0

对于下面的代码,我想使用std :: move来提高效率。我有两个函数,第一个函数使用std :: move,第二个函数只是调用第一个函数。那么,我需要在函数“vector convertToString()”中再次使用std :: move吗?为什么?为什么不?谢谢。我需要再次使用std :: move吗?

class Entity_PortBreakMeasure 
{ 
public: 
Entity_PortBreakMeasure(){} 
int portfolioId; 
string portfolioName; 
int businessDate; 
string assetType; 
string currency; 
string country; 
string industry; 
string indicator; 
double value; 

inline double operator()() 
{ 
    return value; 
} 

static vector<string> convertToString(Entity_PortBreakMeasure& pbm) 
{ 

    //PORTFOLIOID INDUSTRY CURRENCY COUNTRY BUSINESSDATE ASSETTYPE INDICATOR VALUE PORTFOLIONAME 
    vector<string> result; 

    result.push_back(boost::lexical_cast<string>(pbm.portfolioId)); 
    result.push_back(pbm.industry); 
    result.push_back(pbm.currency); 
    result.push_back(pbm.country); 
    result.push_back(Date(pbm.businessDate).ToString()); 
    result.push_back(pbm.assetType); 
    result.push_back(pbm.indicator); 
    result.push_back(boost::lexical_cast<string>(pbm.value)); 
    result.push_back(pbm.portfolioName); 

    return std::move(result); 
} 

vector<string> convertToString() 
{ 
    return convertToString(*this); 
} 
+0

第一个函数应该说'return result;'。这已经被多次讨论过[例如这里](http://stackoverflow.com/q/17473753/596781)。 –

回答

0

move()不应该用于这些功能中的任何一个。

在第一个函数中,你返回一个局部变量。如果没有move(),大多数(所有?)编译器都将执行NRVO,并且您不会获得副本或移动 - 返回的变量将直接在调用者的返回值中构建。即使编译器出于某种原因无法执行NRVO,当用作return的参数时,局部变量也会变成r值,因此无论如何你都会得到一个动作。这里使用move()仅用于禁止NRVO和编译器执行移动(或者在移动不可行的情况下复制)。

在第二个函数中,由于第一个函数按值返回,所以您已经返回一个r值。 move()这里不会添加任何东西,但复杂性(这可能会混淆优化器生成次优代码或未能做复制elision)。

相关问题