473,837 Members | 1,601 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

classes, pointers, vectors, and memory allocation

Hi,

I'm having a little trouble figuring out the difference in terms of
memory allocation between:

class person_info;

class A {

private:
vector<person_i nfo> list;
};
class B {

private:
vector<person_i nfo*> list;
};

int func1() {

A* ptr1 = new A();
B* ptr2 = new B();

person_info info_stack;
person_info* info_heap = new person_info();
}

ptr1 and ptr2 will be dynamically allocated in the heap, but when I add
info_stack to ptr1's vector list, info_stack will be copied into the
heap??? Or will info_stack still reside in the stack? If it is added
into the heap, does A's memory get enlarged as a whole chunk? If there
is not enough space for the whole chunk, will A get copied into another
chunk in the heap big enough to fit it?
What happens when I exit func1 and info_stack gets destroyed, what will
happen to the info_stack I put into the vector in ptr1? Can I still
access it and keep using it?

When i add info_heap to ptr2's vector list, will the memory of B in the
heap be enlarged as a whole chunk?
Sorry for so many questions, but I've been really confused about this
for a while.

Thanks for any help, and for reading this!
John G

Jul 23 '05 #1
2 2653
mo*****@gmail.c om wrote:
Hi,

I'm having a little trouble figuring out the difference in terms of
memory allocation between:

class person_info;

class A {
private:
vector<person_i nfo> list;
};

class B {
private:
vector<person_i nfo*> list;
};
The first class contains a vector of person_info, whereas the second
contains a vector of pointer-to-person_info.
int func1()
{
A* ptr1 = new A();
B* ptr2 = new B();

person_info info_stack;
person_info* info_heap = new person_info();
}

ptr1 and ptr2 will be dynamically allocated in the heap, but when I add info_stack to ptr1's vector list, info_stack will be copied into the
heap???
Standard containers like vector are value-oriented, meaning they
store copies of whatever objects you add to them. So yes, info_stack
will be copied to wherever the vector stores its contents, which is
probably a chunk of memory allocated on the 'heap' (called the
'free store' by the C++ standard).
Or will info_stack still reside in the stack?
info_stack still exists on the 'stack' ('free store' in standardese)
and will continue to do so until it passes out of scope. The vector
ptr1->list contains a separate person_info object which was created
by copying info_stack. These are now two separate objects.
If it is added
into the heap, does A's memory get enlarged as a whole chunk? If there is not enough space for the whole chunk, will A get copied into another chunk in the heap big enough to fit it?
The size of A doesn't change over time. In fact, sizeof(A) is a
constant known at compile time. However, many objects allocate memory
dynamically (from the free store, aka., heap). For example, a vector
typically contains a pointer to a memory buffer that contains the
elements of the vector. The vector allocates the memory, manages it,
and eventually frees it. All that memory management is part of the
internal implementation of vector and is hidden from you.
What happens when I exit func1 and info_stack gets destroyed, what will happen to the info_stack I put into the vector in ptr1? Can I still
access it and keep using it?
Yes, the vector stores a copy, not the object itself.
When i add info_heap to ptr2's vector list, will the memory of B in the heap be enlarged as a whole chunk?


Same as above, sizeof(vector) doesn't change, but the total memory
used by a vector might change over time because the vector can
allocate memory from the free store.

As to the difference between the two vectors, the key to understanding
a vector of pointers (or pointers generally) is that the pointer and
the thing it points to (the pointee) are two distinct objects. Let me
explain with another example:

void f()
{
int n = 1;
int* p = new int(2);

// There are now two objects on the 'stack' (n and p) and one
object
// on the 'heap' (the integer p points to).

vector<int> v;
v.push_back(n);
v.push_back(*p) ;

// We now have a third object on the 'stack' (v), which is a
// vector containing two objects of type int. Vectors and other
// standard containers are value-oriented, meaning they store
// *copies* of the objects you add to them. Thus, we now have a
// total of four integers, n, *p, v[0], and v[1]. Where are the
// last two integers? Wherever the vector decides to put them.
// Most likely, it will have allocated some memory on the 'heap',
// but the point is it's the vector's job to manage that memory
// (including freeing it when the vector itself is destroyed)
// so you don't need to care.

vector<int*> w;
w.push_back(p);
w.push_back(&n) ;

// The fourth object on the 'stack' (w) is also a vector, and it
// two contains two objects, in this case of type pointer-to-int.
// A key to understanding pointers in C++ is that a pointer is an
// object in its own right, distinct from the thing it points to
// (the 'pointee'). We've added two pointers to w (p and the
// address of n) and it has stored copies of them. It 'owns' those
// copies and is responsible for eventually freeing them -- just
// like the vector of ints -- but it's important to understand
// that w's ownership only extends to the pointers themselves, not
// to the objects they point to.
//
// That's why, when you have a vector of pointers, it is up to
// *you* to manage the lifetime of whatever objects those pointers
// point to. The vector only 'owns' the pointers themselves; and a
// raw pointer (unlike some 'smart pointer' classes) doesn't 'own'
// anything.
//
// Since you asked about memory layout, here's a diagram of what
// our program might look like so far:
//
// 'stack' 'heap'
//
// +-------+
// n | 1 | <-----------------------+
// +-------+ |
// +-------+ +-------+ |
// p | * ---------> | 2 | <--+ |
// +-------+ +-------+ | |
// +-------+ | |
// v | ... | +-------+ | |
// | * ---------> | 1 | | |
// | ... | +-------+ | |
// +-------+ | 2 | | |
// +-------+ +-------+ | |
// w | ... | +-------+ | |
// | * ---------> | * -------+ |
// | ... | +-------+ |
// +-------+ | * -----------+
// +-------+
//
// From the preceding discussion, it should be clear that we (not
// the vector w) are responsibe for eventually deleting the object
// we earlier allocated using new. So here we go:

delete p;

// How should one describe the statement above? Many people would
// say we just 'deleted the pointer p.' That's fine as long as you
// understand that it's not precisely true. What we've actually
// deleted is the pointee, the integer p pointed to. The pointer
// object itself (i.e., p) still exists, although now it holds
// an invalid pointer value, which means we're not allowed to do
// anything with it except assign to it.

p = &n; // p still exists; let's assign to it just to show we can
p = NULL; // another equally useless assignment
}

Jul 23 '05 #2
Thanks for the nice detailed reply! It helped alot in my understanding
:)

Regards,
John G

Jul 23 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
18676
by: spoc | last post by:
I have been using memcpy to copy one class to another of the same type. There are reasons why I had to do this bug am getting some odd crashes and maybe I'm doing something dodgy copying classes like this? The classes contain no dynamicaly allocated data, just standard types and arrays. Here is an example of what I'm doing, I know in isolation it may seem odd. I am presuming this will copy all data ok but not really sure of the workings and...
4
3106
by: Venn Syii | last post by:
I've searched all the forums but cannot find an answer to this question. I do the following: vector<MyClass*> myClassList; Later in the program I try to add to myClassList with a .push_back(...) I get an "out of memory" runtime error. I know I'm not out of memory because normal vectors such as vector<int> a, still work, and still work fine.
4
2029
by: Dr. J.K. Becker | last post by:
Hi all, I have vectors that holds pointers to other vectors, like so: vector<whatever> x; vector<whatever*> z; z=&x; Now I add something to x
7
2155
by: enki | last post by:
What I want to do is create sprites and put them in a vector. I know that this specific example dosn't realy fit in this group but my sprite are ponters. vector<*sprite>spvec; sprite * mysprite new sprite(....); when I create a sprite \:
7
4695
by: toton | last post by:
Hi, I have a STL vector of of characters and the character class has a Boost array of points. The things are vector<Characterchars; and class Character{ private: array<Point,Npoints; }; Now are the memory layout is contiguous? i.e all the character resides side by side just like array, and all Points side by side insede the
5
18292
by: madhu | last post by:
http://msdn2.microsoft.com/en-us/library/fs5a18ce(VS.80).aspx vector <intv1; v1.push_back( 10 ); //adds 10 to the tail v1.push_back( 20 ); //adds 20 to the tail cout << "The size of v1 is " << v1.size( ) << endl; v1.clear( ); //clears the vector I have a few questions:
5
2116
by: Renato | last post by:
I have an array of pointers to class Shape. I create 4 items and display their values. shapes Shape *shapes; shapes = new Shape (p1); shapes = new Triangle (p1); shapes = new Polygon (p2);
4
1809
by: tech | last post by:
Hi, I need to pass a block of say 320 bytes memory between some classes which do various processing on it. The app needs to be quick so i can't keep copying. The simplest way is via pointer say: class A {
7
3138
by: ademirzanetti | last post by:
Hi there !!! I would like to listen your opinions about inherit from a STL class like list. For example, do you think it is a good approach if I inherit from list to create something like "myList" as in the example below ? #include "Sector.h" using namespace boost;
0
9696
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10902
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10642
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10288
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9420
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7824
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7014
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4481
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4062
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.