簡體   English   中英

std :: move如何應用於函數的返回值?

[英]How std::move applied on function return value?

在測試以下代碼段時,這里我采用一個字符串向量,並嘗試使用std::move(vector)返回它。 如果我正在使用像這樣的成員函數簽名std::vector<std::string>&& getVector()那么它的工作正常。 如果我正在使用此std::vector<std::string>& getVector()則它不會移動/清除向量內容。

請讓我知道要遵循的正確動作語義。 並且請解釋兩個代碼之間的區別。

代碼:

#include <iostream>
#include <vector>
#include <string>

class VectorMoveDemo
{
public:
    void add(std::string item)
    {
        results_.push_back(item);
    }
    std::vector<std::string>& getVector()
    {
        return std::move(results_);
    }
private:
    std::vector<std::string> results_;
};

int main()
{
    VectorMoveDemo v;
    v.add("Hello ");

    std::cout << "First Time : " << "\n";
    std::vector<std::string> temp = v.getVector();
    for(auto &item : temp)
    {
        std::cout << item << "\n";
    }
    std::cout << "Second Time : " << "\n";

    v.add("World");

    std::vector<std::string> temp2 = v.getVector();
    for(auto &item : temp2)
    {
        std::cout << item << "\n";
    }
}

第一:

std::vector<std::string>& getVector()
{
    return std::move(results_);
}

輸出:

First Time :
Hello
Second Time :
Hello
World

第二

std::vector<std::string>&& getVector()
{
    return std::move(results_);
}

輸出:

First Time :
Hello
Second Time :
Hello
World

任何幫助將非常感激。

我想在向量中添加新值之前清除以前的向量值。 在這里, getVector()應該清空向量內容。

在這種情況下,根本不需要std::move

std::vector<std::string> getVector()
{
    std::vector<std::string> temp;
    temp.swap(results_);
    return temp;
}

但是,您可以在其他成員函數中使用std::move

void add(std::string item)
{
    results_.push_back(std::move(item));
}

暫無
暫無

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

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