I have a situation whereby I need to copy the contents of an STL vector into a memory buffer provided by the system. One might think that given:

std::vector<ObjectType> source; // Initalized to hold the objects
ObjectType* target = reinterpret_cast<ObjectType*>(buffer); // Points to system provided memory buffer

someone could do the following:

std::copy(source.begin(), source.end(), target);

This can be problematic, however, because ObjectType is a complex class whose instances contain instances of other classes. The memory buffer from the system is raw memory which does not have properly constructed objects in it, so the copy algorithm would be performing an assignment to an improperly constructed ObjectTypes.

One way to work around this would be something like the following:

const size_t COUNT = source.size();

for(size_t index = 0; COUNT > index; ++index, ++target){
    new(target) ObjectType(source[index]);
}

This technique uses placement new and the copy constructor to create copies of the items from the vector into the memory buffer. This will work as ObjectType does have a valid, public copy constructor.

I'm wondering if a more elegant solution can be developed that can still allow the use of the std::copy algorithm to accomplish this task. Perhaps someone could use an object similar to std::inserter and can be used on an array, like maybe some sort of replacer object that does the job of the placement new operator in the above loop when called in something like the copy algorithm.

I'm wondering if such an object already exists, that someone can make use of. If something doesn't exist, I'm wondering how practical it would be to create such a thing.

Also, perhaps there is another way to solve the problem that doesn't involve anything suggested so far.

What do people suggest for solving this problem?

Recommended Answers

All 2 Replies

I think you want std::uninitialized_copy .

commented: good to know +2

Yes, arkoenig. That is exactly what I was looking for. Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.