static_cast<T> 是什么?对 T&amp; 做些什么?

2021-12-31 00:00:00 reference casting c++ static-cast rvalue

所以我问了这个问题,我想通过static_cast解决它.(顺便说一句,它确实解决了问题,我只是不确定我是否理解原因.)

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.)

在代码中:

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

static_cast 是否只是构造了一个 R 值 int?那和只是调用有什么区别:

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);

根据答案 static_cast 确实 似乎构造了一个 R 值 int:http://ideone.com/dVPIhD

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

但是这段代码不能在 Visual Studio 2015 上运行.这是编译器错误吗?在这里测试:http://webcompiler.cloudapp.net/

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

推荐答案

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

  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.

在程序员错误的情况下,静态转换不太可能做一些危险的事情,比如将指针转换为 int 而不是 int(...).

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(...).

注意消除强制转换会导致未定义的行为,因为替换操作修改了前面的元素,这可能会破坏 std::replace.

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

我会用

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

我在这里.

至于为什么这在 MSVC 中不起作用...

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

MSVC 可以帮助您处理将 T 类型的变量转换为 T 并且什么都不做的情况.这会破坏您的代码.

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

有一个编译器标志 (/Zc:rvalueCast) 你可以用来让 MSVC 不再破坏你的代码.

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

相关文章