static_cast

I'm having some trouble understanding when you can and cannot cast between pointers. For example

1
2
  const void* head = static_cast<void*>(new int[10]);
const void* tail = static_cast<int*>(head)+10;


fails because line 2 is an "invalid type conversion". What is wrong here?
Last edited on
I'm having some trouble understanding when you can and cannot cast between pointers.


FWIW, you generally want to avoid doing this anyway. The whole point of a type being assigned to a pointer is so you can know what you're pointing to. Removing that type system and using a generic void pointer doesn't change what you're pointing to, it only makes it so you no longer know what you're pointing to -- and therefore makes your code more error prone.

Of course there are legitimate times where you'd want to do this, but you generally don't want to.


That said...

const void* head = static_cast<void*>(new int[10]);

You are actually doing 2 casts here:

1) int* to void* (explicit with your static_cast)
2) void* to const void* (implicit with your assignment)

Both of these casts are legal. int* can be cast to void* because they are both non-const and they are compatible pointer types.

void* can be cast to const void* because it's the same type, only you are adding a const qualifier -- which is perfectly OK to do.


const void* tail = static_cast<int*>(head)+10;

You are doing 2 casts here as well:
1) const void* to int* (with your static_cast)
2) int* to const void* (with your assignment)


Note that const void* to int* will fail, because you cannot drop the 'const' qualifier with static_cast. For that, you would need to use const_cast -- although you don't need to drop the const qualifier anyway. You could just cast to a const int*:

const void* tail = static_cast<const int*>(head)+10;

This is also 2 casts, but unlike above they are both legal because we never try to drop the const qualifier:

1) const void* to const int* (static_cast)
2) const int* to const void* (assignment)
Last edited on
Topic archived. No new replies allowed.