[提升]::D我从喷油器创建独特的shared_ptr对象
[Boost]::DI creating unique shared_ptr objects from injector
以此示例代码为例,我希望得到的结果是按钮 1 和按钮 2 是两个单独的对象。
#include <iostream>
#include <memory>
#include "di.hpp"
namespace di = boost::di;
struct CommandQueue {
void addCommand() {}
};
struct Control {
Control( CommandQueue &cq ) : cq( cq ) {
static int sid{};
id = ++sid;
}
CommandQueue& cq;
int id{};
};
int main() {
auto injector = di::make_injector( di::bind<CommandQueue>().in(di::singleton) );
auto button1 = injector.create<std::shared_ptr<Control>>();
auto button2 = injector.create<std::shared_ptr<Control>>();
std::cout << "button1->id = " << button1->id << std::endl;
std::cout << "button2->id = " << button2->id << std::endl;
return 0;
}
当前输出为:
按钮1->ID = 1
按钮2->ID = 1
而不是预期的:
按钮1->ID = 1
按钮2->ID = 2
从单一实例中删除di::singleton
生存期范围CommandQueue
也不能修复它。我知道shared_ptr的生存范围默认是单例,但我认为这是指注入的依赖项,而不是使用 create 创建的实际对象。
事实上,最简单的事情可能是
auto button1 = injector.create<Control>();
auto button2 = injector.create<Control>();
std::cout << "button1.id = " << button1.id() << std::endl;
std::cout << "button2.id = " << button2.id() << std::endl;
指纹
button1.id = 1
button2.id = 2
如果你必须有共享指针,下一个最简单的事情是
auto button1 = std::make_shared<Control>(injector.create<Control>());
auto button2 = std::make_shared<Control>(injector.create<Control>());
std::cout << "button1->id = " << button1->id() << std::endl;
std::cout << "button2->id = " << button2->id() << std::endl;
从概念上讲,你想要一个控件工厂,而不是一个控件。因此,应考虑从依赖项容器创建工厂:
#include <boost/di.hpp>
#include <iostream>
#include <memory>
namespace di = boost::di;
struct CommandQueue {
void addCommand() {}
};
struct Control {
Control(CommandQueue &cq) : _cq(cq), _id(idgen()) { }
int id() const { return _id; }
struct Factory {
Factory(CommandQueue& cq) : _cq(cq) {}
CommandQueue& _cq;
template <typename... Args>
auto operator()(Args&&... args) const {
return std::make_shared<Control>(_cq, std::forward<Args>(args)...);
}
};
private:
static int idgen() { static int sid{}; return ++sid; }
CommandQueue &_cq;
int _id{};
};
int main() {
auto injector = di::make_injector(di::bind<CommandQueue>().in(di::singleton));
auto factory = injector.create<Control::Factory>();
auto button1 = factory();
auto button2 = factory();
std::cout << "button1->id = " << button1->id() << std::endl;
std::cout << "button2->id = " << button2->id() << std::endl;
}
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 将GoogleMock与Boost::Shared Pointers一起使用时泄漏的Mock对象
- 在python中打开共享对象文件时出错(OSError: cannot open shared object file: