1

There is an equivalent codification in C++ with smartpointers for this code?

In External.cpp:

class ExampleClass {...};

ExampleClass* function()
{
  ExampleClass *ptr = new ExampleClass();
  ptr->doSomething();
  return ptr;
}

In Another.cpp i would like to do something like this properly, how?:

ExampleClass *ptr2 = function();
makiwhtie
  • 51
  • 6
  • 3
    Take a look [here](https://stackoverflow.com/questions/28294620/what-is-the-best-smart-pointer-return-type-for-a-factory-function). The code you provided seems to be a factory function. – Cristian Ionescu Aug 07 '17 at 07:19

2 Answers2

5

There are two actually, you could use either unique_ptr or shared_ptr, look here when to use which: Which kind of pointer do I use when?

I'f you'd opt for the unique_ptr, then you'd get:

class ExampleClass {...};

std::unique_ptr<ExampleClass> function()
{
  std::unique_ptr<ExampleClass> uptr = std::make_unique<ExampleClass>();
  uptr->doSomething();
  return std::move(uptr);
}

//In Another.cpp 
std::unique_ptr<ExampleClass> ptr2 = function();
//you could even store the result in a shared pointer!!
std::shared_ptr<ExampleClass> ptr3 = function();
Lanting
  • 3,060
  • 12
  • 28
1

I won't really recommend it, but you can return an object that implicitly converts to a raw pointer. It will own it for a short duration, and delete if no-one grabs it.

struct RelinquishOrDelete {
  ExampleClass *_ptr;

  operator ExampleClass*() { auto ret = _ptr; _ptr = nullptr; return ret; }

  ~RelinquishOrDelete() {
    if(!_ptr) { 
      cerr << "returned object wasn't taken by a new owner\n";
      delete _ptr;
    }
  }
};

Using it is simple. It will pack and unpack the pointer in this simple case:

RelinquishOrDelete function()
{
  ExampleClass *ptr = new ExampleClass();
  ptr->doSomething();
  return {ptr};
}

// ...

ExampleClass *ptr2 = function();

But of course, it will likely cause unexpected behavior if used in this perfectly reasonable piece of code:

auto ptr3 = function();

A smart pointer with much stricter ownership semantics is really the best approach.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458