![](/img/trans.png)
[英]Which one: Stack or Heap is used when creating objects by NEW in C++
[英]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";
}
到目前為止,這是最快,最安全的方法。 但是我對一件小事情感興趣,那就是insert()函數。 當我調用new Property(TYPE_BOOLEAN)時,我顯然創建了一個新的Property(),沒有人控制它。 從我讀到的內容來看,std :: map在丟棄時不會在指針上調用delete。 當我使用這種插入方法時,插入函數將使用現有值(如果已經存在)。 因此,如果一個值已經存在並且使用它而不是新值,誰會刪除該新創建的Property()?
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/libs/1_55_0/doc/html/variant。 HTML
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.