哪个构造函数会触发移动语义?

时间:2017-11-25 21:18:11

标签: c++ c++11 move-semantics

我目前正在学习c ++,并且想知道哪一个是使用std :: move的正确方法

select numeric_value
from table
where numeric_value >
(select avg(numeric_value)
from table
group by id)

我感到困惑的是哪一个会触发std :: vector的移动构造函数?

这是一个(当调用者不使用std :: move时编译错误)

//Code might be incorrect since I havent tested it out
Xyt::ByteArray* Xyt::ResourceManager::LoadFileToByteArray(std::string Path)
{
try {
    std::ifstream FileStream(Path, std::ios::in);
    std::ifstream::pos_type Pos = FileStream.tellg();

    FileStream.seekg(0, std::ios::beg);

    std::vector<char> Buff(Pos);
    FileStream.read(Buff.data(), Pos);

    FileStream.close();

    //I want to trigger the move constructor here
    return new Xyt::ByteArray(std::move(Buff));
}
catch (std::exception e) {
    std::cout << "ERROR::FILE::FILE_NOT_SUCCESFULLY_READ" << Path << std::endl;
    return nullptr;
    }
}

这个(同时接受std :: move(Buff)和Buff)?

Xyt::ByteArray::ByteArray(std::vector<char>&& Buffer)
{
    this->Buffer = Buffer;
}

还是这个?

Xyt::ByteArray::ByteArray(std::vector<char> Buffer)
{
    this->Buffer = Buffer;
}

我从阅读互联网的理解,第一个构造函数是使用移动语义的正确方法。但是,如果我使用第一个构造函数,这意味着我需要创建另一个构造函数,如果我想在std :: vector Buff上实际复制一个?

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

唯一有效的是第三个。但那是因为您在构造函数中使用了std::move 。它引发了两个动作:一个用于填充参数,另一个用于参数到值。

正确的方法是:

Xyt::ByteArray::ByteArray(std::vector<char>&& Buf)
  : Buffer(std::move(Buf))
{}

这只会调用一次移动操作。

如果要调用移动操作,则必须显式移动命名的右值引用。

  

但是,如果我使用第一个构造函数,这意味着我需要创建另一个构造函数,如果我想在std :: vector Buff上实际复制一个?

你不是必须的。您可以要求用户在调用函数时自行进行复制:

Xyt::ByteArray(std::vector<char>(Buff))

但是,是的,如果您希望用户直接提供左值,并且您想要从左值复制,那么您需要提供一个构造函数,该构造函数接受(const)左值引用并执行副本。 / p>

相关问题