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

為{幸葍}努か 提交于 2019-12-22 05:11:31

问题


Which is the right way to allocate memory via new in the C++ constructor. 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.


回答1:


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.




回答2:


The problem is more general. See C++ FAQ Lite: [10.6] Should my constructors use "initialization lists" or "assignment"?




回答3:


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.




回答4:


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.




回答5:


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). 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.




回答6:


If you want to catch memory allocation errors (which you probably should) then you'll have to make the call to new in the body of the constructor.



来源:https://stackoverflow.com/questions/3466309/what-is-the-right-way-to-allocate-memory-in-the-c-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!