Move std :: vector <T> to T *

all I have some legacy code that 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 not to copy it to int *. Is there any way to do this? I tried the following:

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

Well, values points to the beginning of the vec, internal array , but it is destroyed when vec goes beyond. But I have to keep it.

 &vec[0] = nullptr; // does not compile of course 

So, the question is, can the semantics of displacement be applied in this case? Or maybe some other trick?

+4
source share
2 answers

Short answer: no, there is no way to transfer ownership of the vector buffer outside vector .

I think your best option is to make sure that vector just doesn't die using the wrapper:

 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 &vec_[0] . This will remain constant if / until you add more elements to the vector (so you have to use caution to make sure that resizing the vector does not cause problems).

+5
source

Yup, you can do it - with a little 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 operation vector.swap does not copy int.

+4
source

All Articles