Stub said:
I read the code in a book and it seems not quite right to me. The possible
mistake seems in the dummy::getData(). It returns a local pointer, void*
data, back to its caller. Am I right about this?
class dummy
{
public:
void* getData();
void *first;
};
void* dummy::getData(){
void *data;
data = first;
return data;
}
#include <stdcaution> // I'm certainly not an expert in C++
You're right about the fact that it returns a local variable, but this
is not a problem by itself (well, this may be a problem for the caller
if dummy::first is not initialised before).
Returning a local variable is ok, the caller gets a copy of it. What
would be wrong would be to return *the address of* a local variable.
What seems more problematic to me is that
1/ the local variable 'data' in getData() is useless. This code is the
same as :
void* dummy::getData(){
void *data = first; // useless
return first;
}
which in turn would be better written :
void* dummy::getData(){
return first;
}
2/ since it's a pointer that is returned, and not a copy of the value
pointed, any change made to the value pointed will affect dummy::first
3/ this function by itself is actually of useless, since dummy::first is
public...
4/ ... - which is a Bad Thing(tm).
5/ void pointers are probably the worst way to write generic code in C++
anyway.
Well... I don't know which book this come from, but I suspect the paper
it's made of would be more useful elsewhere...
(gurus please correct me if I said some stupidities)
Bruno