简体   繁体   中英

Do the following 5 lines of code cause a memory leak?

Does this cause a memory leak because pWinsock didn't get deleted inside the fonction?

Winsock* CreateWinsock()
{
    Winsock* pWinsock=new Winsock;

    return pWinsock;
}

Edit: Actually, I cannot delete my pointer since it is a member of Game (pWinsock) that received the newly created Winsock in the code above. Is there anything wrong with this?

class Game{
public:
    Game();
    ~Game();

    void CreateWindowClass(HINSTANCE);
    void CreateRessources(HINSTANCE);

    void ShowLoginScreen();

    HWND Getm_hWnd();

public:
    D2DResources* pD2DResources;
    Winsock* pWinsock;
    MessageLog* pMessageLog;

private:
    HWND m_hWnd;
};

Watch out, if you delete the memory in the function the returned pointer will become a dangling pointer , as the memory for it has already been cleared. Dereferencing such a pointer is undefined behavior .

The program only causes a memory leak if the caller does not remember to delete the memory for themselves. Since you allocated memory within the function and returned it, it must be deleted somehow after the call. To delete the memory, it would look something like this:

Winsock *ptr = CreateWinsock(); // memory passed to ptr
// ...

delete ptr; // delete memory

The problem is that depending on the caller to delete the memory is quite cumbersome and unreliable. These kinds of potential problems can be alleviated through the use of smart pointers such as unique_ptr or shared_ptr . These objects delete the memory when their destructors are called, allowing great flexibility. Here's an example of how it would look for your program:

std::unique_ptr<Winsock> CreateWinsock()
{
    return std::unique_ptr<Winsock>(new Winsock);
}

std::unique_ptr<Winsock> ptr = CreateWinsock();

There's no need to explicitly delete the pointer as the encapsulating smart pointer now has that responsibility.

If the caller of this function deletes the pointer after it uses it, there is no leak. Therefore, it is not appropriate to comment on the memory leak given just this piece of code.

To refrain from such a case where the caller forgets to delete the object , use shared pointer , or another smart pointer .

Nope, all that does is pass back the pointer to Winsock. For example

Winsock* ws = CreateWinsock();
ws->doSomething();
//......
//some more stuff
//......
//Finished using Winsock
delete ws;

If the delete wasn't called there when you're finished with Winsock then that would be seen as a memory leak because memory would be taken up by Winsock when its not being used anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM