gpt4 book ai didi

c++ - 您能否根据是否使用返回值来保证不同的生命周期行为?

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

假设我们有某种subscriber 对象,它利用 RAII 在销毁时清理自身。

我们有记录在案的代码声明以下内容:

1. If you capture the return type, the subscriber will live as long as the value you captured lives.

2. If you don't capture the return type, the subscriber will live as long as the object whose method you called to create the subscriber.

澄清一下,代码如下所示:

template <class... Args>
id &&connect_subscriber(Args &&... args)
{
auto id = connect_subscriber_with_id(std::forward<Args>(args)...);

{
std::lock_guard<std::mutex> lock(subscriber_id_mutex_);
subscriber_ids_.push_back(std::move(id));
return std::move(subscriber_ids_.back());
}
}

文档是:

/// If the resulting `subscriber_id` is assigned storage at the call
/// site, then the subscription will be managed exclusively by the caller.
/// This means that until the identifier is either destroyed or
/// `disconnect_subscriber()` is called with it, the subscription will stay
/// active.
///
/// Conversely, if the `subscriber_id` is not assigned storage at
/// the call site, it will be managed internally inside the task and the
/// subscription will persist for the life-time of the task.

我们能否保证根据是否捕获返回类型来转移所有权?

最佳答案

我对您使用的术语有点费解,但如果我答对了问题,我认为,它的意思是以下受您的代码示例启发的快速而肮脏的 mce。

如果您不为 connect_subscriber 的返回值提供存储,则 std::move 将不会成功并且该 id 将保留在 subscriber_ids_ 中,否则它将被 move 到您的存储并因此从 subscriber_ids_ 中删除并且不受任何管理机制与 subscriber_ids_ 一起使用。

#include <vector>
#include <iostream>

using id = std::string;
std::vector<std::string> subscriber_ids_ = {"31"};

int ids = 42;

id&& connect_subscriber()
{
auto id = std::to_string(ids++);
{
subscriber_ids_.push_back(std::move(id));
return std::move(subscriber_ids_.back());
}
}

void print() {
int i=0;
for(const auto& n:subscriber_ids_)
std::cout << i++ << ":" << n << " ";
std::cout << "\n";
}

int main()
{

connect_subscriber(); // memory not privided
print();

connect_subscriber(); // memory not privided
print();

auto take_it = connect_subscriber(); // memory privided
print();
}

输出是:

0:31 1:42 
0:31 1:42 2:43
0:31 1:42 2:43 3:

输出不是:

0:31 1:42 
0:31 1:42 2:43
0:31 1:42 2:43 3:44

关于c++ - 您能否根据是否使用返回值来保证不同的生命周期行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45827958/

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