简体   繁体   中英

Prevent copy of shared pointer on return

I have a container derived from std::map that holds shared pointers, and a custom method for looking up elements, similar to the code below.

The container does not change while I use it, and I would like the lookup to return the shared pointer without making a copy, and not increment the pointer's counter. How can I ensure this?

struct X;    
using Xp = std::shared_ptr< X >;

struct Xs : std::map< int, Xp >
{
  Xp get( int n ) const {
    auto p = find( n );
    return p != end() ? p->second : nullptr;
  }
};

Xs xs;

void test() {
  // always increments the counter of the shared_ptr :(
  if( auto const& p = xs.get( 5 ) )
    ( void ) p;
}

Edit: I cannot change the container and I cannot return a raw pointer. Is there no way to return a reference to the pointer without changing it?

You might use null object to allow to return reference:

struct Xs : std::map< int, Xp >
{
  const Xp& get( int n ) const {
    static const Xp nullObject{nullptr};
    auto p = find( n );
    return p != end() ? p->second : nullObject;
  }
};

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