![](/img/trans.png)
[英]How to create object in heap without using new operator in c++?
[英]C++ - How to create new instance of a multimap using new operator?
我正在嘗試這樣的事情-
//creation of multimap
multimap <int, string> prioritized_list;
//declared pointer for multimap
multimap <int, string>::const_pointer plist_pointer;
//tried to create instance of multimap.
plist_pointer=new prioritized_list;
我必須在一個函數中創建multimap的新實例,該實例需要多次調用。
我是C ++的新手。 如果我考慮有任何問題,請讓我知道。
您很可能不想使用new
。 與Java之類的語言不同,在C ++中並非每次創建對象都需要new
關鍵字,而且與許多其他語言不同,使用new
創建的對象在不再需要它們時不會自動銷毀 。 你,而不是必須用手動刪除它們delete
。
另外, new
不會返回新創建的對象本身,而是返回指向它的指針,從而使您可以執行討厭的操作,例如存儲指針,稍后刪除對象,然后意外地嘗試通過存儲的指針訪問它,這可能會使程序崩潰。
所有這些都會帶來無盡的問題和錯誤。 尤其是如果您是新手(或者如果您獲得更多經驗並認為您最終可以解決復雜問題:))。
在C ++中,正常的對象創建不需要new
。 這要簡單得多。 您的第一行已經是對象創建:
multimap <int, string> prioritized_list;
這里不需要new
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.