我正试图在C++中创建一个DI容器(用于研究目的)。我知道boost DI容器选项,但我只想自己编写一个有趣的选项。
我希望所创建的容器每个对象只有一个实例“已注册”,因此我应该应用Singleton design pattern。
但是,在C++20中或者至少在modern C++中实现C++20的最佳(惯用)方法是什么?为什么?
发布于 2021-12-29 13:30:05
你是说像这样用meyer的单身汉。(https://www.modernescpp.com/index.php/thread-safe-initialization-of-a-singleton)
我从不使用需要用new创建的单例,因为它们的析构函数从未被调用过。有了这种模式,当程序终止时,析构函数就会被调用。
#include <iostream>
//-----------------------------------------------------------------------------
// create an abstract baseclass (closest thing C++ has to an interface)
struct data_itf
{
virtual int get_value1() const = 0;
virtual ~data_itf() = default;
protected:
data_itf() = default;
};
//-----------------------------------------------------------------------------
// two injectable instance types
struct test_data_container :
public data_itf
{
int get_value1() const override
{
return 0;
}
~test_data_container()
{
std::cout << "test_data_container deleted";
}
};
struct production_data_container :
public data_itf
{
int get_value1() const override
{
return 42;
}
~production_data_container()
{
std::cout << "production_data_container deleted";
}
};
//-----------------------------------------------------------------------------
// meyers threadsafe singleton to get to instances implementing
// interface to be injected.
//
data_itf& get_test_data()
{
static test_data_container test_data;
return test_data;
}
data_itf& get_production_data()
{
static production_data_container production_data;
return production_data;
}
//-----------------------------------------------------------------------------
// object that needs data
class my_object_t
{
public:
explicit my_object_t(const data_itf& data) :
m_data{ data }
{
}
~my_object_t()
{
std::cout << "my_object deleted";
}
void function()
{
std::cout << m_data.get_value1() << "\n";
}
private:
const data_itf& m_data;
};
//-----------------------------------------------------------------------------
int main()
{
auto& data = get_production_data();
my_object_t object{ data };
object.function();
return 0;
}https://stackoverflow.com/questions/70519915
复制相似问题