Reputation: 3260
I am reading the IB api C++ code, and have found the following class structure
class EWrapper;
class EClientSocketBase{
public:
EClientSocketBase( EWrapper *ptr): m_pEWrapper(ptr){}
~EClientSocketBase(){ }
// some methods
private:
EWrapper *m_pEWrapper;
// some other data members
};
class EPosixClientSocket : public EClientSocketBase{
// some methods and data members
EPosixClientSocket( EWrapper *ptr) : EClientSocketBase( ptr){}
~EPosixClientSocket(){}
};
class PosixTestClient : public EWrapper{
public:
PosixTestClient(): m_pClient(new EPosixClientSocket(this)){}
~PosixTestClient(){}
// some other methods
private:
std::auto_ptr<EPosixClientSocket> m_pClient;
// some other methods and data members
};
I feel very uncomfortable about this code, especially on not putting delete
the pointer m_pEWrapper
in the destructor of EClientSocketBase
, and more uncomfortable about the initializing EPosixClientSocket
with this
, but somehow I can not articulate what exactly the mistake is.
m_pClient
, and pointer m_pEWrapper
get deleted respectively? Should you put delete m_pEWrapper
in the destructor of EClientSocketBase
?Upvotes: 1
Views: 157
Reputation: 302718
That's std::auto_ptr
's job. It is:
a smart pointer that manages an object obtained via new expression and deletes that object when
auto_ptr
itself is destroyed.
So in ~PosixTestClient()
, when m_pClient
gets destroyed, it will delete
the pointer that it is managing. This is far safer than taking care of calling delete
yourself.
std::auto_ptr
is deprecated in favor of std::unique_ptr
, which is a strictly superior alternative.
Upvotes: 7