0
這是我的母語的翻譯。
你有一個類:我的解決方案有什麼問題?
class Boo : public SuperBoo {
Foo* fFoo1;
Foo* fFoo2;
}
其中foo - 單形類和噓聲擁有指針fFoo1,fFoo2。
Boo的重載賦值運算符。
我的解決辦法是:
class Foo
{
public:
Foo()
{}
};
class SuperBoo
{
public:
virtual ~SuperBoo()
{}
};
class Boo : public SuperBoo
{
public:
Boo(const int f1_id, const int f2_id)
{
f1 = new Foo(f1_id);
f2 = new Foo(f2_id);
}
~Boo()
{
delete f1;
delete f2;
}
/* C++11 only
Boo(Boo&& other)
{
std::swap(*this, other);
}
*/
Boo(const Boo& other)
{
f1 = new Foo(*(other.f1));
f2 = new Foo(*(other.f2));
}
Boo& operator=(Boo other)
{
std::swap(f1, other.f1);
std::swap(f2, other.f2);
return *this;
}
private:
Foo* f1;
Foo* f2;
};
但僱主不喜歡它。這裏有什麼問題?感謝幫助。
首先,它並不是特例安全。 – jrok 2013-03-15 11:06:14
同意,我將失去指針,如果新投擲 – 2013-03-15 11:09:14
有一個很好的解決這個異常安全問題的方法:使用內建的[智能指針類]之一(http://en.wikipedia.org/wiki/Smart_pointer# C.2B.2B_smart_pointers),它們使用RAII語言爲您解決內存泄漏問題。 – 2013-03-15 11:14:14