相关疑难解决方法(0)

如果构造函数抛出,由`new`分配的内存会发生什么?

这段代码会导致内存泄漏吗?

#include <stdexept>

class MyClass
{
public:
    MyClass()
    {
        throw std::runtime_error("Test");
    }
};

int main()
{
    try
    {
        MyClass * myClass = new MyClass;
    }
    catch (const std::exception & exc)
    {
        // Memory leak?
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

分配的内存new永远不会被删除.这是内部处理,还是实际的内存泄漏?

c++

17
推荐指数
3
解决办法
2101
查看次数

std :: make_unique <T> vs reset(新T)

我想问一个关于构造函数中的内存泄漏的问题.我们来考虑一个课程:

 class Foo
 {
   public:
      Foo(){ throw 500;} 
 };
Run Code Online (Sandbox Code Playgroud)

有什么区别

std::unique_ptr<Foo> l_ptr = std::make_unique<Foo>();
Run Code Online (Sandbox Code Playgroud)

std::unique_ptr<Foo> l_ptr;
l_ptr.reset(new Foo());
Run Code Online (Sandbox Code Playgroud)

在我看来,make_unique的解决方案应该保护我免受内存泄漏,但在这两种情况下我得到了相同的valgrind结果:

$ valgrind --leak-check=full ./a.out
==17611== Memcheck, a memory error detector
==17611== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==17611== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==17611== Command: ./a.out
==17611== 
terminate called after throwing an instance of 'int'
==17611== 
==17611== Process terminating with default action of signal 6 (SIGABRT)
==17611==    at 0x5407418: raise …
Run Code Online (Sandbox Code Playgroud)

c++ memory-leaks smart-pointers unique-ptr c++11

10
推荐指数
1
解决办法
2894
查看次数

标签 统计

c++ ×2

c++11 ×1

memory-leaks ×1

smart-pointers ×1

unique-ptr ×1