-1

This is a follow up of C++ : Coverity reports leaks for peculiar use of references and containers

Question: *b is allocated on the heap ( new B() ) but where are a_vector and its elements stored? What happens when new elements are pushed into a_vector?

int main()
{
    ...
    B* b = new B();
    A a;
    b->add_a_to_b( a );
    ...
    delete (b);
}

class B {
public:
    std::vector<A> a_vector;
    void add_a_to_b( const A& a )
    {
       a_vector.push_back( a );
    }
Community
  • 1
  • 1
unshul
  • 269
  • 3
  • 16
  • `a_vector` is stored on the heap with the rest of `b`, since you asked for that with `new` (of course, it depends on how `new` is overridden for instances of `B`). The contents of `a_vector` are stored in an implementation-defined way, most probably on the heap too. – Frédéric Hamidi Jan 04 '16 at 22:18

1 Answers1

3

a_vector is a member of class B so, when creating a new B the memory is allocated along with the rest of the B (aka what you describe as "on the heap").

When elements are added to the vector, the vector's member functions (like push_back() use the vector's allocator as needed. How/where the allocator does that depends on the allocator.

Peter
  • 35,646
  • 4
  • 32
  • 74
  • Thanks. What is the default behaviour of the allocator on an x86 machine? – unshul Jan 04 '16 at 22:22
  • 1
    That is up to the implementer of your standard library - there is not a general answer for a particular machine architecture, and implementers of different libraries (e.g. with different compilers) might choose to do different things, even if targeting the same machine. There is also nothing stopping you from defining your own allocator (as long as you meet all requirements of an allocator) that manages memory using some funky technique and using that with your containers. That's why I said "it depends on the allocator". – Peter Jan 04 '16 at 22:27