将向量初始化添加到结构构造函数
Adding vector initialization to struct constructor
我有一个结构,如下所示:
struct octNode{
octNode* parent;
octNode* child[8];
std::vector<int> pointIndex;
//constructor of the struct
octNode()
{
memset(parent,0,sizeof(parent));
memset(child,0,sizeof(child));
}
};
但这会引发运行时错误:0xC0000005:访问冲突写入位置0xcdcdcdcd。Octree_octnode_0113.exe中0x771115de处未处理的异常:0xC0000005:访问违规写入位置0xcdcdcdcd。
访问冲突发生在空向量的创建过程中。有没有办法初始化构造函数中的向量,以免发生错误?
在下面
memset(parent,0,sizeof(parent));
您正在将未初始化的指针传递给 memset()
。你的意思是说:
memset(&parent, 0, sizeof(parent));
或者,很简单
parent = NULL; // or nullptr
?
此行会导致使用未初始化的指针:
memset(parent,0,sizeof(parent));
您应该将其设置为 NULL
:
parent = NULL;
(或者更好的是,在初始化列表中这样做:)
octNode() : parent(NULL)
{
memset(child,0,sizeof(child));
}
代码应该说:
struct octNode{
octNode* parent;
octNode* child[8];
std::vector<int> pointIndex;
//constructor of the struct
octNode()
: parent(NULL) // maybe nullptr ?
, pointIndex()
{
std::fill_n(child, 8, NULL); // nullptr?
}
};
相关文章:
- 在 c++ 中将变量作为结构构造函数中的引用传递
- 嵌套的模板结构构造函数实现
- 其他结构中的结构构造函数
- CPP/C 中的常量用法和结构构造函数中的澄清
- 聚合结构构造函数
- 结构构造函数调用不明确
- 关于结构构造函数和析构函数行为-C++
- 带有指针的C++结构:构造函数和析构函数
- 结构构造函数导致堆栈溢出的问题
- C++结构构造函数和函数冲突
- 嵌套结构构造函数和并集的问题
- C++结构构造函数
- 调用结构构造函数后初始化的值是什么
- 在结构构造函数中使用"this"关键字编译错误?-C++
- 这可能吗?在 C# 中调用托管 c++ 结构构造函数
- C++ - 结构构造函数,尝试取消指向结构的指针时出现重定义错误
- C++结构构造函数错误
- 结构构造函数语法
- 结构构造函数错误,为什么使用默认构造函数会调用错误
- Qt 将 QString 传递给结构构造函数不起作用