简体   繁体   中英

Smartpointers equivalent

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();

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();

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.

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