我正在尝试编写一个unique_ptr实现。我正在努力写一个移动构造函数。以下是我的问题:
- 当我将移动构造函数标记为
default
时,我的资源会被删除两次,当我移动并分配指针时(下面是auto foo2 = std::move(foo);
(-为什么 - 当我试图在移动构造函数中分配底层指针时,比如
*rhs = nullptr
(见下面的实现(,编译器说*rhs
是一个右值,我不能给它分配任何东西 - 最后,
rhs.m_ptr = nullptr
起作用。为什么*rhs = nullptr
不起作用
我的代码:
#include <iostream>
namespace my
{
template <class T>
class unique_ptr
{
public:
unique_ptr()
{
m_ptr = new T;
}
unique_ptr(const unique_ptr&) = delete;
// move constructor
unique_ptr(unique_ptr&& rhs) // = default deletes m_ptr twice
{
m_ptr = *rhs;
rhs.m_ptr = nullptr; // *rhs = nullptr doesn't work (*rhs is an rvalue)
}
~unique_ptr()
{
delete m_ptr;
}
T* operator->()
{
return m_ptr;
}
T* operator*()
{
return m_ptr;
}
unique_ptr& operator=(const unique_ptr&) = delete;
// no move assignment yet
private:
T* m_ptr;
};
} // namespace my
struct Foo
{
Foo()
{
std::cout << "Foo" << std::endl;
}
~Foo()
{
std::cout << "~Foo" << std::endl;
}
void printHello()
{
std::cout << "Hello" << std::endl;
}
};
int main()
{
my::unique_ptr<Foo> foo;
foo->printHello();
auto foo2 = std::move(foo);
return 0;
}
附带说明一下,显然我可以将不带任何模板参数的unique_ptr传递给unique_ptrclass模板内的方法。编译器只是假设它是T吗?
请丢弃与所描述的问题无关的任何其他实现错误。这是正在进行的工作。
1(默认的move构造函数不知道类的语义。因此,它移动指针rhs
,但不会重置另一个指针,该指针也会在另一个析构函数中被删除。
2(*rhs
调用operator*
并返回一个临时/右值T*
,即内部指针的副本,并且与通常的operator*
不一致,后者应该返回T&
或const T&
。
3( 参见2。您正在返回一个临时对象。
最后,你应该拥有:
unique_ptr(unique_ptr&& rhs) // = default deletes m_ptr twice
: m_ptr(rhs.m_ptr)
{
rhs.m_ptr = nullptr; // *rhs = nullptr doesn't work (*rhs is an rvalue)
}
T& operator*() {return *m_ptr;}
const T& operator*() const {return *m_ptr;}
等等。
你太努力了。您不必通过外部接口。只分配值:
m_ptr = rhs.m_ptr;
rhs.m_ptr = nullptr;
此外,operator*()
应该返回T&
,而不是T*
。