【发布时间】:2021-04-09 11:43:05
【问题描述】:
我已经开始为 List 类编写一些代码,但我迷路了。我的 Arduino 项目需要它——我不能使用 STL。
这是代码。
#include <iostream>
template <typename T>
class List
{
public:
List<typename T>()
{
m_Count = 0;
m_Data = nullptr;
}
~List()
{
free(m_Data);
}
void Push(const T& element)
{
m_Count++;
T* alloc = (T*)malloc(size_t(sizeof(T) * m_Count));
memcpy(alloc, m_Data, m_Count * sizeof(T));
*(m_Data + sizeof(T) * (m_Count - 1)) = element;
}
T* operator [](unsigned int x) const
{
return (m_Data + x * sizeof(T));
}
private:
T* m_Data;
uint64_t m_Count;
};
struct Vertex
{
int x;
int y;
};
int main()
{
List<Vertex> list;
list.Push({ 0, 1 });
list.Push({ 2, 3 });
list.Push({ 4, 5 });
std::cout << list[0]->x << list[1]->x << list[2]->x;
}
问题出在Push方法的某个地方:当我调用memcpy时,程序触发了编译器断点。
【问题讨论】:
-
为什么在 C++ 程序中使用
malloc?其次,如果T类型不可轻松复制,T* alloc = (T*)malloc(size_t(sizeof(T) * m_Count));将无法工作。如果您要创建自己的课程,请使用new[]和delete[]。 -
感谢您的回复。还有一个问题 - 在这种情况下我该如何使用 memcpy?
-
首先开始使用
new[]。其次,m_Data新分配的内存分配在哪里?仔细查看您的代码,您会发现这并没有完成。 -
为什么不应该使用 malloc 的问题是 malloc 不会创建对象。如果类型
T需要正确构造,malloc对调用构造函数一无所知。因此,您现在调用malloc的那行只分配了一堆字节,仅此而已。您现在有一堆字节不代表T或T的数组应该代表什么。 -
在
Push()中对memcpy()的调用具有未定义的行为,因为m_Count最初表示元素的数量,它会递增,然后memcpy()会比现有元素多复制一个元素在原始缓冲区中。
标签: c++ malloc stdvector memcpy