-2

Where does a list inside an object gets its stack?

The program below shows a size of the object of 40. So where did the list allocate its memory from?

    class TEST
    {
    public:
        TEST(void);
        void Push(void);
    private:
        std::list<int> _list;
        std::list<int>::iterator _it;
        int f;
    };

    TEST::TEST(void) : f(1)
    {

    }

    void TEST::Push(void)
    {
        _list.push_back(f++);
    }

main:
    {
        TEST n;
        int a = sizeof(n);
        std::cout << a << std::endl;

        n.Push();
        a = sizeof(n);
        std::cout << a << std::endl;

        for(int r=0; r<10000; r++){
            n.Push();
        }
        a = sizeof(n);
        std::cout << a << std::endl;
    }

Output:

40 <br/>
40 <br/>
40
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 3
    Welcome to Stack Overflow! Sounds like you could use a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). `sizeof` does not do what you think it does and is explain in the aforementioned books. – NathanOliver Mar 21 '17 at 17:58
  • Possible duplicate of the presented question _"so where did the list allocate its memory from?"_ http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap/80113 – Drew Dormann Mar 21 '17 at 18:50

2 Answers2

1

Just to add on to the comment about your use of sizeof()

I would take a look at the answer to this question here: Size of class object in C++

Essentially the sizeof() operator only takes into account the members of the class and not any associated heap allocations. Although a member variable, _list is essentially just a pointer to an area of memory on the heap, so it maintains a constant size no matter how many items it is referring to - since in reality it is basically just storing a single address of memory. (It obviously stores some more information than that, but I want to keep it simple)

So no matter what you do to _list, the result of sizeof will remain constant since the actual members within n remain constant size.

Community
  • 1
  • 1
picklechips
  • 746
  • 2
  • 8
  • 28
0

You can use the public method std::list::get_allocator to see where your data is stored.

Here is an example of how you can use it(but just to reaserch, It's not supposed to be used like that):

int main ()
{
  int * ptr;
  // allocate an array of 5 elements using _list's allocator:
  ptr=_list.get_allocator().allocate(5);

  // assign some values to array
  for (int i=0; i<5; ++i) ptr[i]=i;

  std::cout << "The allocated array contains:";
  for (int i=0; i<5; ++i) std::cout << ' ' << ptr[i];
  std::cout << '\n';

  _list.get_allocator().deallocate(ptr,5);

  return 0;
}

BTW: Is not a good idea to name members starting with underscore:

all identifiers that begin with an underscore are reserved for use as names in the global namespace

Rama
  • 3,222
  • 2
  • 11
  • 26