Home > Enterprise >  Passing the const-qualified object to the 'std::move'
Passing the const-qualified object to the 'std::move'

Time:12-19

By doing some code analysis in PVS-Studio, it gave me some warning messages.

I have the following statement in a header file:

constexpr int MIN_ALLOWED_Y { 0 };

And in a source file:

std::make_pair<const int, const int>( std::move( MIN_ALLOWED_Y ), std::move( MAX_ALLOWED_Y ) )

In the above expression, I used std::move to cast MIN_ALLOWED_Y to an xvalue because I thought std::make_pair only accepts rvalues;

// from https://en.cppreference.com/w/cpp/utility/pair/make_pair

template< class T1, class T2 >
constexpr std::pair<V1,V2> make_pair( T1&& t, T2&& u );

But I get warning messages like:

V833 Passing the const-qualified object 'MIN_ALLOWED_Y' to the 'std::move' function disables move semantics.

Is this a valid warning? If so then what should I do? Should I remove the std::move (maybe it's redundant in this case?)?

A better question would be where not to use std::move?

CodePudding user response:

Your code:

std::make_pair<const int, const int>( std::move( MIN_ALLOWED_Y ), std::move( MAX_ALLOWED_Y ) )

Is overly complicated. Not only are the moves pointless as PVS Studio told you, but using make_pair when explicitly specifying the types is pointless. You can simplify to:

std::pair<const int, const int>( MIN_ALLOWED_Y, MAX_ALLOWED_Y )

Which does the same thing without excess ceremony.

CodePudding user response:

It sounds like you wrote std::move(MIN_ALLOWED_Y) somewhere and you got a warning about it from a static analyzer. Yes, I would remove the std::move because it doesn't make any sense to move a constant somewhere else.

Move semantics are for moving around C objects where it might impossible or expensive to copy the data/resources contained in the object. The object that was the source of the data in the move operation is possibly changed by the move, but it's impossible for your constant to change.

  • Related