std::bind lose reference when delivered as rvalue reference

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

I have the following code:

#include 
#include 

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


        
2条回答
  •  长情又很酷
    2021-01-01 13:26

    std::bind uses value semantics by default. It's a sane default that lets you do things like the following safely.

    int f(double x);
    
    auto fun = std::bind(f, 1.0); // stores a copy, not a reference to a temporary
    fun();
    

    Using value semantics is safe: the lifetime of the bound arguments becomes the lifetime of the object returned by bind. Using reference semantics would not have that guarantee. So you are required to be explicit when you want reference semantics; if you get in trouble then it's your fault. In order to do that you need to use std::ref:

    int main(void)
    {
        double t=1.0;
        printf("%f\n",t);
        test(t);
        printf("%f\n",t);
        callback(std::bind(test, std::ref(t)));
        printf("%f\n",t);
    }
    

    This same protocol is used elsewhere in the standard library, like the std::thread constructor.

提交回复
热议问题