I have a void pointer of which I can set the value just fine (at least I think I did it right). But when I try to get the value of what is stored there, all I get nothing back. Doesn't matter if the void* points to a string or int or anything else. What am I missing here?
class Vertex2{
public:
int _id;
void *_data;
template<typename T>
T getData() {
T *value = (T*)_data;
return *value;
}
template <typename T>
void setData(T data) {
_data = &data;
}
};
void setData(T data)
receives data
by value.
Setting a pointer to data
therefore is only valid for the lifetime of that function call.
After that, the pointer dangles, and dereference behaviour is undefined.
template <typename T>
void setData(T data) {
_data = &data;
}
let's check what's going on here. You store a pointer to a local variable (method argument actually). Right after you leave the method the local var is destroyed and its memory is free to be reused. Now your void*
points to the same memory address but the memory can contain anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With