在 new 关键字中,由默认构造函数初始化的类中的元素是否也使用 new 关键字在C++?
Is considring new keyword the elements inside the class that are initialized by the default constructor also with new keyword in C++?
初始化具有动态分配成员的类。 new 关键字是否用于分配整个内存块,同时考虑到将由默认构造函数在类内部初始化的成员?
我应该关心这些成员在内存中的放置位置(稀疏或放在一起(吗?我正在递归算法中使用巨大的顶点数组,该算法根据某些错误标准执行自适应网格细化。我需要遍历这些数组来执行其他操作,所以我需要性能。
此外,作为相关主题。下面用于在 main 函数中声明类的两种方法之一在性能方面是否首选?
你能推荐我一些关于这个主题的书/文章/网页吗?
总结问题的玩具代码示例:
class Octree {
vec3* Vertex;
vec3* Cell_Centers;
public:
Octree(unsigned population_to_allocate) //constructor
{
Vertex = new vec3[population_to_allocate*8];
Cell_Centers = new vec3[population_to_allocate];
}
int main()
{
unsigned population_to_allocate = 3000;
Octree* newOctree = new Octree(population_to_allocate);
Octree stackOctree(population_to_allocate);
}
鉴于您说过Octree
s 的数量最多是 7 个,population_to_allocate
是数千个,您可以做的最简单的有效方法是从vec3*
更改为std::vector<vec3>
。 然后你的构造函数将如下所示:
Octree(unsigned population_to_allocate) //constructor
: Vertex(population_to_allocate)
, Cell_Centers(population_to_allocate)
{
}
不使用new
,您将轻松避免内存泄漏和错误。 没有理由使事情变得比这更复杂,因为您只有少数Octree
实例。
相关文章:
- 声明C++数组(带或不带 "new" 关键字)
- 在 Objective-C++ -> EXC_BAD_ACCESS Error 中使用"new"关键字
- 如何在堆上初始化线程?(使用 "new" 关键字)
- 如何在不使用 "new" 关键字的情况下解除分配创建的对象的内存?
- 在 new 关键字中,由默认构造函数初始化的类中的元素是否也使用 new 关键字在C++?
- 野牛解析器无法识别"New"关键字
- 'new'关键字如何工作?我最近才知道新关键字
- 为什么当我使用"new"关键字声明数组指针时无法删除它
- 如果我不使用 new 关键字,可能会出现内存泄漏吗?
- 'new'关键字和类存储
- 说明何时在C++中使用 "new" 关键字
- 在没有“new”关键字的情况下实例化类会导致在堆栈或堆上创建其内部变量
- C++对象初始化,无需 new 关键字并使用指针
- 当对象不使用 new 关键字但父对象在堆中时,对象是否存储在堆栈或堆中
- 在没有 new 关键字的情况下初始化C++对象的内存从何而来
- 模板类的构造函数在使用 new 关键字时调用类型构造函数
- 循环中的多个对象C++而不"new"关键字
- C++:结构和new关键字
- 删除c++中的对象,以及new关键字
- New关键字用作标识符