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



我有一个派生自std::map的容器,其中包含共享指针,以及用于查找元素的自定义方法,类似于下面的代码。

容器在我使用它时不会更改,我希望查找返回共享指针而不进行复制,并且不增加指针的计数器。我怎样才能确保这一点?

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;
}

编辑:我无法更改容器,也无法返回原始指针。有没有办法在不更改指针的情况下返回对指针的引用?

您可以使用 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;
}
};

最新更新