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

Are memory leaks possible with decltype(new any_type())?

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

#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 释放,没有泄漏。

decltype是关键字,用于查询表达式的类型。它只是分析表达式的类型;它实际上并没有执行它。

因此,这不仅不会泄漏,您还可以 decltype -1 的平方根而不会出现任何错误,依此类推。

因为 decltype 和模板处理(如类型特征 类)只是 编译时间 。在 运行 时间内实际上没有发生任何事情。