Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does putting data into std::vector in C++ create a copy of the data?

I am interested if creating a new std::vector (or calling its assign method) creates a copy of the data?

For example,

void fun(char *input) {
    std::vector<char> v(input, input+strlen(input));
    // is it safe to assume that the data input points to was COPIED into v?
}
like image 214
bodacydo Avatar asked Nov 30 '22 18:11

bodacydo


2 Answers

Yes. Elements are always copied into or out of STL containers. (At least until move semantics are added in C++0x)

EDIT: Here's how you can test for copying yourself:

#include <vector>
#include <iostream>

class CopyChecker
{
public:
    CopyChecker()
    {
        std::cout << "Hey, look! A new copy checker!" << std::endl;
    }
    CopyChecker(const CopyChecker& other)
    {
        std::cout << "I'm the copy checker! No, I am! Wait, the"
            " two of us are the same!" << std::endl;
    }
    ~CopyChecker()
    {
        std::cout << "Erroap=02-0304-231~No Carrier" << std::endl;
    }
};

int main()
{
    std::vector<CopyChecker> doICopy;
    doICopy.push_back(CopyChecker());
}

The output should be:

Hey, look! A new copy checker!
I'm the copy checker! No, I am! Wait, the two of us are the same!
Erroap=02-0304-231~No Carrier
Erroap=02-0304-231~No Carrier

like image 90
Billy ONeal Avatar answered Dec 04 '22 13:12

Billy ONeal


Elements are always copied into or out of STL containers.

Although the element may just be a pointer, in which case the pointer is copied but not the underlying data

like image 31
Martin Beckett Avatar answered Dec 04 '22 14:12

Martin Beckett