C++ 如何将我自己的智能指针传递给函数?
有一个智能指针类:C++ 如何将我自己的智能指针传递给函数?,c++,c++11,smart-pointers,C++,C++11,Smart Pointers,有一个智能指针类: template <typename T> class UniquePtr { public: UniquePtr(T* obj) : obj(obj) { } UniquePtr(const UniquePtr& ptr) = delete; UniquePtr(UniquePtr&& ptr) { std::cout << "!! use of
template <typename T>
class UniquePtr {
public:
UniquePtr(T* obj)
: obj(obj)
{
}
UniquePtr(const UniquePtr& ptr) = delete;
UniquePtr(UniquePtr&& ptr)
{
std::cout << "!! use of move !!" << std::endl;
obj = std::move(ptr.obj);
ptr.obj = nullptr;
}
UniquePtr& operator=(const UniquePtr& ptr) = delete;
UniquePtr& operator=(const UniquePtr&& ptr) = delete;
~UniquePtr()
{
delete obj;
}
private:
T* obj;
};
如何将UniquePtr
转换为UniquePtr&
使用std::unique\u ptr
这段代码可以工作。就像这样,您需要为类提供一个模板构造函数,该构造函数接受不同类型的UniquePtr
(允许SFINAE处理继承检查),然后将用于初始化UniquePtr
的状态
template<typename U>
UniquePtr(UniquePtr<U> && other) {
obj = other.obj;//Won't compile if U is not a subclass of T.
other.obj = nullptr;
}
模板
UniquePtr(UniquePtr&其他){
obj=other.obj;//如果U不是t的子类,则不会编译。
other.obj=nullptr;
}
(没有时间给出完整答案)提供了一个使转换成为可能的构造函数:模板唯一\U ptr(唯一\U ptr&&U)无例外代码>您需要复制该功能这很奇怪:obj=std::move(ptr.obj)代码>,obj
是指针。@YSC,是的,你是对的,不需要:)谢谢,它能用。但是,我创建的构造函数是这样的:`template UniquePtr(UniquePtr&&ptr){obj=ptr.get();ptr.reset();}`代码>。它让我可以接触私人会员
void function(UniquePtr<Test>&& ptr)
{
std::vector<UniquePtr<Test>> v;
v.push_back(std::move(ptr));
}
UniquePtr<Test> ptr(new Test);
function(std::move(ptr));
class TestChild : public Test {
public:
TestChild()
{
std::cout << "Test child is created" << std::endl;
}
TestChild(const TestChild& obj) = delete;
TestChild(const TestChild&& obj) = delete;
TestChild& operator=(const TestChild& obj) = delete;
TestChild& operator=(const TestChild&& obj) = delete;
virtual ~TestChild()
{
std::cout << "Test child is destructed" << std::endl;
}
};
UniquePtr<TestChild> ptr(new TestChild);
function(std::move(ptr));
error: invalid initialization of reference of type ‘UniquePtr&&’ from
expression of type ‘std::remove_reference&>::type {aka UniquePtr}’
function(std::move(ptr)); ~~~~~~~~~^~~~~
template<typename U>
UniquePtr(UniquePtr<U> && other) {
obj = other.obj;//Won't compile if U is not a subclass of T.
other.obj = nullptr;
}