Reputation: 12140
In C++, what is the difference in making member variables values or pointers? For example, what is the difference between pThread and thread in the following code:
class A {
public:
boost::thread *pThread;
boost::thread thread;
}
Upvotes: 1
Views: 112
Reputation: 19855
The pointer is the name for an address of memory where you allocated something. So it has a fixed size (32 bit on an Intel x86 architecture for example).
This means that when the A
object is created, the pThread
field will always occupy that 32 bits to store the address of memory where the boost::thread
will effectively reside.
If you don't use a pointer, the boost::thread
will be created on its entirety as part of the A
object, so it will occupy a storage as big as a boost::thread
inside the stack, when an A
object is created.
Managing pointers however can be more complicated than using a non-pointer variable: someone will have to allocate (and deallocate) the memory for the boost::thread
, so the pointer will point to a valid address and no memory leaks will be left.
Upvotes: 1
Reputation: 3188
The difference is the memory layout of the object.
Member items are stored like a struct - sequentially and continuously stored in the memory (possibly with 2-4-8 bytes alignment but otherwise sequentially one after the other). Pointers are stored in the memory address as a 4/8 byte pointer while the actual object can be stored anywhere in the memory.
Consider the situation where you have a struct
struct grades {
unsigned char math;
unsigned char english;
unsigned char history;
unsigned char physics;
unsigned char chemistry;
unsigned char biology;
unsigned char computers;
};
The size of the struct is 7 bytes.
Now if you have a class Student_member:
class Student_member {
unsigned long id;
struct grades _grades;
};
and a class Student_pointer:
class Student_pointer {
unsigned long id;
struct grades *_grades;
};
Then the size in memory of the class Student_member would be 4+7=11 bytes (long + the struct) which would be allocated as a continuous block, while the size in memory of class Student_pointer would be 4+4=8 byte (long + pointer) and another 7 bytes that are allocated somewhere else in memory storing the actual grades.
Upvotes: 4
Reputation: 17346
Not very formally, when you have a member pointer, the object pointed by the member doesn't live by the life cycle of the object pointing to it. The object pointed by the pointer can be NULL. You are responsible for creating an instance when you need one (via new) and clearing it up when you don't need it anymore (via delete).
When you have a member instance (instead of a pointer), the instance is created when the constructor of its parent runs and it's destroyed when the parent's destructor runs.
When you have an object through a pointer, that object may be shared among several other objects, so the object holding the pointer is not necessarily the one controlling the pointed object.
Upvotes: 2