Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
321 views
Welcome To Ask or Share your Answers For Others

1 Answer

  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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...