什么是static_cast< T>做一个T& [英] What does static_cast<T> do to a T&?

查看:181
本文介绍了什么是static_cast< T>做一个T&的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我问了这个问题,我正在通过 static_cast 。 (顺便提一句,它确实解决了问题,我只是不知道为什么。)



在代码中:

 矢量< int> foo = {0,42,0,42,0,42}; 
replace(foo),end(foo),static_cast< int>(foo.front()),13);

static_cast int ?它和只是调用有什么区别:

  replace(begin(foo),end(foo),int {foo。 front()},13); 

编辑:



根据 static_cast 的回答建构R-Value int http://ideone.com/dVPIhD



但此代码不是在Visual Studio 2015上工作。这是一个编译器错误?在此处测试: http://webcompiler.cloudapp.net/

解决方案


  1. 是的,它与 int {...} 相同,除非 .front()返回了需要缩小转换的类型。在这种情况下, int(...)将是相同的。


  2. 错误,静态转换稍微不太可能做某事危险,例如将指针转换为 int(...)的int


注意,由于前面的元素被replace操作修改,消除了未定义行为的转换结果,并且可以破坏 std ::替换



我会使用

  template< class T> 
std :: decay_t< T> copy_of(T& t){return std :: forward< T>(t); }




为什么这不工作在MSVC ...



MSVC有帮助的情况下,你转换类型 T T ,并且不做任何操作。这会中断您的代码。



有一个编译器标志(/ Zc:rvalueCast),您可以使用MSVC不再破坏您的代码。


So I asked this question and I was tinkering around with solving it via static_cast. (Incidentally it does solve the problem, I'm just not sure if I understand why.)

In the code:

vector<int> foo = {0, 42, 0, 42, 0, 42};
replace(begin(foo), end(foo), static_cast<int>(foo.front()), 13);

Is the static_cast simply constructing an R-Value int? What's the difference between that and just the call:

replace(begin(foo), end(foo), int{foo.front()}, 13);

EDIT:

As inferred by the answers static_cast does seem to construct an R-Value int: http://ideone.com/dVPIhD

But this code does not work on Visual Studio 2015. Is this a compiler bug? Test here: http://webcompiler.cloudapp.net/

解决方案

  1. Yes, it is the same as int{...}, unless .front() returned a type that required a narrowing conversion. In that case, int(...) would be identical.

  2. In the case of programmer error, static cast is marginally less likely to do something dangerous, like convert a pointer into an int than int(...).

Note eliminating the cast results in undefined behaviour as the front element is modified by the replace operation, and that could break std::replace.

I would use

template<class T>
std::decay_t<T> copy_of(T&& t){return std::forward<T>(t); }

myself here.

As for why this isn't working in MSVC...

MSVC helpfully takes situations where you cast a variable of type T to a T and proceeds to do nothing. This breaks your code.

There is a compiler flag (/Zc:rvalueCast) you can use to make MSVC no longer break your code.

这篇关于什么是static_cast&lt; T&gt;做一个T&amp;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆