Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return const value prevent move semantics

Tags:

c++

I am a beginner in cpp so excuse me for this question.

I was reading that returning const val prevents move semantics. therefore I dont understand why the following code is compiled and works normally. is it because only temporary object is being created? in what cases the move semantics cannot being done? thank you in advance!

#include <iostream>
using namespace std;

const string foo()
{
    return string("hello");
}

int main()
{
    string other = std::move(foo());
}
like image 317
Nissim Levy Avatar asked Jan 28 '26 19:01

Nissim Levy


2 Answers

std::move is just a unconditional cast to rvalue. In your case the return value of std::move(foo()) was const std::string&&. And because move constructor does not take const argument, copy constructor was called instead.

struct C {
    C() { std::cout << "constructor" << std::endl; }
    C(const C& other) { std::cout << "copy constructor" << std::endl; }
    C(C&& other) { std::cout << "move constructor" << std::endl; }
};

const C get() {
    return C();
}

int main() {
    C c(std::move(get()));
    return 0;
}
like image 59
Ashwani Avatar answered Jan 31 '26 11:01

Ashwani


std::move doesn't actually move anything. It is just an "rvalue cast". You cast something to rvalue, and the move constructor / move assignment operator does the actual moving if possible. "If possible" part is the key. In your example the return value is already an rvalue, so std::move literally does nothing. You may even get warnings like "nothing is moved". That is because the move constructor of std::string takes an argument of type std::string&& not const std::string&&. Because of that, the copy constructor is called.

like image 32
Ayxan Haqverdili Avatar answered Jan 31 '26 10:01

Ayxan Haqverdili



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!