Short answer: As Jesse pointed out, you probably want to use a value member or a pointer, but not a reference in this specific example.
Long answer: The memory model of C++ is more like C's and less like Java's. Objects can exist
- on the stack. This is the case for parameters and local variables.
- on the heap. This is the case for all objects created with
new
.
- in the data segment. These are your global variables.
- inside other objects as value members.
As opposed to this, in Java, except for primitive types and pointers (in Java called references), all objects are created with new
and exist on the stack. This simpler memory model is sufficient for Java since it has garbage collector, which automatically destroys unused objects.
Standard C++ does not have a garbage collector. An object is deleted in the following circumstances:
- a stack-based object is deleted when "it goes out of scope",
- a global object is deleted when the application terminates,
- objects contained in other objects are deleted when the containing object is deleted, but
- objects on the heap must be manually deleted by the developer using
delete
.
Because this manual memory management is error prone, you usually define strong ownership policies between the objects in your C++-application.
Coming back to your question, you want to make sure that you can access your member_
as long as your FooBar
-object exists. So if member_
is not something like FooBar
's owner or another in a similar way closely related object, which is guaranteed to exist as long as the FooBar
-object exists, you probably do not want to use a reference.
In your example, I would use
- a value member if I think of
FooBar
containing member_
,
- a pointer otherwise.