为什么 std::move() 中的 static_cast 会擦除参数的值?

问题描述

我的问题包含两部分:

  1. 函数 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
    
  2. 为什么会有这样的代码:

    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 到 r 值:

    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 =之后使用了字符串的移动构造函数。它必须通过将字符串对象中的所有数据等于 nullptr 或 0 来擦除初始字符串。而 std::move() 本身仅返回右值。正确吗?

我知道我的问题与 static_cast to r-value references and std::move change their argument in an initialization 类似,但我没有找到明确的解释。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)