C++ 中对象的动态内存分配
我正在尝试为非常简单的 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 :( */
}
我的很多困惑实际上都包含在代码本身的注释中。我基本上试图拥有一个数组 c ,其中数组的每个元素都是其自身的对象。
我得到的代码的行为在注释中描述。
I'm trying to dynamically allocate (it's not so dynamic as it is right now, but eventually it will be) memory for objects in a very simple C++ program. I'm new to classes and have only recently started playing with C++, leaving C behind. Here's the code:
#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 :( */
}
A lot of my confusion is actually included within comments in the code itself. I'm basically trying to have an array c where each element of the array is an object of itself.
The behavior of the code that I'm getting is described in the comments.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
也许我们应该看看扩展后的声明:
您已将 b 和 c 定义为指向 Test 的指针,但您似乎希望 c 成为指向 test 的指针数组。您想要的 c 声明可能是:
您将初始化它:
并且您将因此访问它:
Perhaps we should look at the declarations, expanded you have:
You have defined b and c as pointer-to-Test, but you seem to want c to be an array of pointer-to-test. The declaration for c you intended was likely:
which you would initialize:
and which you would access thus:
给定的代码几乎没有严重的问题。
*b
上执行new
,但错过了删除
。for
循环中多次覆盖*c
,这会泄漏记忆。始终在分配新资源之前释放资源
一个指针。
new/new[]/malloc
进行分配,那么您必须分别使用
delete/delete[]/free
释放指针。这与您不使用
*c
维护的情况相同(这就是它失败的原因)。另外,除了学习动态分配之外,还应该了解STL容器,它提供了一种更好的处理动态资源的方法。例如 std::vector。
There are few serious problems with the given code.
new
on*b
but missed todelete
it.*c
few times infor
loop, which will leakmemory. Always deallocate resources before allocating a new one from
a pointer.
new/new[]/malloc
then you mustdeallocate the pointer with
delete/delete[]/free
respectively. Thesame you are not maintaining with
*c
(that's why it fails).Also, apart from learning dynamic allocation one should also be aware of STL containers, which provide a better way of handling dynamic resources. e.g. std::vector.
上面的代码会泄漏内存。
c
只是指向循环迭代中最后构造的对象。这里
c
指向在new Test(1);
上构造的位置。所以,输出。每个new[]应该伴随delete[]并且new伴随delete。两者不能混合。
The above code leaks the memory.
c
just point to the lastly constructed object in the loop iteration.Here
c
points to location constructed onnew Test(1);
. So, the output.Every new[] should be accompanied with delete[] and new with delete. You cannot intermix both.
delete[]
不起作用是完全正常的:您从未将 c 分配为数组,而是分配为指针。您可以将数组的地址存储在指针中,但仅此而已。我实际上想知道为什么 c[1] 有效,因为您的 for 循环只是在同一指针中重复存储指向新分配对象的指针(您没有填充数组!)。That the
delete[]
doesn't work is perfectly normal: you never allocated c as an array, but as a pointer. You could store the address of an array in a pointer, but that's all. I'm actually wondering why exactly c[1] works, because yourfor
loop just stores repeatedly pointers to newly allocated objects in the same pointer (you are not populating an array!).删除c[];
只删除起始元素。如果你想删除该数组,请在 for 循环中使用 dz delete c[]
你未能为 c 分配内存并继续编写错误的代码,如何在不为指针变量分配内存的情况下获得输出?
delete c[];
Only deletes starting element. If you want to delete that array use
dz delete c[]
in for loopYou failed to allocate memory for c and keep on coding its wrong how can you get a output without allocating memory to a pointer variable?
根据我的说法,您已经为 *c 分配了多次内存,
请看一下这段代码,这将使一切变得清晰
So替换会更好,
但根据我的说法,用
如果您希望输出为 i=0 且then i=1 然后这样做-
上面的代码将完全满足您的需求。
See according to me , you have allocated memory for *c multiple times as
Have a look on this code, which will make everything clear
But According to me , it would be more fine to replace
with
So if you want output as i=0 and then i=1 then do so-
The above code is what which will completely satisfy your need.