全部 我有一个遗留代码,在草稿中做这样的事情:
// 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]);
vec 可能很大,我需要避免将它复制到 int*。 有办法吗? 我试过以下:
// type of new operator explained in More Effective C++
LgStr->values = new (&vec[0])int[vec.size()];
好的,values
指向 vec 内部数组的开头,但当 vec 超出范围时它被销毁了。但我必须保留它..
&vec[0] = nullptr; // does not compile of course
所以问题是:在这种情况下是否可以应用 move 语义? 还是其他一些技巧?
最佳答案
简短的回答是不,没有任何方法可以将 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_;
}
然后任何时候你需要使用values
,只需将它分配给&vec_[0]
。如果/直到您向 vector
添加更多项,这将保持不变(因此您将必须小心确保 vector 大小调整不会导致问题)。
关于c++ - 将 std::vector<T> move 到 T*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11102557/