What does static_cast do to a T&?

后端 未结 2 1958
猫巷女王i
猫巷女王i 2020-12-11 04:48

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

2条回答
  •  情深已故
    2020-12-11 05:14

    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
    std::decay_t copy_of(T&& t){return std::forward(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.

提交回复
热议问题