c++ - 可以优化智能指针吗?

标签 c++ c++11 smart-pointers

注意代码

...
{
    int* p = new int(0);
    std::unique_ptr<int> q(p);
    ...
    // make use of 'p'
}
...

在上面的代码中,唯一的指针 q 仅用于在时机成熟时释放 p。 Q 本身不使用。
由于 q 永远不会在声明它的行下方使用,因此它似乎可以在声明后立即释放,从而利用 p“释放后使用”。
问题是 q 保证一直存在直到离开当前范围,或者编译器的优化器可以自由地释放它之前?

最佳答案

使用 as-if 规则,只要可观察到的行为相同,编译器就可以进行任何优化。

立即释放 q/p将不被允许,因为那样您将使用悬空指针。

虽然它可以在范围结束之前调用析构函数:

{
    int* p = new int(0);
    std::unique_ptr<int> q(p);
    ...
    // make use of 'p'
    ...
    // No longer use of p (and q)
    ...
    // Ok, can delete p/q now (as long there are no observable behaviors changes)
    ...
}

operator new/delete可能会全局更改,编译器通常没有足够的信息(尽管链接器有),因此请考虑它们(可能)具有可观察的行为(作为任何外部函数)。

c++14 允许对新表达式进行一些省略/优化,所以
{
    delete new int(42);
    int* p1 = new int(0);
    int* p2 = new int(0);
    std::unique_ptr<int> q2(p2);
    std::unique_ptr<int> q1(p1);
    ...
    // make use of 'p1'/p2
    ...
}

可以“代替”
{
    // delete new int(42); // optimized out
    std::unique_ptr<int[]> qs{new int [] {0, 0}}; // only one allocation instead of 2
    int* p1 = q->get();
    int* p2 = q->get() + 1;
    ...
    // make use of 'p1'/p2
    ...
}

关于c++ - 可以优化智能指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61207369/

相关文章:

c++ - 获取最大、平均值和最小值

c++ - 组合枚举的模板结构

C++11 线程 : Exception when called using lambdas

c++ - 智能指针模板和自动删除指针

c++ - 似乎无法将 unique_ptr 分配给结构

c++ - 使用C++和MFC进行动态图绘制

c++ - 我们能否创建一个类似 scanf 的函数,在填充所有参数时返回 true,否则返回 false,而无需遍历所有变量?

c++ - 从基类指针调用派生类方法

c++ - c++11 shared_ptr 的简单示例无法编译

c++ - boost shared_ptr : How to use custom deleters and allocators