如何以最简洁的方式向unique_ptr传递一个什么都不做的自定义删除器?我需要为我正在编写的JNI函数提供支持,其中C++端期望一个unique_ptr,但是我不希望在退出JNI函数时删除unique_ptr所持有的对象 - 我稍后会处理删除。因此,我想做类似以下的事情:
std::unique_ptr<MyClass, noop_delete> ptr;
一行代码实现 - 不需要单独的函数定义 :-)
如何以最简洁的方式向unique_ptr传递一个什么都不做的自定义删除器?我需要为我正在编写的JNI函数提供支持,其中C++端期望一个unique_ptr,但是我不希望在退出JNI函数时删除unique_ptr所持有的对象 - 我稍后会处理删除。因此,我想做类似以下的事情:
std::unique_ptr<MyClass, noop_delete> ptr;
struct nop
{
template <typename T>
void operator() (T const &) const noexcept { }
};
template <typename T>
using nop_unique_ptr = std::unique_ptr<T, nop>;
std::unique_ptr
具有“独一无二”的含义,同时您也不会因为错误而删除 std::unique_ptr
。这两个属性可能是需要的,而不需要删除指向的对象。 - Fabio A.关于 std::unique_ptr::release
怎么样?就像这样
void JNIfunc (T*) {};
std::make_unique( new T) t;
JNIfunc( t.release);
在@lisyarus的回答评论中,我的回答促使我想出一个比我之前提供的更好的解决方案。这个解决方案涉及到@lisyarus已经提到的事实:一个no-op删除器unique_ptr
与有一个delete
删除器的unique_ptr
是不同类型的。
我将其作为一个单独的答案发布,因为它可能与其他人相关(此外,这无法适应单个评论)。
上下文:对于单元测试,FakeIt模拟框架管理模拟对象的生命周期,因此当需要模拟通过unique_ptr指向的对象时,我们需要一个具有no-op删除器的unique_ptr。
// As in @lisyarus's answer...
struct nop
{
template <typename T>
void operator() (T const &) const noexcept { }
};
// NOTE: We have no use for a pointer that doesn't delete unless we're mocking, so
// the types below are named to indicate that.
#ifndef WE_ARE_BUILDING_UNIT_TESTS
// Production build - we want a unique_ptr that deletes.
template <typename T>
using mockable_unique_ptr = std::unique_ptr<T>;
#else
// Unit test build - we want unique_ptr that doesn't delete.
template <typename T>
using mockable_unique_ptr = std::unique_ptr<T, nop>;
#endif
std::unique_ptr
呢? - 101010unique_ptr
? - Sam Estep