views:

76

answers:

1

Hello, my base class need to expose a method that for some derived classes would return a smart pointer to dynamically allocated array, and for some other derived classes would return a pointer/reference to statically allocated one.

example:

class Base
{
  public:
  virtual ??? foo()=0;
}

class A : public Base
{ 
  private:
  float arr[10];   
  public:
  ??? foo(){ return ???arr; }
}

class B : public Base
{
  public:
  ??? foo(){ 
      allocate array;
      return ???array; 
  }
}

The dynamically allocated array is created inside class method and I would prefer to use a std::unique_ptr. But what should I do for the statically allocated array in class A?

Should I create own class derived from std::unique_ptr that would be aware of pointee allocation and would not try to destroy statically allocated pointee, or maybe there already exist such smart pointers?

+5  A: 

You can provide custom deleters for Boost smart pointers. This can also be an empty function that does not do anything. For the class returning a dynamically allocated array, you can use a standard shared_array, and for the class returning a pointer to a statically allocated array you can return a shared_array with an empty custom deleter.

Note that your problem lies deeper here. Returning a pointer that will be owned by the caller is quit different from returning a pointer owned by the object. You may want to consider not mixing these two in the same function.

Space_C0wb0y