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;
  }
Aneesh Narayanan
  • 3,220
  • 11
  • 31
  • 48
  • 1
    Writing `new std::auto_ptr` defeats the purpose of auto_ptr. – Pubby May 30 '12 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. – Steve Jessop May 30 '12 at 13:35

2 Answers2

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;

Plexico
  • 131
  • 1
  • 4
  • 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. – Nicholas Wilson May 30 '12 at 15:23
  • 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. – Steve Jessop May 30 '12 at 22:22
  • @SteveJessop absolutely, that was one of many auto_ptr flaws to be incompatible with standard containers. – Plexico May 30 '12 at 22:47
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.

sharptooth
  • 167,383
  • 100
  • 513
  • 979