您告诉编译器将数组storage
视为Node
结构。但是storage
中的数据没有进行任何初始化,其内容是不确定的,并且以任何方式使用都会导致未定义的行为。
更具体地说,“结构”的成员没有构造或初始化,因此尝试将成员data
用于任何复杂的事情(如您的情况)很可能导致崩溃。
简单的解决方案是使用展示位置new
head = new (storage) Node;
请注意,放置new
后不能delete
对象,需要显式调用析构函数
head->~Node();
,
您对未初始化的内存进行操作。尤其是您尝试实现自己的内存管理,这将导致99%的实现失败。
您只需在创建的类中使用new
和delete
,就不必再担心存储空间了。
#include <string>
template <typename T>
struct Node {
T data;
Node *next;
};
template <typename T>
class Test
{
public:
Test() {
head = new Node<T>();
}
~Test() {
delete head; head = nullptr;
}
void setData(T data) {
if (head = nullptr) {
head->data = data;
}
}
private:
Node<T>* head = nullptr;
};
int main() {
Test<std::string> test_string;
Test<int> test_int;
test_string.setData("Hello");
test_int.setData(1);
return 0;
}
重要说明:
- 在
Test
的构造函数中,将分配内存
- 对于每个
new
,必须有一个delete
。所以请注意析构函数
- 为实现良好的防御性,请始终检查指针是否为
nullptr
- 为了获得更好的代码风格,请不要使用
using namespace std;
。如果这样做,您将open
变成一个很大的名称空间,该名称空间可能会与您的某些类名或函数名冲突。此错误几乎找不到。
免责声明:这适用于MSVC2017。
奖励
对于更现代的c++
,您可以使用std::unique_ptr
。
#include <string>
#include <memory>
template <typename T>
struct Node {
T data;
Node *next;
};
template <typename T>
class Test
{
public:
void setData(T data)
{
if (head = nullptr)
{
head->data = data;
}
}
private:
std::unique_ptr<Node<T>> head = std::make_unique<Node<T>>();
};
int main()
{
Test<std::string> test_string;
Test<int> test_int;
test_string.setData("Hello");
test_int.setData(1);
return 0;
}
本文链接:https://www.f2er.com/3139483.html