[英]Move std::vector<T> to T*
all I've a legacy code which in draft does something like this: 我所有的遗留代码都在草案中做了这样的事情:
// 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 can be huge and I need to avoid copying it to int*. vec可能很大,我需要避免将其复制到int *。 Is there a way to do it?
有办法吗? I tried following:
我试过以下:
// type of new operator explained in More Effective C++
LgStr->values = new (&vec[0])int[vec.size()];
Ok, values
points to the beginning of vec inner array, but it destroyed when vec is out of scope. 好的,
values
指向vec内部数组的开头, 但是当vec超出范围时它会被破坏。 But I have to keep it.. 但我必须保留它..
&vec[0] = nullptr; // does not compile of course
So question is: is it possible to apply move semantics in this case? 所以问题是:在这种情况下是否可以应用移动语义? Or maybe some other trick?
或者其他一些技巧?
The short answer is that no, there isn't any way to transfer ownership of a vector
's buffer outside the vector
. 简短的回答是没有,没有任何方式转移所有权
vector
的缓冲区外vector
。
I think your best option is to make sure that the vector
just doesn't die by using a wrapper: 我认为你最好的选择是通过使用包装器来确保
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_;
}
Then anytime you need to use values
, just assign it to &vec_[0]
. 然后,只要您需要使用
values
,只需将其分配给&vec_[0]
。 This will stay constant if/until you add more items to the vector
(so you will have to use care to make sure that vector resizes don't cause problems). 这将保持不变,如果/直到你添加更多的项目到
vector
(所以你必须要谨慎,注意确保矢量大小调整不会造成问题)。
Yup, you can do so - with a small trick: 是的,你可以这样做 - 用一个小技巧:
struct LegacyStruct {
std::vector<int> backingStore;
int* values;
LegacyStruct(std::vector<int>& aSource) {
// Steal memory
aSource.swap(backingStore);
// Set pointer
values = &backingStore[0];
};
}
The vector.swap
operation doesn't copy the ints. vector.swap
操作不会复制整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.