Ami*_*mit 4 c++ dynamic-allocation
我试图在一个非常简单的C++程序中动态分配(它现在不是那么动态,但最终会是)对象的内存.我是班级新手,最近才开始玩C++,让C落后.这是代码:
#include <iostream>
using namespace std;
class Test {
private:
int i;
public:
Test(int);
~Test();
void print();
};
Test::Test(int ii) { i = ii; }
Test::~Test() { i=0; cout << "deconstructor called...value of i= " << i << endl; }
void Test::print() { cout << "value of i= " << i << endl; }
int main()
{
Test a(10),*b,*c;
//a.print(); // this works
b = new Test(12);
//b->print(); // this works as well
for (int i=0; i<2; i++)
c = new Test(i);
c->print(); /* this shows that the value of i=1 .. should be 0? */
c[0].print(); /* as expected (I guess), this prints i=1 as well... [expected because c->print() shows i=1 also */
c[1].print(); /* shows value of i=0... */
//delete []c; /* this fails miserably, but `delete c` works, why :( */
}
Run Code Online (Sandbox Code Playgroud)
我的很多困惑实际上都包含在代码本身的注释中.我基本上试图有一个数组c,其中数组的每个元素都是它自己的对象.
我收到的代码的行为在评论中描述.
给定代码几乎没有严重问题.
new上*b,但错过了delete它.*c在for循环中覆盖了几次,这会泄漏内存.始终在从指针分配新资源之前释放资源.new/new[]/malloc则必须delete/delete[]/free分别取消分配指针.同样你没有维持*c(这就是它失败的原因).此外,除了学习动态分配之外,还应该了解STL容器,它提供了处理动态资源的更好方法.例如std :: vector.
也许我们应该看看声明,扩展你有:
Test a(10);
Test *b;
Test *c;
Run Code Online (Sandbox Code Playgroud)
您已将b和c定义为指向测试的指针,但您似乎希望c成为指向测试的指针数组.你想要的声明可能是:
Test **c;
Run Code Online (Sandbox Code Playgroud)
你要初始化的:
c = new Test*[2];
for (int i=0; i<2; i++)
c[i] = new Test(i);
Run Code Online (Sandbox Code Playgroud)
并且您将访问它:
c[0]->print();
c[1]->print();
Run Code Online (Sandbox Code Playgroud)