C 将HEAP对象插入std ::用insert()插入映射,而另一个则存在删除新的对象
C++ When inserting heap Objects into std::map with insert() and another one exists who deletes the new one?
当我需要使用此方法插入多个值时,我正在尝试(某种程度上)在std :: map上缓存多个迭代:
enum PROPERTY_TYPE
{
TYPE_BOOLEAN,
TYPE_INTEGER,
TYPE_UNSIGNED,
TYPE_FLOAT,
TYPE_STRING
};
struct Property {
Property(PROPERTY_TYPE type)
: type(type), bool_val(false), integer_val(0), unsigned_val(0), float_val(0.0f), string_val("")
{ }
PROPERTY_TYPE type;
bool bool_val;
int integer_val;
unsigned int unsigned_val;
float float_val;
std::string string_val;
};
std::map< std::string, Property* > _Properties;
void pushBool(std::string key, bool value)
{
std::pair< std::map< std::string, Property* >::iterator, bool > pItr;
pItr = _Properties.insert( std::pair< std::string, Property* >(key, new Property(TYPE_BOOLEAN)) );
// If the value doesn't exist then it's created automatically or the existion one is used.
pItr.first->second->bool_val = value;
pItr.first->second->integer_val = value ? 1 : 0;
pItr.first->second->unsigned_val = value ? 1 : 0;
pItr.first->second->float_val = value ? 1.0f : 0.0f;
pItr.first->second->string_val = value ? "true" : "false";
}
这是我可以使它能够工作到目前为止的最快,最安全的方法。但是我对一件小东西感兴趣,这就是插入()函数。当我调用新属性(type_boolean)时,我显然创建了一个没有任何控制它的新属性()。从我阅读的内容来看,STD :: MAP在丢弃时不会在指针上删除。当我使用这种插入插入函数的方法时,如果已经存在现有值。那么,谁删除了新创建的属性(),如果一个值已经存在并且使用该值而不是新的属性?
pItr = _Properties.insert( std::pair< std::string, Property* >(key, new Property(TYPE_BOOLEAN)) );
此方法是否通过引入内存泄漏来浪费内存?
是的,该行可能会导致泄漏。
存储智能指针,或在插入之前检查存在。我建议聪明的指针。 unique_ptr
可能是指所有权。
在这种特殊情况下,免费存储分配是一个坏主意,但是我认为真正的问题有一个将物品存储在此处的理由。
你是对的-std::map
不收集谁删除其存储的任何指示的问题 - 它期望客户端代码承担责任,或者存储一种固有地执行此操作的类型。做到这一点的最简单,通常是最好的方法 - 除非您看到明确的理由这样做,否则您将使用"价值语义"类型 - 一种照顾自己的生活,可以是直观地复制,表现很像int
或其他内置类型。
在您的情况下,表面上没有理由使用指针...只是
std::map< std::string, Property > _Properties;
如果您不在乎是插入新元素还是更新旧元素:
Property& p = _Properties[key];
p.bool_val = value;
p.integer_val = ... etc
单独的想法是,如果属性在概念上存储了这些类型的数据中的任何一种,则可能会发现boost::variant
有用:http://www.boost.org/doc/doc/libs/1_55_0/doc/doc/html/variant。html
相关文章:
- 将包含不可复制对象的对插入到映射中
- 在 std::map 中插入对象时构造函数中变量的地址
- 在 c++ 列表中插入对象
- 在列表C 中插入对象
- 如何创建插入对象使用duktape
- 如何在地图中插入对象以保持其排序
- bad_alloc通过右值和对象有效性插入对象时
- 插入对象以设置c++
- 在地图中插入对象而不复制对象
- C++:使用递归在二叉搜索树中插入对象
- 如何在矢量中高效、正确地插入对象
- vector插入对象的副本或引用
- 我可以插入对象到tr1 unordered_map
- 在ostreams中插入对象
- 如何在指针数组中插入对象
- 在链表中按升序插入对象
- 标记分派结构不能插入对象类型
- 链表-插入对象
- 在vector的下标处插入对象
- 按字母顺序向vector插入对象