将std :: vector <T>移动到T*

Igo*_*ack 4 c++ stl vector move-semantics c++11

我所有的遗留代码都在草案中做了这样的事情:

// sadly I have to use this structure
struct LegacyStruct {
  int* values;
}
LegacyStruct* LgStr;
....
    std::vector<int> vec;
    // fill vector in some way here  

    size_t sz = vec.size();
    LgStr->values = new int[sz];
    std::copy(vec.begin(), vec.end(), &LgStr->values[0]);
Run Code Online (Sandbox Code Playgroud)

vec可能很大,我需要避免将其复制到int*.有办法吗?我试过以下:

// type of new operator explained in More Effective C++
LgStr->values = new (&vec[0])int[vec.size()];
Run Code Online (Sandbox Code Playgroud)

好的,values指向vec内部数组的开头,但是当vec超出范围时它会被破坏.但我必须保留它..

&vec[0] = nullptr; // does not compile of course
Run Code Online (Sandbox Code Playgroud)

所以问题是:在这种情况下是否可以应用移动语义?或者其他一些技巧?

Mar*_*k B 6

简短的回答是,没有,没有任何方法可以将一个vector缓冲区的所有权转移到外面vector.

我认为你最好的选择是vector通过使用包装器来确保正常情况不会消失:

class LegacyStructWrapper : private boost::noncopyable  // Or declare private copy constructor/copy assignment or use `= delete` in C++11.
{
private:
    std::vector<int> vec_;
    LegacyStruct wrapped_;
}
Run Code Online (Sandbox Code Playgroud)

然后values,只要您需要使用它,只需将其分配给&vec_[0].如果/直到您添加更多项目vector(这样您不得不小心确保向量调整大小不会导致问题),这将保持不变.