If I have a pointer to a vector, does inserting invalidate it

时间:2016-07-11 19:43:32

标签: c++ vector

Suppose I have the following code:

std::vector<std::string>* vs = new std::vector<std::string>;
vs->push_back(string("Hello"));
vs->push_back(string("World"));

Does do this invalidate the pointer vs? Or more specifically,

void doSomething(std::vector<std::string>* vs) {
    vs->push_back(string("thisWasATriumph"));
    if (vs->size() < 3) {
        doSomething(vs);
    }
}
int main() {
    std::vector<std::string>* vs = new std::vector<std::string>;
    doSomething(vs);
    std::cout << vs->back() << endl;
}

Will the call to doSomething(vs) have the element in it that was previously inserted?

4 个答案:

答案 0 :(得分:5)

Does do this invalidate the pointer vs?

No it doesn't invalidate the pointer to the vector itself (having such is pretty silly in most cases BTW1).

You are probably confusing that with the invalidation of any std::vector<>::iterator values, as it's stated in the documentation:

If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.


Will the call to doSomething(vs) have the element in it that was previously inserted?

Yes.


It's probably better, to simply use a reference, and don't use new at all:

void doSomething(std::vector<std::string>& vs) {
                                      // ^
    vs.push_back(string("thisWasATriumph"));
    if (vs.size() < 3) {
        doSomething(vs);
    }
}

int main() {
    std::vector<std::string> vs; // = new std::vector<std::string>;
                                 // ^^^^^^^^^^ No need or this
    doSomething(vs);
    std::cout << vs->back() << endl;
}

1)There's little to no advantage to dynamically allocate a std::vector. Just use a plain local or member variable with automatic memory allocation.

答案 1 :(得分:2)

No, it does not.

Calling a method on an object will not cause it to move around in memory (barring extreme special cases like methods which delete the object they were called on, but this is very rare).

答案 2 :(得分:1)

No, it doesn't invalidate your vector<string>*.

It's possible to achieve same functionality with references.

void doSomething(std::vector<std::string>& vs) {
    vs.push_back("thisWasATriumph");
    if (vs.size() < 3) {
        doSomething(vs);
    }
}

int main() {
    std::vector<std::string> vs;
    doSomething(vs);
    std::cout << vs.back() << endl;
}

答案 3 :(得分:0)

No. Insert invalidate iterators but not the pointer to the object