What does static_cast do to a T&?

后端 未结 2 1953
猫巷女王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 04:51

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

提交回复
热议问题