samedi 25 novembre 2017

Which constructor will trigger the move semantics?

I'm currently learning c++ and is wondering about the which one is the right way to use 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;
    }
}

What I'm confused about is which one will trigger the move constructor for std::vector ?

Is it this one (compile error when caller doesnt use std::move)

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

this one (accepts both std::move(Buff) and Buff) ?

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

or this one ?

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

My understanding from reading around the internet, that the 1st constructor is the correct way to utilize the move semantics. But if I use the 1st constructor does that mean I need to make another constructor if I want to actually do a copy on the std::vector Buff ?

Any help would be appreciated!

Aucun commentaire:

Enregistrer un commentaire