Passing temporaries as non-const references in C++

前端 未结 3 1072
长情又很酷
长情又很酷 2021-02-03 11:41

I have the following piece of code, as an example dec_proxy attempts to reverse the effects of the increment operator upon the type that is executed in a complex function call f

3条回答
  •  野性不改
    2021-02-03 12:14

    Thanks to MSN, the solution:

    I don't think it is correct by adding the function template template dec_proxy_impl& dec_proxy(T&t).

    What it did is just cheating compiler. It will result in runtime error. The function foo requires the lvaue or lvalue reference. But template dec_proxy_impl& dec_proxy(T&t) doesn't return a valid lvalue reference. In the implementation, it creates a temporary object, and returns it. After the function call finishes, the temporary object will be destroyed. So the value reference passed into the function foo is wrong. Actually the referenced object has already been destroyed. The ++t;++s;++r are trying to access the invalid objects. The behavior is undefined.

    The solution from MSN is correct. The life time of the object dec_proxy(i) is from its declaration to the end of the function call. It makes sure the parameter in the function foo is valid.

提交回复
热议问题