如何获得此void*的值?

Luk*_* G. 5 c++ pointers void

我有一个无效指针,我可以设置该值就好了(至少我认为我做对了).但是当我试图获得存储在那里的东西的价值时,我什么都得不回来.如果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;
    }
};
Run Code Online (Sandbox Code Playgroud)

Bat*_*eba 6

void setData(T data)data 按价值收取.

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

之后,指针悬空,取消引用行为未定义.


小智 3

试试这样:

// 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);
    }
};
Run Code Online (Sandbox Code Playgroud)

我在代码中添加了注释。

至于你的代码

template <typename T>
void setData(T data) {
    _data  = &data;
}
Run Code Online (Sandbox Code Playgroud)

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

void *_data;

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

template<typename T>
class Vertex2
{
    T m_data;
    .
    .
    .
Run Code Online (Sandbox Code Playgroud)

  • @Pi:是的,我愿意。尝试寻求最佳解决方案,请记住 Stack Overflow 是一个问答网站,而不是论坛。因此,不要专门针对 OP 给出答案。 (2认同)