为什么不是这里调用的std :: string&#39移动构造函数?

时间:2018-05-29 16:14:45

标签: c++ move

我有这段代码:

#include <iostream>
#include <string>

using namespace std;

class S
{
public:

  S(std::string && s)
  : str(std::move(s))
  {
  }

  /* Why does a copy of s happen somewhere in here? */
  S(std::string && s, bool dummyArg)
  : str(s)
  {
  }

  void printVal() const
  {
    cout << "S::s is \"" << str << "\"\n";
  }

private:
  string str;
};


int main(int argc, const char * argv[])
{
  string str1{"Some string that I want to move into S"};
  string str2{"Some other string that I want to move into S"};

  // S s0{str1}; // Does not compile because no constructor matches
  S s1{std::move(str1)};
  S s2{std::move(str2), false};

  s1.printVal();
  cout << "str1 is: \"" << str1 << "\"\n";

  cout << "\n";

  s2.printVal();
  cout << "str2 is : \"" << str2 << "\"\n";
}

产生以下输出:(使用Clang(XCode 9)编译)

S::s is "Some string that I want to move into S"
str1 is: ""

S::s is "Some other string that I want to move into S"
str2 is : "Some other string that I want to move into S"

因此,我们可以清楚地看到,在使用第二个构造函数时,str2并未移至S::str。我不明白为什么添加std::move会产生影响,因为std::move只是对其参数执行static_cast<T&&>,这已经是构造函数的类型。

0 个答案:

没有答案