c++ - decltype(new any_type()) 是否可能发生内存泄漏?

标签 c++ c++11 memory-leaks g++

我正在使用 valgrind 检查类指针的任何内存泄漏可能性,并发现以下程序没有内存泄漏:

#include <iostream>
#include <utility>
#include <memory>

using namespace std;

class base{};

int main()
{
  unique_ptr<base> b1 = make_unique<base>();
  base *b2 = new base();
  cout << is_same<decltype(new base()), decltype(b1)>::value << endl;
  cout << is_same<decltype(new base()), decltype(b2)>::value << endl;
  delete b2;
  return 0;
}

这怎么可能?

最佳答案

decltype(还有 sizeof)的操作数不会被求值,所以任何副作用,包括内存分配,都不会发生。只有类型是在编译时确定的。

所以这里唯一的内存分配是在 make_unique 和第一个 new base() 中。前者由 unique_ptr 析构函数释放,后者由 delete b2 释放,不留任何泄漏。

关于c++ - decltype(new any_type()) 是否可能发生内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30305062/

相关文章:

java - 使用 setText 时内存泄漏

linux - 分析网络应用程序中的资源泄漏(套接字处理程序等)

c++ - 复制指针值c++

c++ - 如何在 C++ 中访问有序映射中的键范围/间隔?

复杂继承中的 C++ 模板

c++ - 为什么 "std::begin()"在这种情况下总是返回 "const_iterator"?

C# 位图 - 找不到如何删除 OutOfMemoryException

c++ - 静态函数与 const 函数

存储在 std::map 中的 C++ 基本迭代器

c++ - 如何使用带有重载的enable_if