【发布时间】:2018-03-31 16:43:35
【问题描述】:
使用这个示例代码,我希望得到这样的结果 button1 和 button2 是两个独立的对象。
#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;
}
当前输出为:
button1->id = 1
button2->id = 1
而不是预期的:
button1->id = 1
button2->id = 2
从 CommandQueue 单例中删除 di::singleton 生命周期范围也不能修复它。
我知道默认情况下 shared_ptr 的生命周期范围是单例,但我认为这是指注入的依赖项,而不是使用 create 创建的实际对象。
【问题讨论】:
-
addCommand的相关性是什么 -
这只是一个占位符来证明使用 CommandQueue 作为单例是合理的,但即使没有这个,代码仍然会创建 1 个对象而不是 2 个
标签: c++ boost dependency-injection shared-ptr