Jon Rea wrote:
Following up on: > Any reason for creating iv dynamically?
in "Re: Namespace and #Include best practises"
What are the rules for when member data should be created as new memory
with a member pointer vs as just a member?
One case where you would definitely use dynamic allocation, which may
well be helpful in the issue in your previous post about header file
dependencies, is the pimpl idiom.
http://www.gotw.ca/gotw/024.htm
If the member data is an abstract base class pointer and you only know
at run time which particular derived concrete type you need, then
dynamic allocation is necessary there too. The Strategy Pattern is, I
believe, an example.
Bear in mind that with member pointers and dynamic allocation you are
into "Rule of Three" territory. The compiler generated copy
constructor, assignment operator and destructor will probably be wrong
so you will need to write your own. Smart pointers can help, but with
member objects rather than pointers the problem goes away.
It's really a design decision, but I'd start with: Use a member object
when you can and a member pointer with dynamic allocation when you have
to.
Gavin Deane