C++对象赋值为 NULL
我正在查看一些使用 Boost.Function 的代码并有一个关于如何编写代码以允许赋值为 NULL 的问题。我试图找到相应的 Boost 代码,但没有成功。基本上,是什么让这成为可能?
boost::function<void()> func;
func = NULL;
编辑:以下内容不适合我编译,那么他们如何防止这种情况呢?
func = 1;
I was looking at some code that uses Boost.Function and have a question about how code can be written to allow assignment to NULL. I tried to track down the corresponding Boost code, but was unable to. Basically, what makes this possible?
boost::function<void()> func;
func = NULL;
EDIT: The following doesn't compile for me though, so how do they prevent this too?
func = 1;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通过带有指针参数的运算符重载。来自 boost 来源:
这并不意味着“func”本身是 NULL,实际上您可以访问它自己的函数。以下代码可以编译并且不会崩溃。
By operator overloading with pointer parameter. From boost sources:
This doesn't mean that "func" itself is NULL, indeed you can access its own functions. Following code compiles and doesn't crash.
我不知道你到底想做什么,但这可能会有所帮助:
顺便说一句,在 C++ 中你大多写 0 或 nullptr 而不是 NULL。
I dont know what exactly you are trying to do but this could help:
Btw, in C++ you mostly write 0 or nullptr instead of NULL.
boost::function
可以在其赋值运算符中接受指向函数的指针。指针可以是有效指针或NULL
(即0)。尝试传递int
时出现错误的原因是您无法将整数分配给指针。这就像尝试执行以下操作:也不会编译。
boost::function
can accept a pointer to a function in its assignment operator. A pointer can be a valid pointer orNULL
(meaning 0). The reason you get an error when trying to pass anint
is that you cannot assign an integer to a pointer. It is like trying to do the following:Which won't compile either.
正如您在文档中看到的, std::function 有一个赋值来自
nullptr_t
的运算符As you can see in the documentation the std::function has an assignment operator from
nullptr_t