c++ - static_cast 到右值引用和 std::move 在初始化中更改它们的参数

标签 c++ rvalue-reference static-cast

下面的简单代码表明,static_cast 为右值引用类型和 std::move 可能会根据获取的对象的类型在初始化语句中更改它们的输入参数(此处为变量 inupt)初始化。有人可以解释这种行为吗?

我至少很高兴 static_cast 和 std::move 的行为相似,因为 std::move 确实在幕后使用了 static_cast

#include <iostream>
#include <string>

int main() {

   {
      std::string input("hello");
      std::string&& result = static_cast<std::string&&>(input);
      std::cout << "cast case 1: input: " << input << " result: " << result << std::endl; // prints: cast case 1: input: hello result: hello
   } 

   {
      std::string input("hello");
      std::string result = static_cast<std::string&&>(input);
      std::cout << "cast case 2: input: " << input << " result: " << result << std::endl; // prints: cast case 2: input:  result: hello
   }

   {
      std::string input("hello");
      static_cast<std::string&&>(input);
      std::cout << "cast case 3: input: " << input << std::endl; // prints: cast case 3: input: hello
   }

   {
      std::string input("hello");
      std::string&& result = std::move(input);
      std::cout << "move case 1: input: " << input << " result: " << result << std::endl; 
      // prints: move case 1: input: hello result: hello
   } 

   {
      std::string input("hello");
      std::string result = std::move(input);
      std::cout << "move case 2: input: " << input << " result: " << result << std::endl; 
      // prints: move case 2: input:  result: hello
   }

   {
      std::string input("hello");
      std::move(input);
      std::cout << "move case 3: input: " << input << std::endl; 
      // prints: move case 3: input: hello
   }

}

最佳答案

您观察到的行为不足为奇且合情合理。

当你使用

  std::string result = static_cast<std::string&&>(input);

调用移动构造函数来初始化result。移动构造函数移动 input 的内容到result 是有道理的。

对比

  std::string&& result = static_cast<std::string&&>(input);

这里,result 不是新对象。它只是 input 的右值引用。这里没有任何内容需要移动 input 的内容。

关于c++ - static_cast 到右值引用和 std::move 在初始化中更改它们的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57187928/

相关文章:

c++ - 缓存 CAtlList 对象的 POSITION 对象是否安全?

c++ - 如何将文件中的长字符串读入数组或类似的东西?

c++ - std::forward 如何接收正确的参数?

c++11 - 什么是函数类型的右值引用?

c++ - 基于值(value)的向上转型

c++ - 如何使用笛卡尔积将 vector 元组转换为元组 vector ?

c++ - 在glsl中初始化全局变量?

c++ - 无法从 Type* 转换为 Type&&

c++ - 为什么编译器在将函数 static_cast(ing) 为 void* 时表现不同?

c++ - static_cast 抛出错误,但 C 风格的转换有效