调用构造函数分配内存?

时间:2013-09-25 08:13:44

标签: c++

如果构造函数用于分配内存。

在以下程序中,它不起作用。 参见

#include <iostream>

using namespace std;

class Demo
{
    int i;
public:
    Demo()
    {
        cout<<"\nDefault contructor called";
    }
    Demo(int x)
    {
        i = x;
        cout<<"\nParameter contructor called";
    }
    void Display()
    {
        cout<<endl<<"i = "<<i<<endl;
    }
};

int main()
{
    Demo *demo = new Demo[5]; // = {1,2,3,4,5};

    int i;
    cout<<endl<<endl<<"First time";
    cout<<endl<<"Addresses are "<<endl;
    for( i=0;i<5; i++)
    {
        cout<<endl<< &demo[i];
    }
    cout<<endl<<endl<<"first time assigning values";    
    for( i=0;i<5; i++)
    {
        demo[i]= i;
    }

    cout<<endl<<endl<<"\nAfter first assignment";
    cout<<endl<<"Addresses are "<<endl;
    for( i=0;i<5; i++)
    {
        cout<<endl<< &demo[i];
    }
    cout<<endl<<endl<<"Second time assigning values";    
    for( i=0;i<5; i++)
    {
        demo[i]= i+5;
    }
    cout<<endl<<endl<<" After Second assignment ";
    cout<<endl<<"Addresses are "<<endl;
    for( i=0;i<5; i++)
    {
        cout<<endl<< &demo[i];
    }

    for( i=0;i<5; i++)
    {
        demo[i].Display();
    }
    return 0;
}

输出:

Default contructor called
Default contructor called
Default contructor called
Default contructor called
Default contructor called

First time
Addresses are 

0x8281008
0x828100c
0x8281010
0x8281014
0x8281018

first time assigning values
Parameter contructor called
Parameter contructor called
Parameter contructor called
Parameter contructor called
Parameter contructor called


After first assignment
Addresses are 

0x8281008
0x828100c
0x8281010
0x8281014
0x8281018

Second time assigning values
Parameter contructor called
Parameter contructor called
Parameter contructor called
Parameter contructor called
Parameter contructor called

 After Second assignment
Addresses are 

0x8281008
0x828100c
0x8281010
0x8281014
0x8281018
i = 5

i = 6

i = 7

i = 8

i = 9

这里构造函数被调用三次,内存地址相同,意味着它没有分配新内存并使用相同的地址。为什么呢?

为什么构造函数被多次调用?

2 个答案:

答案 0 :(得分:1)

执行此操作时:

demo[i]= i;

i用于使用带有int的构造函数构造临时对象。然后将此临时分配给demo[i]。赋值不会导致demo[i]被重建为具有不同地址的新对象(对象无法重建,并且永远不能更改其地址),它只会导致成员分配成员demo[i]成员的临时成员(除非你提供了一个与你没有做过不同事情的任务操作员。)

答案 1 :(得分:1)

认为构造函数为您的对象分配内存是一个根本的误解。调用构造函数时,您已经拥有分配的内存,无论是在堆栈上还是在堆上。构造函数只准备此内存以便以后使用它。

但是,构造函数通常负责为对象使用的资源分配进一步的内存,即

class Container
{
public:
    Container()
        : ptr_(new int[5])
    {}
    // ...
private:
    int* ptr_;
}