Why do I need to call new?

Possible Duplicates:
When to use “new” and when not to, in C++?
When should I use the new keyword in C++?

It seems like I could program something without ever using the word new , and I would never have to worry about deleting anything either, so why should I ever call it?

From what I understand, it's because I would run out of stack memory.

Is this correct? I guess my main question is, when should I call new ?


It's a matter of object lifetime: if you stack-allocate your objects, the objects destructors will be called when these objects go out of scope (say, at the end of the method). This means that if you pass these objects out of the method that created them, you'll find yourself with pointers to memory that could be overwritten at any time.


It's because you may not know at compile time whether you need an object, or how many, or of what type. The new operator allows you to dynamically allocate objects without having to know such things in advance.

Here's an example of not knowing the type of object in advance:

class Account { ... };
class CheckingAccount : public Account { ... };
class VisaAccount : public Account { ... };

...

Account *acct = type == "checking" ? new CheckingAccount : new VisaAccount;

The main reason you'll need to use new/delete is to get manual control the lifetime of your objects.

Other reasons are already provided by others but I think it's the more important. Using the stack, you know exatly the lifetime of your objects. But if you want an object to be destroyed only after an event occurs, then it cannot be automatically defined.

链接地址: http://www.djcxy.com/p/96526.html

上一篇: 'new'关键字在c ++中做了什么?

下一篇: 为什么我需要拨打新电话?