|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
|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:
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 10; ++j)
// row_vector.clear() // redundant because row_vector is already empty here