现代C++中的自动生命周期管理无法按预期工作

Shi*_*nbo -2 c++

我试图证明现代C++一旦超出范围就会自动删除它.我正在使用下面的代码来执行测试.但它并没有像预期的那样真正起作用.根据任务管理器中显示的内存大小,它仍然具有200 + MB内存.但是一旦我取消注释delete stringTest,内存减少到不到1 MB.有人请帮忙看看我在这里忽略了什么吗?非常感谢.

在我的测试中使用了Visual Studio 2015.

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

class StringTest
{
public:
    std::string StringSample;

    StringTest::StringTest()
    {
        StringSample = "abcdefghijklmnopqrstuvwxyz...";
    }

    std::string StringTest::Substring(int length)
    {
        std::string result = StringSample.substr(0, length);

        return result;
    }
};

void testStringSeveralTimes()
{
    for (auto i = 0; i < 100000; i++)
    {
        auto stringTest = new StringTest();
        // delete stringTest;
    }
}

int main()
{
    testStringSeveralTimes();

    std::cout << "Done." << std::endl;
    int a;
    std::cin >> a;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

小智 6

我想在学习基础知识之前,我不会使用"现代C++"这个词.在C++ 11之前,auto是一个存储类说明符,它意味着自动存储持续时间,它与指针变量有关,而不是它管理的内存.在C++ 11中,auto重新调整以允许在变量声明中执行模板参数推导.stringTest被推断为StringTest*.

您正在寻找的概念是RAII,并不是新的.您应该使用智能指针,它将为您管理内存,并在它超出您期望的范围时解除分配.

auto stringTest = std::make_unique<StringTest>();
Run Code Online (Sandbox Code Playgroud)