开发者

C++ object assignment to NULL

开发者 https://www.devze.com 2023-02-10 21:31 出处:网络
I was looking at some code that uses Boost.Function and have a question 开发者_C百科about how code can be written to allow assignment to NULL.I tried to track down the corresponding Boost code, but wa

I was looking at some code that uses Boost.Function and have a question 开发者_C百科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;


By operator overloading with pointer parameter. From boost sources:

#ifndef BOOST_NO_SFINAE
   self_type& operator=(clear_type*)
   {
     this->clear();
     return *this;
   }
#endif

This doesn't mean that "func" itself is NULL, indeed you can access its own functions. Following code compiles and doesn't crash.

TEST_F(CppTest, BoostFunctions) {
    boost::function<void()> func;
    func = NULL;
    ASSERT_TRUE(func==NULL);
    ASSERT_FALSE(func.has_trivial_copy_and_destroy());
}


I dont know what exactly you are trying to do but this could help:

boost::function<void()> *pFunc;
pFunc = NULL;

Btw, in C++ you mostly write 0 or nullptr instead of NULL.


boost::function can accept a pointer to a function in its assignment operator. A pointer can be a valid pointer or NULL (meaning 0). The reason you get an error when trying to pass an int is that you cannot assign an integer to a pointer. It is like trying to do the following:

char* c = 1;

Which won't compile either.


As you can see in the documentation the std::function has an assignment operator from nullptr_t

0

精彩评论

暂无评论...
验证码 换一张
取 消