从类移动向量(与 2013 编译器相比)

moving vector from class (vs 2013 compiler)

本文关键字:编译器 2013 移动 向量      更新时间:2023-10-16

我想从类中移动向量

class Data
{
    public:
        std::vector<int> && getValues() {return std::move(values);}
    private:
        std::vector<int> values;
};

我使用 vs2013 编译器,据我所知,它不支持 ref 限定符。如何移动安全?

Data d;
std::vector<int> v1;
std::vector<int> v2;
...
v1=d.getValues(); //i want copy
v2=std::move(d.getValues());  // i want move

只需通过正常引用返回:

class Data
{
public:
    const std::vector<int>& getValues() const {return values;}
    std::vector<int>& getValues() {return values;}
    // And if you really want to move member, you may do
    std::vector<int> takeValues() {return std::move(values);}
private:
    std::vector<int> values;
};

然后你可以使用

Data d;
std::vector<int> v1;
std::vector<int> v2;
//...
v1 = d.getValues(); // copy
v2 = std::move(d.getValues()); // move
// Or alternatively:
v2 = d.takeValues(); // move
相关文章: