gpt4 book ai didi

c++ - 使用 boost::bind 传递比预期更多的参数安全吗?

转载 作者:IT老高 更新时间:2023-10-28 13:01:28 24 4
gpt4 key购买 nike

使用 , 结果 可能会收到比绑定(bind)对象预期更多的参数。从概念上讲:

int func() { return 42; }
boost::function<int (int,int,int)> boundFunc = boost::bind(&func);
int answer = boundFunc(1,2,3);

在这种情况下,func() 在堆栈上接收 1,2 和 3,即使其签名表明它不接受任何参数。

这与 boost::bind 用于 partial application 的更典型用法不同。 ,其中某些对象的值是固定的,从而产生一个 boost::function,它需要更少的参数,但在调用绑定(bind)对象时提供正确数量的参数

以下代码适用于 MSVC++2010 SP1。这是张贴的简化形式;原代码也可以在 Linux 上的 g++4.4 下运行。

是否根据 C++ 标准明确定义了以下内容?

#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>

using namespace std;

void func1(int x) { std::cout << "func1(" << x << ")\n"; } // end func1()

void func0() { std::cout << "func0()\n"; } // end func0()

int main(int argc,char* argv[])
{
typedef boost::function<void (int)> OneArgFunc;
OneArgFunc oneArg = boost::bind(&func1,_1);
// here we bind a function that accepts no arguments
OneArgFunc zeroArg = boost::bind(&func0);
oneArg(42);
// here we invoke a function that takes no arguments
// with an argument.
zeroArg(42);

return 0;
} // end main()

我明白为什么 zeroArg(42) 有效:未使用的参数由调用例程放入堆栈,而被调用例程根本无法访问。当被调用例程返回时,调用例程清理堆栈。由于它将参数放在堆栈上,它知道如何删除它们。

将迁移到另一个架构或编译器打破这个?更积极的优化会打破这一点吗?


我正在从 Boost 文档或标准文档中寻找更强有力的声明。我也找不到一个明确的立场。

使用调试器并查看程序集和堆栈,很明显第一个示例中的 func 没有收到值 1,2 和 3:您在这方面是正确的。第二个示例中的 func0 也是如此。至少对于我正在查看的实现,MSVC++2010SP1 和 g++4.4/Linux,这是正确的。

查看引用的 Boost 文档,并不清楚传递额外参数是否安全:

bind(f, _2, _1)(x, y);                 // f(y, x)

bind(g, _1, 9, _1)(x); // g(x, 9, x)

bind(g, _3, _3, _3)(x, y, z); // g(z, z, z)

bind(g, _1, _1, _1)(x, y, z); // g(x, x, x)

Note that, in the last example, the function object produced by bind(g, _1, _1, _1) does not contain references to any arguments beyond the first, but it can still be used with more than one argument. Any extra arguments are silently ignored, just like the first and the second argument are ignored in the third example. [Emphasis mine.]

关于忽略额外参数的声明并不像我想说服我在一般情况下这是正确的那样明确。看TR1 ,从 3.6.3 节可以清楚地看出,从 bind 返回的 callable object 可以使用与 target object 不同数量的参数来调用预计。这是最好的保证吗?

最佳答案

是的,这是安全和便携的——正如 the documentation 中明确提到的。 , boost::bind 返回的绑定(bind)表达式会默默地忽略额外的参数。

即,在您的第一个示例中,func 确实 not 接收值 123boundFunc 接收值 123 并将它们转发给包含的绑定(bind)表达式,它安全地接收并忽略它们,然后调用 func()。同样,在您的第二个示例中, zeroArg 接收值 42 并将其转发到包含的绑定(bind)表达式,该表达式接收并忽略该值,然后调用 func0( ).

关于c++ - 使用 boost::bind 传递比预期更多的参数安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7394367/

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