Home > front end >  Initializing a member pointer with a dynamically allocated pointer
Initializing a member pointer with a dynamically allocated pointer

Time:01-18

Is it possible and good practise to initialize a member pointer with a dynamically allocated pointer? Should I delete the pointer in the destructor?

class Apple
{
  public:
    Apple(int* counter) : counter_(counter);
    ~Apple(); // should I delete counter_ here?
  private:
    int* counter_;
}

int main()
{
  someptr = new int;
  apple_fruit = Apple(someptr);
  delete someptr;

  return 0;
}

I am fairly new to C and still have some confusion on how best to deal with dynamically allocated memory especially when its used for initialization.

CodePudding user response:

Yes, it's possible to initialize a member pointer with a pointer to dynamically allocated data. I've seen this done in instances where a class needs access to an instance of another (dynamically allocated) class.

It's good practice only if you absolutely need to do it. If it's simply an integer we're dealing with (as in your example) then don't use a pointer and store the actual integer instead.

For deletion, do not delete the pointer in the class destructor unless it's your class that originally allocated the data. Your instinct was correct to delete it in main() because it was created in main().

CodePudding user response:

createIterator shouldn't be creating a pointer. It should instead create an instance of ConcreteIterator and return that instead of dynamically allocating memory. However if we decide to create a pointer anyway, I suppose it should be deleted in a new function "ConcreteAggregate::destroyIterator" that's called from main.

cag_, cag, and ag all point to the same data. That's kinda what shallow copy means. So if cag_ is deleted, it will delete what the ag pointer points to.

  •  Tags:  
  • Related