c++ - 在未初始化的对象上使用 std::bind 是否安全?

标签 c++ bind

由于我无法正确设计我的类(class),我达到了需要这样的东西的地步:

struct A
{
   A( function< void(string&) cb > ): callback(cb) {}
   function< void(string&) > callback;

   template <std::size_t T>
   void func( string& str) { ... }
}

int main(){
vector<A> items = {
   A( bind( &A::func<1>, items[0], _1) ),
   A( bind( &A::func<2>, items[1], _1) ),
   ...
}

使用安全吗?如果没有,是否有替代方案?

最佳答案

这当然不安全。 items[0]将在 items 之前进行评估已初始化。

这里正确的做法可能是只使用 lambda,例如

vector<A> items = {
    A( [&items](string& s){ items[0].func(s); } ),
    A( [&items](string& s){ items[1].func(s); } ),
    ...
}

这只会获取对 items 的引用在初始化期间,然后拉出 items[0]仅当实际调用回调时。

或者,您能否更改回调以获取 A&作为参数?如果你的回调类型是 std::function<void(A&, string&)>那么你可以通过 &A::func<1>作为回调,它将起作用。

关于c++ - 在未初始化的对象上使用 std::bind 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14247272/

相关文章:

c - 如何在 C 上连接到服务器,定义两侧端口

c++ - 部署后,简单的C++ ofstream项目无法正常工作

c++ - C++ 中的(共享)互斥体

c++ - 无法识别父类的字段

c++ - 将指针设置为 int 值

Haskell:用 do-notation 定义 FoldM

c++ - 在 C++ 中多次运行按引用选择排序函数

c# - Blazor输入+数据列表如何将所选项目绑定(bind)到对象

centos - 使用 BIND : no servers could be reached 创建 DNS

javascript - 绑定(bind)两个输入,以便即使其中之一被用户更改,它们也会显示相同的文本