Is there a way to detect if objects pointed by p and d are of different types? (p points to int and d points to array of ints):
int* p = new int();
int* d = new int[20];
Is there a way to detect if objects pointed by p and d are of different types? (p points to int and d points to array of ints):
int* p = new int();
int* d = new int[20];
...objects pointed by p and d are of different types? (p points to int and d points to array of ints):
Well, first off, that's not really correct. Yes, d
points to the beginning of an array, but
they both point to the exact same thing; an int
. Whether or not you can safely perform arithmetic on the pointer and then dereference it is another question.
When you dereference them the machine simply gives you back an appropriately sized chunk of memory and interprets it as an int.
C++ isn't exactly the goto language for meta programming, and if you're dealing with pointers does it really matter anyway? I've never found the need to do this. You know you have a pointer, you (should) know if it points to one int
or a bunch of int
s as you declared it, so what exactly is the problem you are trying to solve?
I would say that no. both p and d are pointers to int, d is a pointer to the head of the array - and the head is an int.
array of ints is not the type of d - it's a pointer to int
#include <iostream>
#include <typeinfo>
using namespace std;
int main()
{
int* p = new int();
int* d = new int[20];
float* f = new float();
if (typeid(p) == typeid(d))
cout << "equal" << endl;
else
cout << "not equal" << endl;
if (typeid(p) == typeid(f))
cout << "equal" << endl;
else
cout << "not equal" << endl;
}
Outputs:
equal
not equal
Is there a way to detect if objects pointed by p and d are of different types?
Your supposition is false. p and q are both pointing to the same type, an int.
If you implement your own new
and new[]
you could, but the dragons here will eat you alive:
void * operator new(size_t size)
{
size_t * allocation = (size_t *)malloc(size+sizeof(size_t));
*allocation = size;
return allocation + 1;
}
void * operator new[](size_t size)
{
size_t * allocation = (size_t *)malloc(size+sizeof(size_t));
*allocation = size;
return allocation + 1;
}
template<typename T> size_t allocationCount(T*memory)
{
size_t * allocation = reinterpret_cast<size_t*>(memory) - 1;
return *allocation / sizeof(T);
}
int main()
{
int * fred = new int;
int * nurk = new int[30];
cout << allocationCount(fred) << endl;
cout << allocationCount(nurk) << endl;
}
Outputs:
1
30