最近,我經常通過爲operator=
分配一個新值來重置對象。我的大多數課程都使用「複製和交換」慣用語定義了copy constructor
和operator=
。在大多數情況下,它工作正常,雖然效率不如以前,但大多並不重要。有一種情況下,這不起作用。它的時候需要在新對象的constructor
之前調用destructor
。重置對象
注:最讓我使用這個類是不可複製
class Foo
{
public:
Foo() : m_i(0) {}
Foo(int i) : m_i(i) {}
Foo(Foo&& rhs);
Foo& operator=(Foo rhs);
friend void swap(Foo& lhs, Foo& rhs);
private:
Foo(Foo& rhs) {} // uncopyable object
int m_i;
};
Foo::Foo(Foo&& rhs)
: Foo()
{
swap(*this, rhs);
}
Foo& Foo::operator=(Foo rhs)
{
swap(*this, rhs);
return *this;
}
void swap(Foo& lhs, Foo& rhs)
{
using std::swap;
swap(lhs.m_i, rhs.m_i);
}
int main()
{
Foo f(123);
f = Foo(321); // at one time both Foo(123) and Foo(321) exist in memory
}
然後我教給可能改寫operator=
先手動調用destructor
然後做swap
(在這種情況下rhs
會採用const引用)。然而this answer on stackOverflow讓我覺得不然。
我真的很喜歡operator =重置我的對象,因爲代碼是乾淨的,和內置類型(如int)相同。它還使用constructor
和destructor
的代碼,因此不需要編寫和維護額外的代碼。
所以我的問題是:有沒有一種方法來實現我的目標,用乾淨的代碼重置我的對象,並且沒有額外的代碼要寫入,並且在構建新對象之前破壞對象?
我可以使用放置新語法來編寫reset()方法。感謝這個想法。 – rozina