ptr_vector cleanup question

Hi, Below I have posted code that I'm trying to clean up. I'm specifically trying to clean up the MainFunction() implementation. You'll notice that I'm creating an object on the heap, Initializing it, and if the initialization fails I simply delete the object. However, if it succeeds I proceed to add it to my ptr_vector container and keep it. There are a few things to be cautious about, however: 1) Connect() may or may not throw exceptions, which would ultimately result in a memory leak. 2) The Socket object is not copy constructable. One idea I thought of to clean this up was to define my ptr_vector as a container of shared_ptr<Socket> objects, however I'm not sure if this is recommended. It would definitely solve the problem of exceptions being thrown. Perhaps there's a boost::shared_ptr_vector somewhere I don't know about :) class Socket { public: bool Connect() { /* Assume valid implementation */ return false; } }; boost::ptr_vector<Socket> sockets; void MainFunction() { Socket* mySocket = new Socket; if( mySocket->Connect() ) { sockets.push_back( mySocket ); } else { delete mySocket; } }

On Wed, Mar 19, 2008 at 6:31 PM, Robert Dailey <rcdailey@gmail.com> wrote:
Below I have posted code that I'm trying to clean up. I'm specifically trying to clean up the MainFunction() implementation. [...]
Sounds like auto_ptr could be of help: void MainFunction() { std::auto_ptr<Socket> mySocket(new Socket); if( mySocket->Connect() ) { sockets.push_back( mySocket.release() ); } } HTH, ~ Scott P.S. I think this kind of issue is more suited for boost-users than boost-dev, for future posts.

On Wed, Mar 19, 2008 at 5:37 PM, Scott McMurray <me22.ca+boost@gmail.com> wrote:
On Wed, Mar 19, 2008 at 6:31 PM, Robert Dailey <rcdailey@gmail.com> wrote:
Below I have posted code that I'm trying to clean up. I'm specifically trying to clean up the MainFunction() implementation. [...]
Sounds like auto_ptr could be of help:
void MainFunction() { std::auto_ptr<Socket> mySocket(new Socket);
if( mySocket->Connect() ) { sockets.push_back( mySocket.release() ); } }
HTH, ~ Scott
P.S. I think this kind of issue is more suited for boost-users than boost-dev, for future posts.
Thanks, sometimes boost makes me overlook STL :) This is what I needed. I'll be sure to post on boost-user next time. The names are somewhat identical in my address book so sometimes I post to the wrong one.
participants (2)
-
Robert Dailey
-
Scott McMurray