【发布时间】:2019-05-17 00:47:57
【问题描述】:
我正在尝试编写一个 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_ptr 类模板中的方法。编译器是否只是假设它是 T?
请放弃与所述问题无关的任何其他实施错误。正在进行中。
【问题讨论】:
标签: c++ move-semantics unique-ptr move-constructor