I have the following case:
T* get_somthing(){
std::vector vec; //T is trivally-copyable
//fill vec
T* temp = new T[vec.size()];
memc
P.S. Changing the design is not an option. Using the std::vector there is mandatory. Returning a pointer to array is also mandatory.
Changing the design is your best option. I recommend reconsidering this stance.
There is (currently†) no way to "steal" the buffer of a vector, so given the (silly††) limitations stated in the question, copying is the way to go.
† Tomasz Lewowski linked a proposal that would change this if it is included in a future standard: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4359.pdf (Edit: as pointed out, it was rejected from c++17)
†† Silly until justified by concrete requirements.
It is a wrapper between two modules. One need vector the other need pointer.
Presumably, the other interface that needs the pointer, delegates the destruction of the buffer to the caller, possibly using some sort of call back like void delete_somthing(T*)
. Taking ownership without giving it back would have been very bad design, in my opinion.
In case you do have control of the destruction, you can store the vector in a map, and erase the vector, when the pointer is passed for destruction:
std::unordered_map> storage;
T* get_somthing(){
std::vector vec; //T is trivally-copyable
//fill vec
T* ptr = vec.data();
storage[ptr] = std::move(vec);
return ptr;
}
void delete_somthing(T* ptr){
storage.erase(ptr);
}