我如何取回此 void* 的值?

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

我有一个空指针,我可以很好地设置它的值(至少我认为我做对了)。但是当我试图获取存储在那里的值时,我什么也得不到。 void* 指向字符串或 int 或其他任何内容都没有关系。 我在这里错过了什么?

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) 按值 data 接收

因此,设置指向 data 的指针仅在该函数调用的生命周期内有效。

在那之后,指针悬空,解引用行为是未定义

那里没有存储任何东西。

您将指针设置为指向一个函数参数,然后它超出了范围。

你想投多少就投多少,但是那个物体不见了!

除非您动态分配,否则此设计将无法工作。

考虑 std::variant 或其他东西。

template <typename T>
void setData(T data) {
    _data  = &data;
}

让我们看看这里发生了什么。您存储指向局部变量的指针(实际上是方法参数)。离开该方法后,局部变量立即被销毁,其内存可以自由重用。现在你的 void* 指向相同的内存地址,但内存可以包含任何内容。

这样试试:

// the entire class should be templated and you should not cast the data to void
template<typename T>
class Vertex2
{
public:
    int _id;
    // data is no longer void
    T m_data;

    // now returning a const pointer to your data and protect it against manipulation from outside
     getData() const {
        return m_data;
    }

    // was setting the address of a temporary, that will not work. Now it takes a copy and moves that to the member.
    void setData(T data) {
        m_data = std::move(data);
    }
};

我在代码中添加了注释。

关于你的代码

template <typename T>
void setData(T data) {
    _data  = &data;
}

不要那样做。您将地址存储到数据的临时副本中。这样会出错!

void *_data;

不要将数据存储为 void,模板 class 如下:

template<typename T>
class Vertex2
{
    T m_data;
    .
    .
    .