I’m... too obsessed with std::move?

Ok so as far as I’ve read, then entire point of adding the type type&& was to allow for just a quick transfer of data like without copying for when you no longer need the original object yes? It’s for identifying times when you want that kind of thing, so I was wondering, does that mean that I should always move my return object? It [i]sounds[/s] like a good idea in my head, but I have a feeling I would have seen someone doing it if it was so great so like what’s the deal there why is it not a thing am I just getting a little too obsessed?

1
2
3
4
5
6
7
8
  std::string func()
  {
    std::string result;
    // code
    return std::move(result);
  }
  //...
  std::string s = std::move(func());
NO. Please don't use move() for return. C++ now does copy elision for returned objects. See https://en.cppreference.com/w/cpp/language/copy_elision

If move() is specified then this can impact upon compiler optimisation. See https://stackoverflow.com/questions/17473753/c11-return-value-optimization-or-move

1
2
3
4
5
6
7
8
std::string func()
  {
    std::string result;
    // code
    return result;
  }
  //...
  std::string s = func();


If you look at the addresses used then you'll see that no copy has taken place. Eg:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
std::string func()
{
	std::string result;

	std::cout << (int)result.data() << std::endl;
	return result;
}

int main()
{
	std::string s = func();

	std::cout << (int)s.data() << std::endl;
}


On my computer shows:
1
2
1638168
1638168


showing that no copy has taken place.

If move is used:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
std::string func()
{
	std::string result;

	std::cout << (int)result.data() << std::endl;
	return move(result);
}

int main()
{
	std::string s = func();

	std::cout << (int)s.data() << std::endl;
}


Then the display is:

1
2
1638112
1638168


which is probably not what is wanted or intended.
Last edited on
Ahhh ok ok I see thanks :)
Topic archived. No new replies allowed.