Pergunta

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;
  }
Foi útil?

Solução

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.

Outras dicas

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;

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top