1.Passing by Value
函数形参的声明 是pass by value
void foo(std::string str); // takes the object by value
std::string s{"hello"};
...
foo(s); // calls foo(), str becomes a copy of s
foo(std::move(s)); // calls foo(), s is moved to str
foo(returnStringByValue());
// calls foo(), return value is moved to str
一段测试代码
void Fun(MyString Temp)
{
cout << (int)Temp.pStr << endl;
cout << "6666" << endl;
}
MyString Fun1()
{
MyString b(2, "12");
cout << (int)b.pStr << endl;
return b;
}
int main(void)
{
MyString a(5, "Hello");
cout <<"a" << a << endl;
MyString B = std::move(a);
cout << (int)B.pStr << endl;
Fun(std::move(B));
Fun(Fun1());
return 0;
}
运行结果表示 在pass-by-value的时候,使用std::move()实参,会创建一个新的对象,该对象调用std::move()
函数返回来的右值,也是如此
2.
void fooByVal(std::string str);
// takes the object by value
void fooByRRef(std::string&& str);
// takes the object by rvalue reference
...
std::string s1{"hello"}, s2{"hello"};
...
fooByVal(std::move(s1)); // s1 is moved
fooByRRef(std::move(s2)); // s2 might be moved
①string by value 肯定会调用移动构造
先创建一个新的对象,然后调用移动构造
②string by rvalue reference 会不会调用,这取决于编译器的行为,反正VS2019下面不会调用,str和s2的地址相同
3.总结
①右值引用被&&修饰 且没有 const
②可以被临时无名对象初始化 或者 没有被const修饰的被std::move标志的
③return by value对象的生存周期被右值引用拓展了
④Std::move()是一个static_cast到相应的右值引用类型
⑤被std::move标记的对象 也可以传给一个const lvalue reference形参
但是不能给一个 lvalue reference形参
⑥被std::move标记的对象,也可以传给一个 value的形参,也就是
pass by value ,会调用移动构造
⑦const rvalue reference 没什么卵用
⑧移动后的对象,尽量就不要在使用了