gpt4 book ai didi

c++ - 完美转发,为什么析构函数被调用了两次?

转载 作者:太空狗 更新时间:2023-10-29 19:48:10 24 4
gpt4 key购买 nike

我正在尝试创建一个模仿 Python 的 with 语句的函数,但我遇到了一些我不太理解的有趣行为。

使用以下程序:

#include <iostream>

struct foo {
foo() { std::cout << "foo()" << std::endl; }
~foo() { std::cout << "~foo()" << std::endl; }
};

auto make_foo() -> foo {
return {};
}

template <typename T, typename F>
auto with(T&& t, F&& fn) -> void {
fn(std::forward<T>(t));
}

auto main() -> int {
std::cout << "before" << std::endl;
with(make_foo(), [](auto f) {
std::cout << "during" << std::endl;
});
std::cout << "after" << std::endl;
}

当使用 Xcode 6.3 和 -std=c++14 提供的 clang 编译并运行时,我得到以下输出:

before
foo()
during
~foo()
~foo()
after

有人知道为什么我的输出中有两个 ~foo() 吗?

最佳答案

这是两个对象:

with(make_foo(), [](auto f) {

      1^^^^^^^^^    2^^^^^^

make_foo()返回的对象,还有函数参数f

如果您通过引用传递(更改为 auto&& f),那么您将只会看到一个对象的证据。

没有创建消息,因为这是通过复制/移动构造创建的,并且您在这些构造函数中没有任何输出。

请注意,make_foo() 中可能有更多对象,但您的编译器正在执行复制省略

关于c++ - 完美转发,为什么析构函数被调用了两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32046699/

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