0

I was browsing on cppreference.com recently and I happened to discover this page about std::move, a function I knew nothing about.

In this page, it is clearly stated that

Unless otherwise specified, all standard library objects that have been moved from are placed in a valid but unspecified state.

So the C++ standard doesn't guarantee anything about the content of the variable after a std::move. The part that is bugging me though is the "Unless otherwise specified".

What I would like to know is whether compilers such as GCC or Visual C++ provide any guarantee on the content of the variable? Some quick testing with a string in Visual Studio 2013 seemed to show that the string was always empty after the move operation.

Sunreef
  • 4,452
  • 21
  • 33

1 Answers1

0

Well, when the standard says, the state is not defined, then it is not defined. As @LogicStuff wrote, there are types with a defined state after being moved from, e.g. std::unique_ptr<>.

So the guarantee is, that the state is valid. That means, that all the methods can safely be called, though there is no guarantee, what they might return. Most of the time, you'll only want to call the destructor on these objects.

Also note, as many have said in the comments, that moving does not happen with std::move(). std::move() only returns the reference it gets as a rvalue reference. Move constructors and move assignment operators accept rvalue references as their parameters and do the actual moving.

Calling that function std::move() might seem suboptimal when you only look at its name. Looking at its use, the name is just perfect, because it tells the reader, that this time you want e.g. the move constructor to be called, not the copy constructor.

cdonat
  • 2,748
  • 16
  • 24
  • 1
    _all the methods can safely be called_. Methods **without preconditions**. – Revolver_Ocelot May 24 '16 at 19:09
  • @Revolver_Ocelot OK, methods that are as methods should be. I know, that even with the standard library that is not always perfect, but the rule should be, that as long as an object exists, all its methods can be called with a defined behavior. Here "defined" means, for every valid state of an object. It does not include how the object has reached that state. – cdonat May 24 '16 at 21:04