gpt4 book ai didi

c++ - 为什么在调用 std::call_once() 时需要这个指针?

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

在“C++ Concurrency in Action”一书§3.3.1 中,在介绍使用std::call_once() 对类成员进行线程安全延迟初始化时,给出了以下示例:

#include <mutex>

struct connection_info
{};

struct data_packet
{};

struct connection_handle
{
void send_data(data_packet const&)
{}
data_packet receive_data()
{
return data_packet();
}
};

struct remote_connection_manager
{
connection_handle open(connection_info const&)
{
return connection_handle();
}
} connection_manager;


class X
{
private:
connection_info connection_details;
connection_handle connection;
std::once_flag connection_init_flag;

void open_connection()
{
connection=connection_manager.open(connection_details);
}
public:
X(connection_info const& connection_details_):
connection_details(connection_details_)
{}
void send_data(data_packet const& data)
{
std::call_once(connection_init_flag,&X::open_connection,this);
connection.send_data(data);
}
data_packet receive_data()
{
std::call_once(connection_init_flag,&X::open_connection,this);
return connection.receive_data();
}
};

int main()
{}

来自 its doc ,第三个参数是传递给函数X::open_connection()的参数。鉴于 X::open_connection() 没有输入参数,为什么调用 std::call_once() 时这里需要 this 指针?

std::call_once(connection_init_flag,&X::open_connection,this);

P.S.:删除this指针会导致C2064错误:

error C2064: term does not evaluate to a function taking 0 arguments


更新:在引入类似函数时,“C++ Concurrency in Action”一书的 §4.2.1 中进一步明确解决了这个问题,即 std::async:

If the first argument (should be the second one for std::call_once) is a pointer to a member function, the second argument (should be the third one for std::call_once) provides the object on which to apply the member function (either directly, or via a pointer, or wrapped in std::ref), and the remaining arguments are passed as arguments to the member function. Otherwise, the second (should be the third one for std::call_once) and subsequent arguments are passed as arguments to the function or callable object specified as the first argument.

最佳答案

Why is this pointer needed when calling std::call_once()?

因为open_connection 是一个非静态数据成员。它必须在某些东西上被调用,并且那个东西是同一个实例,由 this 指向(从技术上讲,非静态成员函数有一个隐式的第一个参数用于 this。 )

它可以用不同的实例调用,尽管在这种情况下这没有意义:

X x;
std::call_once(connection_init_flag, &X::open_connection, &x);

关于c++ - 为什么在调用 std::call_once() 时需要这个指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23197333/

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