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;
An object of a class cannot be set to NULL; however, you can set a pointer (which contains a memory address of an object) to NULL.
In C programming language a Null pointer is a pointer which is a variable with the value assigned as zero or having an address pointing to nothing. So we use keyword NULL to assign a variable to be a null pointer in C it is predefined macro.
Pointers refer to a location in memory (RAM). When you have a null pointer it is pointing to null, meaning that it isn't pointing to location in memory. As long as a pointer is null it can't be used to store any information, as there is no memory backing it up.
free() is a library function, which varies as one changes the platform, so you should not expect that after passing pointer to this function and after freeing memory, this pointer will be set to NULL.
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With