在C ++构造函数中分配内存的正确方法是什么? [英] What is the right way to allocate memory in the C++ constructor?
本文介绍了在C ++构造函数中分配内存的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是在C ++构造函数中通过 new
分配内存的正确方法。参数列表中的第一种方式:
class Boda {
int * memory;
public:
Boda(int length):memory(new int [length]){}
〜Boda(){delete [] memory; }
};
或在构造函数主体中:
class Boda {
int * memory;
public:
Boda(int length){
memory = new int [length];
}
〜Boda(){delete [] memory; }
};
感谢Boda Cydo。
解决方案我认为最简单的方法是使用 boost scoped array ,并让别人测试良好的库代码为你处理。
因此:
class Boda {
boost :: scoped_array< int>记忆;
public:
Boda(int length):memory(new int [length]){}
〜Boda(){}
};
此外,作用域数组不能被复制 - 所以你避免了另一个答案中提到的讨厌的复制构造函数释放问题。
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.
解决方案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.
这篇关于在C ++构造函数中分配内存的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文