Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

smart pointer the element of a std::pair

I have a function which return a std::pair<objectA*, objectB*>. The documentation of the function says that it is my responsibility to deallocate the two elements. Now I am simply doing:

{
  std::pair<objectA*, objectB*> the_pair;

  ...

  if (condition) {
     delete the_pair.first;
     delete the_pair.second;
     return;
  }

  ...

  delete the_pair.first;
  delete the_pair.second;
}

how can I use smart pointer to automate the deletion of the two elements when the_pair goes out of scope?

like image 245
Ruggero Turra Avatar asked Feb 18 '26 14:02

Ruggero Turra


2 Answers

If I understand correctly, it is the responsibility of the caller to delete the pointers. In that case, you could create a unique_ptr managing each element of the pair:

{ // some scope

  std::pair<objectA*, objectB*> the_pair = the_function();
  std::unique_ptr<objectA> pfirst(the_pair.first);
  std::unique_ptr<objectB> psecond(the_pair.second);

} // pointers get deleted

Alternatively, you can write your own scope guard:

struct pointer_pair_guard
{
  pointer_pair_guard(std::pair<objectA*, objectB*>& p) : p_(p) {}
  ~pointer_pair_guard() 
  { 
    delete p_.first;
    delete p_.second;
  }
  pointer_pair_guard(const pointer_pair_guard&) = delete;
  pointer_pair_guard& operator=(const pointer_pair_guard&) = delete;
  private:
    std::pair<objectA*, objectB*>& p_;
};

then

{ // some scope

  std::pair<objectA*, objectB*> the_pair = the_function();
  pointer_pair_guard gd(the_pair);

} // pointers get deleted
like image 148
juanchopanza Avatar answered Feb 21 '26 04:02

juanchopanza


I'd be tempted to stub the function and use the stub.

std::pair<
    std::shared_ptr<objectA>,
    std::shared_ptr<objectB>
> nice_foo(...)
{
    std::pair<objectA*, objectB*> temp = bad_foo(...);    
    return std::pair<
        std::shared_ptr<objectA>,
        std::shared_ptr<objectB>
    >(std::shared_ptr<objectA>(temp.first), std::shared_ptr<objectB>(temp.second));
}

In your code, instead of calling bad_foo, call nice_foo. The returned pair owns the memory so you don't need to worry about deleting it.

like image 26
Bathsheba Avatar answered Feb 21 '26 02:02

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!