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

initialization by std::move(param)

48 views
Skip to first unread message

quanzhou

unread,
Mar 17, 2023, 2:34:47 AM3/17/23
to
Hi Experts,

I have a question, for type like:

struct A
{
int num = 0;
std::string text {};
};

A a{13, "hi"};
A b = std::move(a);

after this, what is the value of a.num?
I know most probable answer is 13, since "move of builtin types is copy", but does standard document give any guarantee that b.num are for sure read-accessed?

Or unspecified?


Thanks,
Anhong

Bonita Montero

unread,
Mar 17, 2023, 4:25:29 AM3/17/23
to
The implicit move moves only moveable objects. b.num is still 13.
Implicit moves are only generated if all of the following methods
are not given:

there are no user-declared copy constructors;
there are no user-declared copy assignment operators;
there are no user-declared move assignment operators;
there is no user-declared destructor.

(from en.cppreference.com)

Öö Tiib

unread,
Mar 17, 2023, 6:44:40 AM3/17/23
to
The num is 13, text is in valid but unspecified state.

Again one such place where standard could require that text
is empty without any harm done to performance of anything
as in lot of existing implementations the text member is
empty.

Malcolm McLean

unread,
Mar 17, 2023, 8:45:58 AM3/17/23
to
You're abusing the system by accessing a.num after the move, except for the purpose of destroying a.
However it's not C-style "undefined behaviour". std::move converts an l-value to an r-value, which
esnures that the move constructor, if it exists, is called. That's all it does. Whilst for commonsense
purposes you can say "a is invalid because of the std::move", this isn't actually what happens.

Andrey Tarasevich

unread,
Mar 17, 2023, 5:17:45 PM3/17/23
to
Yes, it is guaranteed to be 13 post-move. The language guarantees that
move-semantics for scalar types boils down to classic copy-semantics.

--
Best regards,
Andrey
0 new messages