Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ object assignment to NULL

Tags:

c++

null

boost

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;
like image 224
JaredC Avatar asked Feb 17 '11 14:02

JaredC


People also ask

Can you set object to null?

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.

Can we assign value to a null pointer in C?

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.

Can we assign value to null pointer?

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.

Does C free set pointer to null?

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.


1 Answers

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());
}
like image 77
b10y Avatar answered Sep 23 '22 13:09

b10y