JaredC
JaredC

Reputation: 5310

C++ object assignment to NULL

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;

Upvotes: 5

Views: 701

Answers (4)

b10y
b10y

Reputation: 879

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());
}

Upvotes: 3

Zac Howland
Zac Howland

Reputation: 15870

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.

Upvotes: 1

Gene Bushuyev
Gene Bushuyev

Reputation: 5538

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

Upvotes: 0

codymanix
codymanix

Reputation: 29490

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.

Upvotes: 1

Related Questions