iamvegan
iamvegan

Reputation: 492

Understanding `std::move` in a constructor

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?

Upvotes: 0

Views: 73

Answers (1)

M.M
M.M

Reputation: 141544

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.

Upvotes: 1

Related Questions