mec*_*ahi 6 move-semantics c++11
想象一下,我有一个类,其主要职责是填充数据容器.我想将数据移出这个类.所以我有:
class cCreator
{
public:
void generate()
{
///generate the content of data_ and populate it
....
....
}
//variation 1
std::vector<int>&& getData1()
{
return std::move(data_);
}
//variation 2
std::vector<int> getData2()
{
return std::move(data_);
}
private:
std::vector<int> data_
};
Run Code Online (Sandbox Code Playgroud)
S getData()的变体1和变体2之间有什么区别?当我从函数定义中省略&&时会发生什么变化?
在第一种情况下,函数本身实际上没有发生任何移动。您只是返回一个右值引用,它允许原始调用者在需要时移动。在第二种情况下,数据实际上被移动到临时数据中,无论调用者如何使用结果。
cCreator c1, c2;
c1.getData1(); // no move
std::vector<int> v1 = c1.getData1(); // move directly from data_
// into v1.
c2.getData2(); // move to temporary, which isn't used.
std::vector<int> v2 = c2.getData1(); // move from data_ to temporary,
// then move from temporary to v2.
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
227 次 |
最近记录: |