Passing temporaries as non-const references in C++

前端 未结 3 1129
长情又很酷
长情又很酷 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:09

    What you try to do is to pass a rvalue (your new dec_facade(i)) as an lvalue reference, which explains why it doesn't work.

    If you compiler support it, you can use rvalue references, using && type modifier : (Support for rvalue reference could be enabled by switching on C++0x or C++11 [partial] support)

    template
    void foo(T& t)
    {    
        ++t;
    }
    template
    void foo(T&& t)
    {    
        ++t;
    }
    

    But that only one part of the problem. What you try to do, is to pre-increment a temporary value! That's non-sense, as it won't live after that call. Your object will be increment, then destroyed.


    One other solution would be to remove the & from your function definition, which would permit it to accept any parameter. But that's perhaps not what you want.

提交回复
热议问题