I was trying to guarantee that memory I allocated dynamically is pointing nowhere.
I tried the following
template<typename T>
[...something here...]
T *mem = new T[size];
for ( int i=0; i<size; i++ )
{
(mem+i) = NULL;
}
[...something else there...]
Just as one could write
int *pInt = new int;
pInt = NULL;
But it that doesn't work because in the upper example mem
isn't an "lvalue"?
Why does this only appear to be the case if I allocate dynamically more the one type-specific memory on the heap?
In addition one strange thing happens if I use a template-function, because it seems to be legal to write
template<typename T>
[...something here...]
T mem = new T[size];
for ( int i=0; i<size; i++ )
{
*(mem+i) = NULL;
/* or the equivalent
mem[i] = NULL;
*/
}
[...something else there...]
How can it be possible to assign NULL
(which is basically the int
value 0) to a variable or object that could be basically anything? It might be an int
variable, fine, it would work. But what if I called the template function with std::string
. It shouldn't work at all, right? So why does it appear to be legal to write something like this?
Is it the freedom to program generic but also the responsibility to watch out, not to invoke some generic function with the wrong type?