Is there a way to move already initialized data into a std::vector
?
Here's my own simple vec
class:
template<typename T>
class vec final
{
std::unique_ptr<T[]> pValues;
size_t size = 0;
public:
std::span<T> span() const { return std::span<int>(pValues.get(), size); }
vec(T* p, size_t sz) : size(sz) { pValues.reset(p); }
};
As you can see, it will take ownership of the memory passed to it:
int main()
{
constexpr size_t count = 99;
auto orig = std::make_unique<int[]>(count);
{
std::span<int> orig_(orig.get(), count);
std::iota(orig_.begin(), orig_.end(), -1);
assert((orig_[0] == -1) && (orig_[1] == 0) && (orig_[98] == 97));
}
vec<int> nums(orig.release(), count);
auto nums_ = nums.span();
assert((nums_[0] == -1) && (nums_[1] == 0) && (nums_[98] == 97));
}
This all works "as desired," but I'd like to do something similar with std::vector
; in particular, I do not want to copy the data into a std::vector
(imagine count
being significantly larger than 99).
In other words, I'd like to do the "copy around some pointers" that (usually) happens when I std::move
one std::vector
to another; but the source is my own pointer. As my sample code shows, it's "easy" enough to do, but I don't want my own vec
.
When I'm done, I'd like to "traffic" in a std::vector
because that way I can completely forget about memory management (and having do further extend my own vec
class). Using a std::vector
also works well with existing C++ code that can't be changed.