0

This is a sample code of my program. Here I am dynamically allocating memory using std::auto_ptr and entering values( in function) after that I am again allocation memory for the same variable. So Do the previously allocated memory will be deallocated when allocated a new memory for the same. I am doubtful about this since I am using std::auto_ptr. Thanks in advance.

  #include "stdafx.h"
  #include <iostream>
  #include <memory>
  #include <windows.h>

  std::auto_ptr<HANDLE> *eventHandle;

  void function()
  {
    eventHandle = new std::auto_ptr<HANDLE>[5];
    std::auto_ptr<HANDLE> handle(new HANDLE);
    *handle = CreateEvent(NULL, false, false, NULL);
    eventHandle[0] = handle;
  }

  void f2()
  {
    if(NULL == eventHandle)
    {
      std::cout<<" HANDLE NULL";
    }
  }

  int _tmain(int argc, _TCHAR* argv[])
  {
    function();
    f2();
    function();
    return 0;
  }
2
  • 1
    Writing new std::auto_ptr defeats the purpose of auto_ptr. Commented May 30, 2012 at 13:33
  • @Pubby: this is a dynamically-sized array of auto_ptr, though. Or it would be, if the 5 wasn't a hard-coded constant. A dynamically-sized array doesn't defeat the purpose of auto_ptr in the same way. Commented May 30, 2012 at 13:35

2 Answers 2

2

In your example : the HANDLE pointers are smart pointers but not the array of std::auto_ptr. In this case you'll have to call delete [] eventHandle prior to the second function() call, this will also delete the HANDLE smart pointers.

However, the HANDLE objects would have to be closed by CloseHandle function prior to deletion, so I question the need of smart pointers here since you'll always know when the HANDLE is no more needed and the pointer to the object has to be deleted.

P.S. std::auto_ptr is a bit flawed. If you have access to VS2010, I would suggest you to use std::shared_ptr.

P.P.S. if you want to test for NULL, you should always initialize pointers to NULL, they're aren't by default. std::auto_ptr<HANDLE> *eventHandle = NULL;

Sign up to request clarification or add additional context in comments.

3 Comments

std::shared_ptr's bit more expensive than auto_ptr. It's std::unique_ptr which is the C++11 more direct replacement for auto_ptr.
Most important is that with either shared_ptr or unique_ptr, you can get rid of the nasty new[], and use a nice std::vector or std::array of smart pointers.
@SteveJessop absolutely, that was one of many auto_ptr flaws to be incompatible with standard containers.
1

Here

std::auto_ptr<HANDLE> *eventHandle;

you have a raw pointer, so when you reassign it the previous value is just overwritten and the array of objects of type auto_ptr previously pointed to is leaked.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.