Move std::vector<T> to T*
c++, c++11, move-semantics, stl, vector
Solution
The short answer is that no, there isn't any way to transfer ownership of a `vector`'s buffer outside the `vector`.
I think your best option is to make sure that the `vector` just doesn't die by using a 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 to `&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).
Problem
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*. 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. 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?