【发布时间】:2021-10-07 04:04:07
【问题描述】:
我的问题包含两个部分:
-
函数
static_cast<Т>(arg)会改变arg的内部结构吗?显然不是,根据这样的代码:float i1 = 11.5; int x = static_cast<int>(i1); std::cout << i1<<std::endl; //11.5 std::cout << x<<std::endl; //11 -
为什么会有这样的代码:
std::string s1 = "123"; std::string s2 = std::move(s1); std::cout << s1 << std::endl; //empty std::cout << s2 << std::endl; //123其中
std::move()仅使用static_cast到右值:template<typename _Tp> constexpr typename std::remove_reference<_Tp>::type&& move(_Tp&& __t) noexcept { return static_cast<typename std::remove_reference<_Tp>::type&&>(__t); }将
s1设为空字符串?
我猜,是因为在s2 =之后使用了字符串的move构造函数。它必须通过将字符串对象中的所有数据等同于nullptr 或 0 来擦除初始字符串。而std::move() 本身只返回右值。对吗?
我知道我的问题与 static_cast to r-value references and std::move change their argument in an initialization 类似,但我没有找到明确的解释。
【问题讨论】:
-
改变
s1的不是std::move或static_cast,而是用于初始化s2的string(string&&)构造函数。这是移动语义的重点。自己看看——如果你只是单独写std::move(s1);,s1将保持不变。
标签: c++ rvalue static-cast stdmove