c++ - 为什么 std::bind() 试图复制我的对象?

标签 c++ stl

我正在使用 VS2010。 在我的不可兼容场景类的构造函数中,我有:

auto& character_mgr = CharacterManager::Instance();
    character_mgr.initialize();
character_mgr.add_observer(  std::bind( &Scene::on_character_event, *this, std::placeholders::_1, std::placeholders::_2 ) );

这里 add_observer 定义为:

void add_observer( Observer observer ){ ... }

观察者定义为:

typedef std::function< void ( CharacterEvent, const Character& ) > Observer;

问题是编译器告诉我有人试图复制我在绑定(bind)中使用 *this 提供的场景,认为它会保留对它的引用,而不是尝试复制当我复制绑定(bind)生成的仿函数时。

  1. 为什么要复制我的对象?正常吗?
  2. 在提供对象的成员函数时应该如何避免复制?

最佳答案

  1. 这是默认行为。
  2. 要通过引用传递,请尝试使用 std::ref 。

关于c++ - 为什么 std::bind() 试图复制我的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5850360/

相关文章:

c++ - std::shared_ptr::reset() "invalidates"其他引用

c++ - 以 boost spirit 实现运算符优先级

c++ - 从函数返回 STL vector - 复制成本

c++ - 在容器条目上放置互斥锁的安全有效的方法

c++ - 有没有办法从 map 中获取特定的键值对?

android - 尝试为 Android 构建 Xerces-C++

c++ - xerces c++ getChildNodes getLength

c++ - 导致段错误的独立列表之间的插入/删除语句的顺序

c++ - 在对的 vector 中按关键字查找对

c++ - 取消引用 std::shared_ptr<T[]>?