Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the value of this void* back?

Tags:

c++

pointers

void

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;
    }
};
like image 493
HappyHippo Avatar asked Aug 30 '18 12:08

HappyHippo


2 Answers

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.

like image 73
Bathsheba Avatar answered Nov 15 '22 02:11

Bathsheba


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.

like image 32
Andriy Tylychko Avatar answered Nov 15 '22 02:11

Andriy Tylychko