简体   繁体   English

C ++-如何使用new运算符创建multimap的新实例?

[英]C++ - How to create new instance of a multimap using new operator?

I am trying something like this - 我正在尝试这样的事情-

//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;

I have to create new instance of multimap in a function, that needs to be called multiple times. 我必须在一个函数中创建multimap的新实例,该实例需要多次调用。

I am new to C++. 我是C ++的新手。 Please let me know if I am considering anything wrong. 如果我考虑有任何问题,请让我知道。

You most likely don't want to use new . 您很可能不想使用new Unlike in languages like Java, the new keyword is not needed for every object creation in C++, and unlike in many other languages, objects created with new are not automatically destroyed when you no longer need them. 与Java之类的语言不同,在C ++中并非每次创建对象都需要new关键字,而且与许多其他语言不同,使用new创建的对象在不再需要它们时不会自动销毁 You instead have to delete them manually with delete . 你,而不是必须用手动删除它们delete

Also, new does not return the newly created object itself but a pointer to it, allowing you to do nasty things like storing the pointer, later deleting the object and then accidentally attempting to access it through the stored pointer, which may crash the program. 另外, new不会返回新创建的对象本身,而是返回指向它的指针,从而使您可以执行讨厌的操作,例如存储指针,稍后删除对象,然后意外地尝试通过存储的指针访问它,这可能会使程序崩溃。

All of this creates endless problems and bugs. 所有这些都会带来无尽的问题和错误。 Especially if you are a newbie (or if you gain more experience and think you can finally handle the complexity :)). 尤其是如果您是新手(或者如果您获得更多经验并认为您最终可以解决复杂问题:))。

In C++, normal object creation doesn't require new . 在C ++中,正常的对象创建不需要new It is much simpler. 这要简单得多。 Your first line is already object creation: 您的第一行已经对象创建:

multimap <int, string> prioritized_list;

No need for new here. 这里不需要new

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM