gpt4 book ai didi

c++11 - C++ 允许将数据移出类成员的最佳方法是什么(std::move 语法)

转载 作者:行者123 更新时间:2023-12-04 14:56:45 25 4
gpt4 key购买 nike

想象一下,我有一个主要负责填充数据容器的类。我想将数据移出这个类。所以我有:

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_
};

S getData() 的变体 1 和变体 2 之间的区别是什么?当我从函数定义中省略 && 时会发生什么变化??

最佳答案

在第一种情况下,函数本身实际上没有发生任何 move 。您只是返回一个右值引用,它允许原始调用者在需要时 move 。在第二种情况下,无论调用者如何使用结果,数据实际上都被 move 到临时数据中。

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.

关于c++11 - C++ 允许将数据移出类成员的最佳方法是什么(std::move 语法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35798407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com