C++ 中对象的动态内存分配

发布于 2024-11-26 05:36:52 字数 1078 浏览 1 评论 0原文

我正在尝试为非常简单的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

去了角落 2024-12-03 05:36:52

也许我们应该看看扩展后的声明:

Test a(10);
Test *b;
Test *c;

您已将 b 和 c 定义为指向 Test 的指针,但您似乎希望 c 成为指向 test 的指针数组。您想要的 c 声明可能是:

Test **c;

您将初始化它:

c = new Test*[2];

for (int i=0; i<2; i++)
   c[i] = new Test(i);

并且您将因此访问它:

c[0]->print();
c[1]->print();

Perhaps we should look at the declarations, expanded you have:

Test a(10);
Test *b;
Test *c;

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:

Test **c;

which you would initialize:

c = new Test*[2];

for (int i=0; i<2; i++)
   c[i] = new Test(i);

and which you would access thus:

c[0]->print();
c[1]->print();
猫性小仙女 2024-12-03 05:36:52

给定的代码几乎没有严重的问题。

  1. *b 上执行 new,但错过了删除
  2. 您在 for 循环中多次覆盖 *c ,这会泄漏
    记忆。始终在分配新资源之前释放资源
    一个指针。
  3. 如果您使用 new/new[]/malloc 进行分配,那么您必须
    分别使用delete/delete[]/free释放指针。这
    与您不使用 *c 维护的情况相同(这就是它失败的原因)。

另外,除了学习动态分配之外,还应该了解STL容器,它提供了一种更好的处理动态资源的方法。例如 std::vector

There are few serious problems with the given code.

  1. Performing new on *b but missed to delete it.
  2. You are overwriting *c few times in for loop, which will leak
    memory. Always deallocate resources before allocating a new one from
    a pointer.
  3. If you are allocating with new/new[]/malloc then you must
    deallocate the pointer with delete/delete[]/free respectively. The
    same 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.

此生挚爱伱 2024-12-03 05:36:52
for (int i=0; i<2; i++)
    c = new Test(i);

上面的代码会泄漏内存。 c 只是指向循环迭代中最后构造的对象。

c->print(); /* 这表明 i=1 的值应该是 0?

这里c指向在new Test(1);上构造的位置。所以,输出。

每个new[]应该伴随delete[]并且new伴随delete。两者不能混合。

for (int i=0; i<2; i++)
    c = new Test(i);

The above code leaks the memory. c just point to the lastly constructed object in the loop iteration.

c->print(); /* this shows that the value of i=1 .. should be 0?

Here c points to location constructed on new Test(1);. So, the output.

Every new[] should be accompanied with delete[] and new with delete. You cannot intermix both.

快乐很简单 2024-12-03 05:36:52

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 your for loop just stores repeatedly pointers to newly allocated objects in the same pointer (you are not populating an array!).

罪#恶を代价 2024-12-03 05:36:52

删除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 loop

You 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?

江湖彼岸 2024-12-03 05:36:52

根据我的说法,您已经为 *c 分配了多次内存,

for (int i=0; i<2; i++)
c = new Test(i);

请看一下这段代码,这将使一切变得清晰

for (int i=0; i<2; i++)
{   c = new Test(i);    }       /*see , here the loop goes for i=0; then
                                for i=1; which basically overwrites what c will have
                                 i.e. finally       c = new test(1); */
c->print(); /* works fine , gives value of i=1 */
c[0].print(); /* as expected , this prints i=1 as well... */
c[1].print(); /*clearly, it will give a garbage value */
delete c;

So替换会更好,

for (int i=0; i<2; i++)
{   c = new Test(i);    }

但根据我的说法,用

c = new Test(1);    //as the previous code is doing the same in for loop but that was consuming more resources

如果您希望输出为 i=0 且then i=1 然后这样做-

c = new int(0);
c->print(); /* works fine , gives value of i=0 */
c[0].print(); /* as expected , this prints i=0 as well... */
delete c;

c = new int(1);
c->print(); /* works fine , gives value of i=1 */
c[0].print(); /* as expected , this prints i=1 as well... */
delete c;

上面的代码将完全满足您的需求。

See according to me , you have allocated memory for *c multiple times as

for (int i=0; i<2; i++)
c = new Test(i);

Have a look on this code, which will make everything clear

for (int i=0; i<2; i++)
{   c = new Test(i);    }       /*see , here the loop goes for i=0; then
                                for i=1; which basically overwrites what c will have
                                 i.e. finally       c = new test(1); */
c->print(); /* works fine , gives value of i=1 */
c[0].print(); /* as expected , this prints i=1 as well... */
c[1].print(); /*clearly, it will give a garbage value */
delete c;

But According to me , it would be more fine to replace

for (int i=0; i<2; i++)
{   c = new Test(i);    }

with

c = new Test(1);    //as the previous code is doing the same in for loop but that was consuming more resources

So if you want output as i=0 and then i=1 then do so-

c = new int(0);
c->print(); /* works fine , gives value of i=0 */
c[0].print(); /* as expected , this prints i=0 as well... */
delete c;

c = new int(1);
c->print(); /* works fine , gives value of i=1 */
c[0].print(); /* as expected , this prints i=1 as well... */
delete c;

The above code is what which will completely satisfy your need.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文