0

I am trying to understand the usage of std::move. Could you please tell me if my reasoning is right? I consider the following class:

class T{
  public:
    T(string s){
        str = move(s);
    }
    string str;
};

Now let's consider two ways of using this class.

  1. T t("abc");

Here what happens is that string "abc" is first created, and then its resource is moved to t.str. Therefore string "abc" is never copied.

  1. string s = "abc"; T t(s);

Here, first, string s is created. Then a copy of s is passed by value to the constructor T(). Finally the resource of the copy of s is moved to t.str. In total "abc" is copied once.

Is this true?

5
  • 2
    In your first example, the characters are copied once. In the second, they are copied twice. There's no way for std::string to somehow share its storage with the string literal, with no copying, so at least one copy is inevitable. In the second example, there are two copies because in the end there are two named objects of type std::string, with the same contents. Commented Apr 18, 2020 at 22:31
  • 1
    Herb Sutter addresses this nicely in his 2014 CppCon talk "Back to the Basics!": youtu.be/xnqTKD8uD64?t=4310 Commented Apr 18, 2020 at 22:51
  • I think what you're looking for is a move constructor T(string&& s) : str(std::move(s)) {} Commented Apr 18, 2020 at 23:06
  • @IgorTandetnik Thanks, I think I see your point. Quick follow up: In the second case, if I initialized with string s("abc"); would your answer still be the same? Commented Apr 19, 2020 at 0:33
  • 1
    Yes. Makes no difference. Commented Apr 19, 2020 at 0:34

1 Answer 1

1

In your first case s is initialized from the char array "abc", and then s's resource is moved to t.str . Then s is destroyed.

In your second case the first s (why do people asking these questions always use the same variable name for two different things?) is initialized from the char array "abc". Then the function parameter s is initialized from the first s by copy-construction, and then function parameter s has its resource moved to t.str, and then function parameter s is destroyed.

Sign up to request clarification or add additional context in comments.

1 Comment

"why do people asking these questions always use the same variable name for two different things?" -> I realized that this makes answering the question harder. Sorry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.