4

Regarding move semantics and containers:

  1. I know STL containers take advantage of move when the move operations are defined in the elements type. But how does it know if an element has defined move operations or not?

  2. Why don't STL containers just invoke std::move() on the elements anyway, regardless of whether the element has defined the move operations or not? I'm asking this because I know you can invoke std::move() on objects even if its type does not define any move operations.

Thank you.

0

1 Answer 1

8

Long story short, that's exactly what they do, calling std::move without caring if it will be able to move or just copy.

It's worth noting that some functions offering the strong exception guarantee, such as std::vector::resize, will call the lesser known std::move_if_nothrow instead of std::move.

Sign up to request clarification or add additional context in comments.

4 Comments

I think this answers both parts of my question: STL containers don't actually detect whether the move operations for an element are defined or not, they just blindly call std::move_if_no_throw anyway and then use overload resolution to choose the move or copy version of a function. Please feel free to correct me if I have misunderstood something. Thanks.
Pedantic comment: The spirt of your answer is correct. However "calling move_if_noexcept instead of move most of the time" is inaccurate. Most of the time, the strong exception guarantee is not required nor supplied. vector in particular uses move_if_noexcept for a few operations such as reserve and push_back. I would call it the exception, not the rule, especially if we are talking about all std-defined containers. Most of the time, basic exception safety is required by the standard, and supplied by the implementations.
@HowardHinnant I do agree with your comment. Edited my answer to reflect it. Thank you!
@TiagoGomes: Now I have no choice but to up vote your answer. ;-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.