我有一个无效指针,我可以设置该值就好了(至少我认为我做对了).但是当我试图获得存储在那里的东西的价值时,我什么都得不回来.如果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)
小智 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)
我在代码中添加了注释。
至于你的代码
Run Code Online (Sandbox Code Playgroud)template <typename T> void setData(T data) { _data = &data; }
不要那样做。您将地址存储到数据的临时副本。这会出问题的!
void *_data;
不要将数据存储为 void,将类模板化如下:
template<typename T>
class Vertex2
{
T m_data;
.
.
.
Run Code Online (Sandbox Code Playgroud)