类(包括结构和动态变量)存储在哪里?

时间:2015-01-29 12:25:18

标签: c++ struct

假设我有以下课程:

class message
{
    private:
        HeaderType header;
        // Message text
        byte * text;    

    public:
        message(int ID,struct in_addr senderIP);
        ~message();
        HeaderType getHeader();
        byte * getText();
};

其中HeaderType是一个结构,如下所示:

typedef struct {
    int mID;
    struct in_addr mIP;
}HeaderType;

存储的类(包括结构和动态变量)在哪里(Stack,heap ...)?

P.S。我将message m声明为静态变量。

2 个答案:

答案 0 :(得分:3)

  

类存储在堆栈中,而结构体在免费存储区中分配

这根本不正确。它们是相同的,除了struct成员默认为public,默认情况下class成员为private

分配内存的地方完全取决于你实例化对象。

Foo a;             // instantiated on the stack
Foo b* = new Foo;  // on the heap

如果上面的Foostructclass并不重要,它们的行为方式相同。

在您的示例中,成员byte* text;将与您的班级一起分配。更明确地说,如果在堆栈上实例化message,则会在堆栈上分配text;如果在堆上实例化message,则会在堆上分配text

话虽如此,被指向的对象的位置不必与指针的位置相同。例如

int* x;               // This is a pointer declared on the stack

int a = 5;            // This is an int declared on the stack
int* b = new int(5);  // This is an int declared on the heap

x = &a;       // pointing to a stack object
x = b;        // pointing to a heap object
x = nullptr;  // pointing to nothing!

因此,您可以看到实际指针的内存和指向的对象的内存不相关。实际上,在最后一行中,指针已实例化,但指向nullptr

答案 1 :(得分:1)

对于您更正的问题:

message的静态实例将位于数据段。每个非指针成员(包括HeaderType的成员)的内存在编译时保留。在程序开始时将调用messageHeaderType的构造函数,它们将初始化此内存。

如果message的构造将为byte* text分配内存,则此内存将位于堆中。