+ Reply to Thread
Results 1 to 2 of 2

Thread: Void pointer in C++

  1. #1
    Junior Member
    Join Date
    Jun 2012
    Posts
    14

    Void pointer in C++

    I often see code which resembles something like the following:

    Code:
    void * foo(int bar);
    What does this mean? Does it mean that it can return anything? Is this similar to dynamic or object in C#?

  2. #2
    Junior Member
    Join Date
    Jun 2012
    Posts
    10
    A void* does not mean anything. It is a pointer, but the type that it points to is not known.

    It's not that it can return "anything". A function that returns a void* generally is doing one of the following:

    -> It is dealing in unformatted memory. This is what operator new and malloc return: a pointer to a block of memory of a certain size. Since the memory does not have a type (because it does not have a properly constructed object in it yet), it is typeless. IE: void.
    -> It is an opaque handle; it references a created object without naming a specific type. Code that does this is generally poorly formed, since this is better done by forward declaring a struct/class and simply not providing a public definition for it. Because then, at least it has a real type.
    -> It has explicit documentation telling you what type(s) that you can use the pointer for.
    -> It is nothing like dynamic or object in C#. Those constructs actually know what the original type is; void* does not. This makes it far more dangerous than any of those, because it is very easy to get it wrong.

    And on a personal note, if you see code that uses void*'s "often", you should rethink what code you're looking at. void* usage, especially in C++, should be rare, used primary for dealing in raw memory.

+ Reply to Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts