简体   繁体   中英

Unique pointer usage still memory leak, find it

#include <iostream>
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

class My_Container
{
public:
    My_Container(int y) : x{new int(y)}
    {
        //*x = y;
    }

    int get_value() const
    {
        return *x;
    }

    bool has_value() const
    {
        return x != nullptr;
    }

private:
    std::unique_ptr<int> x = std::make_unique<int>();
};

int test1(My_Container const &container)
{
    if (container.has_value())
    {
        return container.get_value();
    }
    return -1;
}

int test2(My_Container const &container)
{
    if (container.has_value())
    {
        return container.get_value();
    }
    return -1;
}

int main()
{

    My_Container c1{5};
    My_Container const c2{3};

    std::cout << test1(c1) << std::endl;
    std::cout << test1(c2) << std::endl;

    std::cout << test2(c1) << std::endl;
    std::cout << test2(c2) << std::endl;

    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT);
    _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT);
    _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT);
    if (_CrtDumpMemoryLeaks())
    {
        std::cout << "he" << std::endl;
    }
    return 0;
}

5 3 5 3 Detected memory leaks, Dumping objects -> {153} normal block at 0x011D0580. 4 bytes long: Data, < > 03 00 00 00 {152} normal block at 0x011D9E30. 4 bytes long: Data. < > 05 00 00 00 Object dump complete. he

The above is the output.

Could anyone find where this memory leaks are produced in the code?

Thank you so much.

_CrtDumpMemoryLeaks reports the memory as lost because c1 and c2 are still in scope. Try

int main() 
{
    {
        My_Container c1{5};
        My_Container const c2{3};

        std::cout << test1(c1) << std::endl;
        std::cout << test1(c2) << std::endl;

        std::cout << test2(c1) << std::endl;
        std::cout << test2(c2) << std::endl;
    }
    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT);
    _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT);
    _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT);
    if (_CrtDumpMemoryLeaks())
    {
        std::cout << "he" << std::endl;
    }
    return 0;
}

This should report no memory leaks.

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