What does static_cast<T> do to a T&?

旧巷老猫 提交于 2019-11-28 11:22:34
  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.

Member function front returns a reference to the first element of a non-empty vector.

On the other hand standard algorithm replace declared like

template <class ForwardIterator, class T>
  void replace (ForwardIterator first, ForwardIterator last,
                const T& old_value, const T& new_value)

takes the third parameter also by reference. Thus in general the first element of the vector can be changed by the algorithm and as result processing of other elements of the vector by the algorithm can be incorrect.

Using static_cast a temporary object is created and will not be changed by the algorithm So the processing of all elements of the vector will be correct.

As for me then I suggested a C++ proposal to use keyword auto in such cases. For example

replace(begin(foo), end(foo), auto( foo.front() ), 13);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!