std::bind lose reference when delivered as rvalue reference

耗尽温柔 提交于 2019-11-30 11:15:44

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.

Andy Prowl

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!