[英]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.我有一个从
std::map
派生的容器,它包含共享指针,以及一个用于查找元素的自定义方法,类似于下面的代码。
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:您可以使用 null object 来允许返回参考:
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;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.