std::bind lose reference when delivered as rvalue reference

前端 未结 2 1082
感情败类
感情败类 2021-01-01 12:58

I have the following code:

#include 
#include 

template 
auto callback(T&& func) ->decltype(fu         


        
2条回答
  •  佛祖请我去吃肉
    2021-01-01 13:24

    std::bind() is designed for value semantics (as R. Martinho Fernandes nicely explains in his answer), and does create copies internally. What you need/want is std::ref:

    callback(std::bind(test, std::ref(t)));
    //                       ^^^^^^^^^^^
    

    std::ref returns an std::reference_wrapper<> object that wraps a reference to your original argument. This way, the reference_wrapper object around t gets copied, and not t itself.

    This allows you to choose between value semantics (assumed by default) and reference semantics (which requires your explicit intervention).

    Here is a live example.

提交回复
热议问题