C 将HEAP对象插入std ::用insert()插入映射,而另一个则存在删除新的对象



当我需要使用此方法插入多个值时,我正在尝试(某种程度上)在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

最新更新