防止在返回时复制共享指针

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.

容器在使用时不会发生变化,我希望查询返回共享指针而不进行复制,并且不增加指针的计数器。我该如何确保?

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;
}
评论
reum
reum

您可以使用null对象来允许返回引用:

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;
  }
};
点赞
评论