Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to call size() method on moved-from vector? [duplicate]

Standard specifies that STL containers, after begin moved (in this case we talk about std::move that enables move construction / assignment), are in valid, but unspecified state.

I belive that means we can only apply operations that require no preconditions. I recall that someone here, on Stackoverflow, claimed that to be true and after some checking I agreed. Unfortunately, I cannot recall what sources have I checked. Furthermore, I was not able to find relevant information in the standard.

From [container.requirements.general/4], table 62 ([tab:container.req]), we can see that a.size() has no preconditions. Does that mean this code is safe?

#include <iostream>
#include <vector>

int main() {
    std::vector<int> v1 = {1, 2, 3};
    std::vector<int> v2 = std::move(v1);

    std::cout << v1.size(); // displaying size of the moved-from vector
}

It's unspecified what will this code print, but is it safe? Meaning, do we have undefined behaviour here?

EDIT: I don't believe this question will be too broad if I ask abour other containers. Will the answer be consistent among all other STL containers, including std::string?

like image 780
Fureeish Avatar asked Mar 03 '23 17:03

Fureeish


1 Answers

There is no undefined behavior here, because of the lack of pre-conditions. The Standard guarantees that a moved-from container will be left in a valid but unspecified state. A valid state implies that anything that doesn't have preconditions can be invoked, but the result will be unpredictable.

So yeah, this is not UB, but definitely useless and a bad idea.

like image 64
Vittorio Romeo Avatar answered Apr 30 '23 10:04

Vittorio Romeo