Give a std::vector ownership of another vector's memory?

Ann*_*inn 1 c++ optimization vector

I have a constructor that looks like this:

Thing::Thing(std::vector<uint8> & data){
    m_data = data; // m_data is also a vector<uint8>
    // do other stuff
}
Run Code Online (Sandbox Code Playgroud)

However, data holds a pretty large chunk of memory, and instead of copying it, I'd like data to simply give it up to m_data, as the caller will never need it after constructing this object. What's the best way to do this in C++?

R S*_*ahu 6

You can use the move assignment operator.

m_data = std::move(data);
Run Code Online (Sandbox Code Playgroud)

It will be better to change the argument type to a value or an rvalue reference so that the user of the function is not surprised that the contents of the input argument have been moved.

Thing::Thing(std::vector<uint8>&& data){
    m_data = std::move(data);
    // do other stuff
}
Run Code Online (Sandbox Code Playgroud)

Given that, the calling function will be aware that they need to pass an rvalue reference and won't be surprised by the move of the contents.

It will be better to initialize m_data using data instead of assigning to it.

Thing::Thing(std::vector<uint8>&& data) : m_data(std::move(data))
{
    // do other stuff
}
Run Code Online (Sandbox Code Playgroud)

  • 请建议他们按值或右值引用传递。否则,不清楚所有权是否正在转移。另外,作为构造函数,您应该使用类成员初始化列表。 (2认同)