类成员的唯一性

Uniqueness in class members

本文关键字:唯一性 成员      更新时间:2023-10-16

c++新手在这里,我希望我的类引用相同的对象与相同的构造函数参数的所有实例化(例如,如果对象已经存在,我实例化的新变量应该返回现有的对象,而不是创建一个具有相同的值)。是否有一种语义上的方法来做到这一点,或者是最好的方法来保持一个静态向量,其中包含类中的所有对象,并检查在构造函数中,如果一个存在相同的参数?

如果你可以从参数中创建一个散列,你可以做一些类似的事情:

class YourClass
{
    static std::unordered_map< std::string, YourClass > s_instances; // You can use std::map as well
    static YourClass& get_instance( paramtype1 param1, paramtype2 param2 );
    static std::string create_hash( paramtype1 param1, paramtype2 param2 );
    // The implementation depends on the type of parameters
};
std::unordered_map< std::string, YourClass > YourType::s_instances;
YourClass& YourClass::get_instance( paramtype1 param1, paramtype2 param2 )
{
    auto hash = create_hash( param1, param2 );
    auto it = s_instances.find( hash );
    if ( it == s_instances.end( ) )
    {
        return it->second;
    }
    else
    {
        s_instances[ hash ] = YourType( param1, param2 );
        return s_instances[ hash ];
    }
}

自然有很多问题需要你回答:1. 这个操作应该是线程安全的吗?即可以通过多个线程并行或不访问?如果是,你应该保护s_instances不被并行修改。

  • 毁灭阶段会是什么样子?静态成员的销毁顺序与创建顺序相反,很难控制何时执行。这意味着有可能在YourClass的析构函数中已经销毁了需要的某些资源。因此,我建议一些可控的破坏阶段,其中s_instances元素被移除和破坏。