简体   繁体   中英

C++ smart pointer to statically and dynamically allocated resource

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM