Angus Comber
Angus Comber

Reputation: 9708

If code changed to std::move(vector) will that save a copy operation in this function

The function is to extract the file contents into a vector as below:

std::vector<uint8_t> GetFileContents(const std::string& filename)
{
    std::ifstream file(filename, std::ios::binary);
    if (!file.good())
    {
        return {};
    }
    file.seekg(0, std::ios::end);
    std::streampos fileSize = file.tellg();
    file.seekg(0, std::ios::beg);

    std::vector<uint8_t> fileData(fileSize);
    file.read((char*) &fileData[0], fileSize);
    return fileData;
}

On the lines:

std::vector<uint8_t> fileData(fileSize);
file.read((char*) &fileData[0], fileSize);
return fileData;

The fileData vector is copied into a temporary vector to be returned here?

Do I need to change to:

std::vector<uint8_t> fileData(fileSize);
file.read((char*) &fileData[0], fileSize);
return std::move(fileData);

to do a move and save a vector copy operation?

Any other changes required in the function to support move?

Is there any value in std::move({}) for the empty case?

Upvotes: 0

Views: 74

Answers (1)

Jarod42
Jarod42

Reputation: 217293

No, you shouldn't use std::move there.

That avoids possible NRVO, and there is an implicit move anyway.

See Automatic_move_from_local_variables_and_parameters for further detail.

Upvotes: 7

Related Questions