类成员的唯一性
Uniqueness in class members
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
元素被移除和破坏。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 嵌套在类中时无法设置成员数据
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 将函数类成员映射到类本身内部
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 将公共但非静态的成员函数与ALGLIB集成
- 多成员Constexpr结构初始化
- 类成员的唯一性