gpt4 book ai didi

c++ - unique_ptr 不在编译器资源管理器中生成删除指令?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:23:21 25 4
gpt4 key购买 nike

我一直在研究 Compiler Explorer最近。我加载了其中一个采用指针参数的示例,并将其更改为采用 unique_ptr 参数。但我注意到在输出程序集中,明显没有对 operator delete 的调用。我很好奇是否有人知道为什么。

这是您可以粘贴到资源管理器中的示例。确保同时将 -O3 放入编译器选项中。

#include <memory>

using std::unique_ptr;

void maxArray(unique_ptr<double[]> x, unique_ptr<double[]> y) {
for (int i = 0; i < 65536; i++) {
if (y[i] > x[i]) x[i] = y[i];
}
}

编辑:同样为了比较,如果我改为粘贴来自 cppreference 的代码示例之一,那么我在输出中获取运算符删除。

#include <iostream>
#include <memory>

struct Foo
{
Foo() { std::cout << "Foo::Foo\n"; }
~Foo() { std::cout << "Foo::~Foo\n"; }
void bar() { std::cout << "Foo::bar\n"; }
};

void f(const Foo &)
{
std::cout << "f(const Foo&)\n";
}

int main()
{
std::unique_ptr<Foo> p1(new Foo); // p1 owns Foo
if (p1) p1->bar();

{
std::unique_ptr<Foo> p2(std::move(p1)); // now p2 owns Foo
f(*p2);

p1 = std::move(p2); // ownership returns to p1
std::cout << "destroying p2...\n";
}

if (p1) p1->bar();

// Foo instance is destroyed when p1 goes out of scope
}

编辑:+1 到 krzaq。构造和销毁参数的是调用者,而不是被调用者。

最佳答案

这个问题归结为:

void foo(unique_ptr<int>)
{
}

foo(make_unique<int>());

foo 的参数在哪里?

以下标准语与这个问题相关:

N4140 §5.2.2 [expr.call]/4

The lifetime of a parameter ends when the function in which it is defined returns. The initialization and destruction of each parameter occurs within the context of the calling function.

换句话说:您的maxArray 不需要负责调用xy 的析构函数; gcc 以这种方式实现它,这就是代码生成中没有 delete 调用的原因。

关于c++ - unique_ptr 不在编译器资源管理器中生成删除指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40066406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com