Daniel Vlasenko Daniel Vlasenko - 1 year ago 217
C++ Question

Assigning c-array to c++ vector

I have a question about lifetime of onstack created arrays and about transforming them to c++ vectors. For ex I have two functions:

void getVector()
auto myVector = createVectorFromArray();

vector<float> createVectorFromArray()
float myArr[10];
readDataFromSomewhere(myArr, 10); //some read data function with signature void(float*, size_t)
vector<float> resVector;
resVector.assign(myArr, myArr+10);
return resVector;

As I understand array myArr will be killed as soon as we leave function createVectorFromArray. So iterators of vector myVector in function getVector will point to nowhere. Am I right or this works in another way? And how should I better make vector from array to return it from function in this situation?

Thank you!

Answer Source

std::vector::assign here copies the contents of myArr into resVector so when myArr goes out of scope and you return resVector, it doesn't matter and will still contain the values.

An shorter way would be to do this would be to pass myArr, myArr + 10 to your vectors constructor like follows:

float myArr[10];
readDataFromSomewhere(myArr, 10);
vector<float> resVector(myArr, myArr + 10);
return resVector;

As stated by another answer here you could actually get rid of the array entirely like so:

vector<float> resVector(10);
readDataFromSomewhere(&resVector[0], 10);
return resVector;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download