2015-05-18 49 views
11

我检查使用valgrind类指针任何内存泄漏的可能性,并发现了下面的程序没有内存泄漏:decltype(new any_type())可能发生内存泄漏吗?

#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; 
} 

这怎么可能呢?

回答

16

decltype(和sizeof)的操作数未被评估,因此不会发生任何副作用,包括内存分配。只有类型是在编译时确定的。

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

+2

这个特别有趣的结果是像[std :: declval](http://en.cppreference.com/w/cpp/utility/declval)这些专门用于这些表达式的函数, 'decltype(std :: declval ()。method())',实际上并没有在任何地方实际定义。 – cartographer

8

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

所以,不但不会泄漏,您可以decltype的平方根-1没有任何错误,依此类推。

2

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