Class Member Memory Allocation

Discussion in 'C++' started by Jon Rea, Jan 30, 2006.

  1. Jon Rea

    Jon Rea Guest

    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?

    Cheers,
    Jon Rea
    Jon Rea, Jan 30, 2006
    #1
    1. Advertising

  2. Jon Rea

    TB Guest

    Jon Rea sade:
    > 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?
    >


    It's a design question, really.

    --
    TB @ SWEDEN
    TB, Jan 30, 2006
    #2
    1. Advertising

  3. Jon Rea

    Gavin Deane Guest

    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
    Gavin Deane, Jan 30, 2006
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. E11
    Replies:
    1
    Views:
    4,716
    Thomas Weidenfeller
    Oct 12, 2005
  2. Alex Vinokur
    Replies:
    1
    Views:
    398
    Jakob Bieling
    Jul 24, 2003
  3. Ken
    Replies:
    24
    Views:
    3,837
    Ben Bacarisse
    Nov 30, 2006
  4. chris
    Replies:
    6
    Views:
    972
    chris
    Oct 28, 2005
  5. Bjarke Hammersholt Roune
    Replies:
    14
    Views:
    1,170
    Bjarke Hammersholt Roune
    Mar 6, 2011
Loading...

Share This Page