简体   繁体   English

在C ++构造函数中分配内存的正确方法是什么?

[英]What is the right way to allocate memory in the C++ constructor?

Which is the right way to allocate memory via new in the C++ constructor. 这是在C ++构造函数中通过new分配内存的正确方法。 First way in the argument list: 参数列表中的第一种方式:

class Boda {
    int *memory;
    public:
        Boda(int length) : memory(new int [length]) {}
        ~Boda() { delete [] memory; }
};

or in the body of constructor: 或者在构造函数体中:

class Boda {
    int *memory;
    public:
        Boda(int length) {
            memory = new int [length];
        }
        ~Boda() { delete [] memory; }
};

Thanks, Boda Cydo. 谢谢,Boda Cydo。

I think the simplest way to do this would be to use a boost scoped array and let someone else's well tested library code handle it all for you. 我认为最简单的方法是使用一个增强范围的数组,并让其他人经过良好测试的库代码为您处理。

So: 所以:

class Boda {
    boost::scoped_array<int> memory;
    public:
        Boda(int length) : memory(new int [length]) {}
       ~Boda() {}
};

Moreover, scoped arrays cannot be copied - so you avoid the nasty copy constructor deallocation issue mentioned in another answer. 此外,无法复制范围数组 - 因此您可以避免另一个答案中提到的令人讨厌的复制构造函数释放问题。

You should use resource management classes that will handle it for you. 您应该使用将为您处理它的资源管理类。 Else, you run into some serious problems with exception safety, aside from needlessly duplicating existing logic and maintenance of copy/assignment operators. 否则,除了不必要地复制现有逻辑和维护复制/赋值操作符之外,您还会遇到异常安全方面的一些严重问题。

I would say both are equivalent in the effect they produce and both are "the right way". 我会说两者在它们产生的效果上是等价的,两者都是“正确的方式”。 I prefer initializer lists but I would go with the second variant just to be able to test for invalid length argument before trying to allocate the memory. 我更喜欢初始化列表,但我会选择第二个变量,以便在尝试分配内存之前能够测试无效长度参数。

memory member variable is a pointer, if you allocate it in initialization list and it fails, your class is not initialized and you don't need to free it later (thanks to RAII design pattern which is used by C++ for class initialization). memory成员变量是一个指针,如果你在初始化列表中分配它并且它失败了,你的类没有被初始化,你不需要在以后释放它(感谢C ++用于类初始化的RAII设计模式)。 If you allocate its memory inside the constructor's body, similar behavior will happens. 如果在构造函数体内分配其内存,则会发生类似的行为。

But if you want to handle something, then allocate its memory in the constructor's body. 但是如果你想处理某些事情,那么在构造函数的主体中分配它的内存。 Check something or try/catch it or print some useful messages, but at least, you have to throw another exception, because your class initialization is broken. 检查一下或尝试/捕获它或打印一些有用的消息,但至少,你必须抛出另一个异常,因为你的类初始化被破坏了。

I think memory allocation in the constructor's body is more readable than the other one. 我认为构造函数体中的memory分配比另一个更可读。

如果你想捕获内存分配错误(你可能应该这样做),那么你将不得不在构造函数的主体中调用new。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM