0x56794E 0x56794E - 1 month ago 7
C++ Question

C++ vector: push_back an array of int => Does array get copied?

I'm new to C++'s object lifetime, so bear with me.

I have a vector of dynamically allocated arrays of integers:

std::vector<int*>


This page says "The content of val is copied (or moved) to the new element."

What I understand from this is that what I push into the array MAY be moved or copied, but when is it moved and when is it copied?

I suspect the valued is copied if it's of primitive types? E.g., int, char, etc?

And it's copied otherwise? Does that means my array would be "moved"?

===================

EDIT 1: what I'm trying to find out is that suppose I pass the vector into a function. In this function I allocate an array of integers and push it into the vector. Once the function returns and I'm back to the caller, can I still safely access the array that was just pushed into the vector?

EDIT 2: some suggested using
vector<vector<int>>
, so my question became, if I pass the "parent" vector into some function. In this function, I create the inner vector and push it into the outer vector. When I'm back to the caller, can I still safely access the new inner vector that was just pushed into the outer vector?
Something like this:

void foo()
{
vector<vector<int>> parentV;
addVect(parentV);

//Is is safe to access parentV[0][0] here?
}


void addVect(vector<vector<int>> &parentV)
{
vector<int> child;
child.push_back(1);
child.push_back(2);
parentV.push_back(child);
}

Answer

some suggested using vector>, so my question became, if I pass the "parent" vector into some function. In this function, I create the inner vector and push it into the outer vector. When I'm back to the caller, can I still safely access the new inner vector that was just pushed into the outer vector?

void foo()
{
    vector<vector<int>> parentV;
    addVect(parentV);

    //Is the "child" vector still safe for access here?
}


void addVect(vector<vector<int>> &parentV)
{
    vector<int> child;
    child.push_back(1);
    child.push_back(2);
    parentV.push_back(child);
}

To answer:

Is the "child" vector still safe for access here?

No and yes.

No, not through the name child at least. child is local to addVect and thus foo won't know anything about it. It will be destroyed after addVect returns.

Yes, you can access it's values through parentV since they've been copied to parentV and you're passing parentV as reference.

auto copyOfChild = *parentV.rbegin(); //get the last vector since push_back adds to the end of the vector

or

auto copyOfChild = parentV[parentV.size() - 1]; //get the last vector since push_back adds to the end of the vector