首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >static_cast到r值引用和std::在初始化中移动它们的参数

static_cast到r值引用和std::在初始化中移动它们的参数
EN

Stack Overflow用户
提问于 2019-07-24 16:58:27
回答 2查看 272关注 0票数 0

下面的简单代码显示,static_cast到r值引用类型和std::move可能会根据被初始化对象的类型,在初始化语句中更改它们的输入参数(这里是变量inupt)。有人能解释一下这种行为吗?

我至少感到高兴的是,static_cast和std::move的行为类似,因为std::move确实在幕后使用了static_cast。

代码语言:javascript
运行
复制
#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
   }

}
EN

Stack Overflow用户

发布于 2019-07-24 17:24:15

至少static_cast和std::move的行为类似,因为std::move确实使用了static_cast

不仅是相似的,而且他们做的事情完全一样。std::move是对rvalue引用的静态强制转换。

有人能解释一下这种行为吗?

  1. result是指input的引用。绑定引用不会修改引用对象。
  2. 对象被初始化。因为它是从rvalue初始化的,所以使用了move构造函数。根据std::string的文档,input对象处于未指定但有效的状态,这可能但与被移动之前没有什么不同。
  3. 转换的结果被丢弃。这没有副作用,input也不会被修改.
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57187928

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档