Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Still usable after having been moved?

28 views
Skip to first unread message

Frederick Virchanza Gotham

unread,
Jul 12, 2023, 5:51:22 PM7/12/23
to
Link to GodBolt:

https://godbolt.org/z/KjEbGPWMT

And here it is copy-pasted:

#include <sstream>
#include <iostream>
#include <utility>

using std::stringstream, std::cout, std::endl;

void Func(std::stringstream &&arg)
{
static std::stringstream obj;

obj = std::move(arg);

cout << obj.str() << endl;
}

int main(void)
{
std::stringstream ss;

for ( unsigned i = 0u; i < 8u; ++i )
{
ss << i;

Func( std::move(ss) );
}
}


Should this code work properly on every implementation of the C++23 standard?

Alf P. Steinbach

unread,
Jul 13, 2023, 6:04:22 AM7/13/23
to
Yes, with a proper definition of "properly".

I doubt that you're guaranteed that `ss` retains its original state
after being moved from.

All you're guaranteed in general, is that the object is in a valid
state, i.e. that the class invariant is preserved.

---

Not what you're asking but regarding styles/conventions to me it seems
inconsistent to have a `using`-declaration of various things and then
refer to these things with namespace qualification.

Also inconsistent with C-ish `(void)` parameter list and C-ish type
builder operator attached to the declared name, in C++.


- Alf

Malcolm McLean

unread,
Jul 13, 2023, 6:12:27 AM7/13/23
to
No. After an std::move() the only legal operations on an object are to assign it a new value,
or to destroy it. The object is in a well-formed but invalid state. Exactly what depends on
the implementation of the move constructor, and so if you implement the class yourself,
you can abuse the system and still write defined C++. But not if you use a class provided
by someone else.

Alf P. Steinbach

unread,
Jul 13, 2023, 10:48:50 AM7/13/23
to
No. Current standard draft, <url:
https://eel.is/c++draft/lib.types.movedfrom>

<<
16.4.6.15 Moved-from state of library types[lib.types.movedfrom]
1 Objects of types defined in the C++ standard library may be moved from
([class.copy.ctor]). 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.
2 An object of a type defined in the C++ standard library may be
move-assigned ([class.copy.assign]) to itself. Unless otherwise
specified, such an assignment places the object in a valid but
unspecified state.
>>

- Alf


0 new messages