Johan Lundberg
Johan Lundberg

Reputation: 27038

is it legal to call .clear(), .shrink_to_fit(), .empty() on a moved from std::vector?

As a specific subcase of these two questions:

Is a moved-from vector always empty?

What can I do with a moved-from object?

one wonders: Is it legal to call .clear(), .chrink_to_fit(), .empty() on a moved-from std::vector before assigning a new vector to it? I could ask about push_back() but I don't know what that would give, since it's not safe to rely on a moved from vector being empty.

What is clear is that destruction, as well as assignment from a new vector is legal.

std::vector<int> fs = getVec();
giveVecs(std::move(fs));
fs.empty();  // 1.?
fs.size();   // 2.?
fs.shrink_to_fit(); // 3.?
fs.clear(); // //4. ?
fs = {} ; // 5. Should be fine, but weird when we have .clear()
fs.push_back(1); // 

Edit:

I should clarify, that some operations do have preconditions: Therefore, (as you can read in the other questions), not All operations are legal after a move.

My question can therefore be restated like this: Are there any preconditions on either of the three operations? One source of problems could be fine print related to the allocator of the moved from object.

Upvotes: 2

Views: 894

Answers (3)

Gem Taylor
Gem Taylor

Reputation: 5613

The legal but unspecified state might be truly empty (using internal buffer move); it might be the content of the moved-to container (using swap), it could be that it still has the memory from the moved-to container; but all the elements destructed, and size() reporting zero (swap & clear()).

Or it might be any number of other things I haven't thought of, but they should all look like valid states of the container.

Upvotes: 0

Stephen Newell
Stephen Newell

Reputation: 7828

A moved object is in a valid, but unspecified state. Through the magic of Google, the relevant part of the standard is 17.6.5.15 [lib.types.movedfrom]

Objects of types defined in the C++ standard library may be moved from (12.8). Move operations may be explicitly specified or implicitly generated. Unless otherwise specified, such moved-from objects shall be placed in a valid but unspecified state.

As to what's legal for a moved std::vector, it probably depends what the other function did to it. My hunch is that with most implementations you can do pretty much anything you want, but I don't believe that's guaranteed anywhere. It's possible that all the member functions will fail (valid could mean they don't crash, but the object effectively stays useless).

Upvotes: -1

druckermanly
druckermanly

Reputation: 2741

Yes. Moving an object leaves it in an unspecified, but valid state.

So you can call clear, shrink_to_fit, empty, push_back, etc.

But you should probably start with clear due to that unspecified qualifier :) .

Upvotes: 6

Related Questions