英文:
C++ Compilation problem with creating an array of struct from the heap
问题
以下是翻译好的部分:
- 构造函数:
MyClass(int xx, int yy) : x(xx), y(yy)
{
m_BufferPtr = new struct BufferCustom[CONST_BUFFER_SIZE];
}
编译错误:分配不完整类型 struct BufferCustom 的内存。
- 析构函数中的警告:
if (m_BufferPtr){
delete [] m_BufferPtr;
m_BufferPtr = nullptr;
}
警告:删除不完整类型 'struct BufferCustom' 的指针可能导致未定义行为。
我对为什么会出现这个错误感到困惑!
英文:
I'm getting a compilation error and warning when I compile this.
#include <iostream>
struct {
uint8_t m_data;
int size;
} BufferCustom;
class MyClass
{
private:
int x, y;
const int CONST_BUFFER_SIZE = 10;
struct BufferCustom *m_BufferPtr;
public:
MyClass(int xx, int yy) : x(xx), y(yy)
{
m_BufferPtr = new struct BufferCustom[CONST_BUFFER_SIZE];
}
virtual ~MyClass() {
if (m_BufferPtr){
delete [] m_BufferPtr;
m_BufferPtr = nullptr;
}
}
// user defined copy constructor
MyClass(const MyClass& rhs)
: x{ rhs.x }, y{ rhs.y } // initialize members with other object's // members
{
std::cout << "User defined copy constructor invoked.";
//m_BufferPtr = new struct B
}
MyClass& operator=(const MyClass &rhs)
{
std::cout << "Assignment operator called\n";
return *this;
}
};
int main()
{
MyClass o1{ 1, 2 };
MyClass o2 = o1; // user defined copy constructor invoked
o2 = o1;
}
The error(s) are in these lines:
- Ctor
MyClass(int xx, int yy) : x(xx), y(yy)
{
m_BufferPtr = new struct BufferCustom[CONST_BUFFER_SIZE];
}
compilation error being Allocation of incomplete type struct BufferCustom
- The second warning is in the dtor
if (m_BufferPtr){
delete [] m_BufferPtr;
m_BufferPtr = nullptr;
}
saying that Deleting pointer to incomplete type 'struct BufferCustom' may cause undefined behavior
I am perplexed as to why this is an error!
答案1
得分: 6
这段代码:
struct {
uint8_t m_data;
int size;
} BufferCustom;
...定义了一个具有匿名类型的结构体,然后定义了一个名为BufferCustom
的该类型的实例。所以BufferCustom
是一个没有名称的类型的单个变量。
但是您后来的代码尝试将BufferCustom
用作类型的名称。我猜您的本意可能是这样:
struct BufferCustom {
uint8_t m_data;
int size;
};
这将BufferCustom
定义为类型的名称,因此您可以随后分配类型为BufferCustom
的对象。
英文:
This:
struct {
uint8_t m_data;
int size;
} BufferCustom;
...defines a struct with an anonymous type, then defines one instance of that type named BufferCustom
. So BufferCustom
is a single variable of a type that doesn't have a name.
But your later code attempts to use BufferCustom
as if it were the name of a type. I'd guess what you intended was something like this instead:
struct BufferCustom {
uint8_t m_data;
int size;
};
This defines BufferCustom
as the name of the type, so you can later allocate objects of type BufferCustom
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论