Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a useful scenario for moving const objects?

I realized that the common-knowledge that "you cannot move a const object" is not entirely true. You can, if you declare the move ctor as

X(const X&&);

Full example below:

#include <iostream>

struct X
{
    X() = default;
    X(const X&&) {std::cout << "const move\n";}
};

int main()
{
    const X x{};
    X y{std::move(x)};
}

Live on Coliru

Question: is there any reason why one would want such a thing? Any useful/practical scenario?

like image 875
vsoftco Avatar asked Apr 18 '17 19:04

vsoftco


People also ask

Can a const object be moved?

A move constructor requires the modification of the original object and since that object is const you cannot move so it calls the copy constructor instead.

Can you move a const variable?

Expert #2: “You cannot move from a variable marked as const, and instead the copy-constructor/assignment will be invoked more often.

When should we use std :: move?

std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object. In particular, std::move produces an xvalue expression that identifies its argument t . It is exactly equivalent to a static_cast to an rvalue reference type.

Does C++ automatically move?

That's pretty much the only time you should write std::move , because C++ already uses move automatically when copying from an object it knows will never be used again, such as a temporary object or a local variable being returned or thrown from a function.


1 Answers

Your example doesn't move anything. Yes, you wrote std::move to get an rvalue and you invoked a move constructor, but nothing actually ends up getting moved. And it can't, because the object is const.

Unless the members you were interested in were marked mutable, you would not be able to do any "moving". So, there is no useful or even possible scenario.

like image 148
Lightness Races in Orbit Avatar answered Nov 12 '22 04:11

Lightness Races in Orbit