阅读关于
std :: unique_ptr
的内容,位于http://en.cppreference.com/w/cpp/memory/unique_ptr上,我的天真印象是,足够智能的编译器可以用裸指针替换正确使用的unique_ptr
,并在销毁unique_ptr
时仅插入delete
。这实际上是这种情况吗?如果是,那么任何主流优化编译器都会这样做吗?如果没有,是否可能编写一些具有unique_ptr
编译时安全性好处的代码,可以优化为没有运行时成本(在空间或时间方面)?
注意:对于那些(正确地)担心过早优化的人来说:这里的答案不会阻止我使用std :: unique_ptr
,我只是很好奇它是否是一个真正棒极了的工具。
编辑 2013/07/21 20:07 EST:
好的,所以我使用以下程序进行了测试(请告诉我其中是否有问题):
#include <climits>
#include <chrono>
#include <memory>
#include <iostream>
static const size_t iterations = 100;
int main (int argc, char ** argv) {
std::chrono::steady_clock::rep smart[iterations];
std::chrono::steady_clock::rep dumb[iterations];
volatile int contents;
for (size_t i = 0; i < iterations; i++) {
auto start = std::chrono::steady_clock::now();
{
std::unique_ptr<int> smart_ptr(new int(5));
for (unsigned int j = 0; j < UINT_MAX; j++)
contents = *smart_ptr;
}
auto middle = std::chrono::steady_clock::now();
{
int *dumb_ptr = new int(10);
try {
for (unsigned int j = 0; j < UINT_MAX; j++)
contents = *dumb_ptr;
delete dumb_ptr;
} catch (...) {
delete dumb_ptr;
throw;
}
}
auto end = std::chrono::steady_clock::now();
smart[i] = (middle - start).count();
dumb[i] = (end - middle).count();
}
std::chrono::steady_clock::rep smartAvg;
std::chrono::steady_clock::rep dumbAvg;
for (size_t i = 0; i < iterations; i++) {
smartAvg += smart[i];
dumbAvg += dumb[i];
}
smartAvg /= iterations;
dumbAvg /= iterations;
std::cerr << "Smart: " << smartAvg << " Dumb: " << dumbAvg << std::endl;
return contents;
}
使用 g++ --std=c++11 -O3 test.cc
编译 g++ 4.7.3 版本,得到的结果为 Smart: 1130859 Dumb: 1130005
,这意味着智能指针与愚蠢指针之间的差距仅有0.076%,几乎可以确定是噪音所致。
unique_ptr
有哪些运行时成本?至于空间,对我来说sizeof(myuniqueptr)
和sizeof(myptr)
完全相同,都是8个字节的int
。 - Rapptz