[英]Problems with implementation of unique_ptr's move constructor
我正在嘗試編寫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嗎?
請丟棄與描述的問題無關的任何其他實施故障。 它正在進行中。
1)默認的移動構造函數不知道您的類的語義。 所以它移動指針rhs
,但它不會重置另一個指針,這個指針也將被刪除。
2) *rhs
調用operator*
並返回臨時/ rvalue 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*
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.