Shouldn't line 12 cause an illegal access violation since the vector no longer exists? |
The move constructor doesn't affect the lifetime of the moved-from object at all.
(As a reminder, the lifetime of a object with class type, like
vec1, ends when its destructor begins. The move constructor doesn't call
vec1's destructor.)
Is the output at line 12 UB? |
By convention, a move assignment or move constructor leaves the moved-from object in an
unspecified but valid state. Therefore you can do anything to a moved-from object as long as you don't assume anything about it.
For example, if line 12 was
vec1.front(), that would be undefined behavior because
front assumes the vector has at least one element. But
vec1.size() is fine because
size doesn't assume anything.
Finally,
unspecified but valid does not always mean
empty, but the standard library does actually empty out stuff that's moved from. This can occasionally make it easier to reuse objects:
1 2 3 4 5 6 7 8 9 10
|
std::vector<std::vector<int>> matrix;
std::vector<int> row_vector;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 10; ++j)
row_vector.push_back(i*j);
matrix.push_back(std::move(row_vector));
// row_vector.clear() // redundant because row_vector is already empty here
}
| |