gpt4 book ai didi

c++ - boost::ref 和常规引用之间的区别

转载 作者:可可西里 更新时间:2023-11-01 16:36:37 26 4
gpt4 key购买 nike

boost::ref(i)& i 有什么区别?在什么情况下我们不能使用常规引用而必须使用 boost::ref 代替?如果可能,请包括示例。

最佳答案

来自Boost.Ref Documentation :

The purpose of boost::reference_wrapper is to contain a reference to an object of type T. It is primarily used to "feed" references to function templates (algorithms) that take their parameter by value.

注意:boost::reference_wrapperstd::reference_wrapper(至少是 Boost 1.52)之间的一个重要区别是 std::reference_wrapper 的能力 完美包装函数对象。

这会启用如下代码:

// functor that counts how often it was applied
struct counting_plus {
counting_plus() : applications(0) {}
int applications;

int operator()(const int& x, const int& y)
{ ++applications; return x + y; }
};

std::vector<int> x = {1, 2, 3}, y = {1, 2, 3}, result;
counting_plus f;
std::transform(begin(x), end(x), begin(y),
std::back_inserter(result), std::ref(f));
std::cout << "counting_plus has been applied " << f.applications
<< " times." << '\n';

关于c++ - boost::ref 和常规引用之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2561145/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com