gpt4 book ai didi

c++ - 元组中返回的对象的 std::tie 和生命周期

转载 作者:行者123 更新时间:2023-11-28 01:46:03 34 4
gpt4 key购买 nike

在下面的代码中,我有一个函数修改两个昂贵的复制对象,我试图在没有输出参数的情况下逃脱

   struct FatThing {/* some big data members here*/};

auto processFatThings(FatThing ft1, FatThing ft2)-> std::tuple<FatThing, FatThing> {
// do smth with those two
return std::make_tuple(move(ft1), move(ft2));
}

auto useProcessFatThings()-> void {
FatThing ft1, ft2;
std::tie(ft1, ft2) = processFatThings(move(ft1), move(ft2)); // dangling references?
}

我现在有点困惑,因为编译器没有发出任何警告, sanitizer 和 memcheck 是干净的,代码可以工作。但!!!这里不是用 std::tie 创建的悬挂引用吗?

最佳答案

不,没有悬挂引用。 ft1ft2 将分配给 processFatThings

的返回值中的相应元素

例子见下面的代码

#include <iostream>
#include <tuple>
#include <type_traits>

using std::cout;
using std::endl;

class Something {
public:
Something() {
cout << __PRETTY_FUNCTION__ << endl;
}
Something(Something&&) {
cout << __PRETTY_FUNCTION__ << endl;
}
Something(const Something&) {
cout << __PRETTY_FUNCTION__ << endl;
}
~Something() {
cout << __PRETTY_FUNCTION__ << endl;
}
Something& operator=(const Something&) {
cout << __PRETTY_FUNCTION__ << endl;
return *this;
}
};

int main() {
Something one, two;
std::tie(one, two) = std::make_tuple(Something(), Something());
}

现场演示 https://wandbox.org/permlink/iG1qIJ2VKL4bljPM

这里你会看到有4个构造,分别对应onetwomake_tuple的两个参数。

然后 make_tuple 的两个移动结构。

然后就是两个copy assignments。这是这里的关键部分。 Something 对象被复制到任何与 std::tie“绑定(bind)”的对象。

所以没有悬空引用,你得到拷贝/移动!

关于c++ - 元组中返回的对象的 std::tie 和生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45036492/

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