Are they the same thing? If not, what is the difference? Thanks for your input.
Printable View
Are they the same thing? If not, what is the difference? Thanks for your input.
Nope...they are different....one is basically describing the content the pointer is actually pointing to while the other is simply a pointer of type 'void'...in other words
Thus...a null-pointer can be a 'void'-pointer as well...Code:void* void_pointer;
int* null_pointer = 0;
Code:void* void_and_null_pointer = 0;
void is used to mean "Nothing", as in void foo() which means foo is a function that returns "Nothing".Quote:
Originally Posted by dullboy
void* is used to mean "something that can be anything", as in void *foo() which means foo is a function that can return a pointer to "anything"... cool heh :-)
NULL means "A thing which is Nothing" as in int *p = NULL; which means p is a pointer to int and it currently points to a thing which is defined as nothing :-)
A NULL is simply defined as 0 in most C/C++ implementations.
So, it is common to see code like if(!foo(...)) instead of if(NULL == foo(...)) which is also correct....
All the above mentioned definitions are mine and mine alone and do not represent the feelings of the C++ community in any way... :-)
Excellent! Thanks.
Quote:
Originally Posted by Andreas Masur
No, not cool: "I have a pointer to... something. Now what?"Quote:
Originally Posted by raghuvamshi
void* is only really useful if a function manipulates a pointer as a value in itself, rather than as a "reference" to something else, e.g. ostream operator<<(ostream, void*).
void * is also commonly used in standard APIs. For example, a thread function takes a void * parameter, a generic way of being able to pass it data.
This is how C APIs are often done, but in C++ APIs it is better to define a base class and expect a pointer to the base class.
Threads, for example, can be done like this:
This is a very loose description to show how one might start writing a C++ wrapper to pthread_create which removes the need for void *. (The return value of the thread function is also void *, and you might want to use a different class, a ThreadResult class).Code:// in header:
class ThreadClass
{
public:
virtual ThreadClass* threadFunc() = 0;
};
thread_t create_thread( ThreadClass * pThreadClass );
/// in .cxx file
namespace
{
extern "C" void * the_one_thread_function( void * param )
{
ThreadClass * pThreadClass( reinterpret_cast< ThreadClass * >(param ) );
return pThreadClass->threadFunc();
}
}
thread_t create_thread( ThreadClass * pThreadClass )
{
thread_t result;
pthread_create( &result, 0, the_one_thread_function, 0 );
return result;
}
(If you want to implement this in full, then it is probably a good idea to take an optional thread-attribute parameter (2nd parameter to pthread_create). You'd also need some kind of collection (somewhere to store the ThreadFunc object and subsequently be able to delete it), thus a thread pool ).