问题描述
我的尝试(下方)在实施
类似智能指针的东西时有什么问题吗?
模板< T级>
级SmartPointer
{
私人:
T * t;
public:
SmartPointer(){t = new T();}
SmartPointer(const SmartPointer< T>& rhs){t = rhs.t;}
T& operator *()const {return(* t);}
T * operator->()const {return(t);}
SmartPointer< T>& ; operator =(const SmartPointer< T>& rhs){t = rhs.t;返回(* this);}
~SmartPointer(){删除t;}
};
我写的程序为了测试这次崩溃,我根本不会这么做,因为我知道我在某处犯了错误。不,我不能使用Boost来实现这一点。
-
Christopher Benson-Manica |我*应该*知道我在说什么 - 如果我
ataru(at)cyberspace.org |不,我需要知道。火焰欢迎。
Is there anything wrong with my attempt (below) at implementing
something resembling a smart pointer?
template < class T >
class SmartPointer
{
private:
T *t;
public:
SmartPointer() {t=new T();}
SmartPointer( const SmartPointer<T> &rhs ) {t=rhs.t;}
T& operator*() const {return(*t);}
T* operator->() const {return(t);}
SmartPointer<T>& operator= ( const SmartPointer<T> &rhs ) {t=rhs.t; return(*this);}
~SmartPointer() {delete t;}
};
The program I wrote to test this crashes, and I wouldn''t be at all
surprised to learn that I''ve made a mistake here somewhere. And no, I
can''t use Boost for this.
--
Christopher Benson-Manica | I *should* know what I''m talking about - if I
ataru(at)cyberspace.org | don''t, I need to know. Flames welcome.
推荐答案
是的。你复制构造函数是错误的。它会成员复制,当它需要做一个深层复制时。
SmartPointer(const SmartPointer< T>& rhs){t = new T (rhs.t); }
适用于您的任务操作员
-
Karl Heinz Buchegger
是的。你复制构造函数是错误的。当它应该进行深层复制时,它会进行成员复制。
SmartPointer(const SmartPointer< T>& rhs){t = new T(rhs.t); }
你的任务操作员也一样
Yep. You copy constructor is wrong. It does a memberwise copy, when
it should do a deep copy.
SmartPointer( const SmartPointer<T> &rhs ) {t = new T( rhs.t ); }
same for your assignment operator
实际上,任务操作员的情况更糟。
因为它现在,它还会泄漏内存
-
Karl Heinz Buchegger
删除t;在任务之前,当然:)谢谢!
-
Christopher Benson-Manica |我*应该*知道我在说什么 - 如果我
ataru(at)cyberspace.org |不,我需要知道。火焰欢迎。
With delete t; coming before the assignment, of course :) Thanks!
--
Christopher Benson-Manica | I *should* know what I''m talking about - if I
ataru(at)cyberspace.org | don''t, I need to know. Flames welcome.
这篇关于智能指针实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!