1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Copying from std::vector to memory buffer

Discussion in 'C++' started by tron_thomas, Sep 1, 2010.

  1. tron_thomas

    tron_thomas New Member

    Sep 1, 2010
    Likes Received:
    Trophy Points:
    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 source; // Initalized to hold the objects
    ObjectType* target = reinterpret_cast(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?
  2. techgeek.in

    techgeek.in New Member

    Dec 20, 2009
    Likes Received:
    Trophy Points:
    EOC (exploitation of computers)..i m a Terminator.
    Not an alien!! for sure
    Home Page:
    i think u need
    Your problem would be solve then...

Share This Page