Daniel Vlasenko Daniel Vlasenko - 3 months ago 14
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

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;
Comments