C++中各种类成员的内存分布

在C++中,标准库里面的容器,如vector,list都可以动态增长,如果把这些容器作为某个class的成员,那么这个class的内存是怎么分配的呢?

写了一个简单的程序测试一下,如下,

#include <string>
#include <vector>
#include <list>
#include <iostream>
using std::string;
using std::vector;
using std::list;
using std::cout;
using std::endl;

class Elem
{
public:
    Elem(int i,string s):index(i),name(s){
        for(int k=0;k<index;k++)
        {
            array.push_back(k);
            tlist.push_back(name);
        }
    }
    void PrintMemAddr(){
        cout << "address test:" << endl;
        cout << "\tthis:\t" << (this) << endl;
        cout << "\tindex:\t" << (&index) << endl;
        cout << "\tarray:\t" << (&array) << endl;
        cout << "\tname:\t" << (&name) << endl;
        cout << "\tlist:\t" << (&tlist) << endl;
    }

private:
    int index;
    vector<int> array;
    string name;
    list<string> tlist;
};

主函数程序如下,

int main()
{
    //double t = 3.14;
    int t = 3;
    cout << "t:\t" << (&t) << endl;

    Elem a(7,"hello");
    a.PrintMemAddr();

    string s = "hello, who are you?";
    cout << "s:\t" << (&s) << endl;

    Elem b(7,"hello");
    b.PrintMemAddr();

    double d = 3.14;
    cout << "d:\t" << (&d) << endl;

    Elem* c = new Elem(17,"who");
    c->PrintMemAddr();

    return 0;
}

最后输出结果如下,

t:    0xbfb55664
address test:
    this:    0xbfb55620
    index:    0xbfb55620
    array:    0xbfb55624
    name:    0xbfb55630
    list:    0xbfb55634
s:    0xbfb5566c
address test:
    this:    0xbfb5563c
    index:    0xbfb5563c
    array:    0xbfb55640
    name:    0xbfb5564c
    list:    0xbfb55650
d:    0xbfb55658
address test:
    this:    0x86df1a8
    index:    0x86df1a8
    array:    0x86df1ac
    name:    0x86df1b8
    list:    0x86df1bc

可以看出,在class里面,数据成员的地址与class里面的顺序一致,vector或者list虽然是动态数据结构,但是放在vector或者list里面的数据并不是放在它们自己的空间里面的,所以它们在class里面所占用的空间是固定的,然后在main函数里面,数据应该都是在栈上的,c是堆上的,地址明显与其它的不太一致。然而,a和b的地址,也就是前两个class的输出,地址基本上连续,潜在它们中间的几个变量,地址不是按先后顺序的,而且是接在a和b后面的,谁能帮我解释下么?

posted @ 2012-11-07 22:15  Frandy.CH  阅读(715)  评论(0编辑  收藏  举报