Allanqunzi
Allanqunzi

Reputation: 3260

where does the pointer created by new get deleted in this code?

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.

  1. A question to ask is that where the pointer m_pClient, and pointer m_pEWrapper get deleted respectively? Should you put delete m_pEWrapper in the destructor of EClientSocketBase?
  2. Is there something wrong in this code? If yes, what is it? If not, is it a good practice to write code like this?

Upvotes: 1

Views: 157

Answers (1)

Barry
Barry

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.


Note that in C++11, std::auto_ptr is deprecated in favor of std::unique_ptr, which is a strictly superior alternative.

Upvotes: 7

Related Questions