C++ 创建一个对象:有或没有`new`
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6337294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating an object: with or without `new`
提问by M.S. Dousti
Possible Duplicate:
What is difference between instantiating an object using new vs. without
可能的重复:
使用 new 和不使用实例化对象有什么区别
This is probably a basic question, and might have already been asked (say, here); yet I still don't understand it. So, let me ask it.
这可能是一个基本问题,并且可能已经被问过(比如,这里);但我还是不明白。所以,让我问一下。
Consider the following C++ class:
考虑以下 C++ 类:
class Obj{
char* str;
public:
Obj(char* s){
str = s;
cout << str;
}
~Obj(){
cout << "Done!\n";
delete str; // See the comment of "Loki Astari" below on why this line of code is bad practice
}
};
what's the difference between the following code snippets:
以下代码片段有什么区别:
Obj o1 ("Hi\n");
and
和
Obj* o2 = new Obj("Hi\n");
Why the former calls the destructor, but the latter doesn't (without explicit call to delete
)?
为什么前者调用析构函数,而后者不调用(没有显式调用delete
)?
Which one is preferred?
哪一个是首选?
回答by Lightness Races in Orbit
Both do different things.
两者都做不同的事情。
The first creates an object with automatic storage duration. It is created, used, and then goes out of scope when the current block ({ ... }
) ends. It's the simplest way to create an object, and is just the same as when you write int x = 0;
第一个创建一个具有自动存储期的对象。它被创建、使用,然后在当前块 ( { ... }
) 结束时超出范围。这是创建对象最简单的方法,和你写的时候一样int x = 0;
The second creates an object with dynamic storage durationand allows two things:
第二个创建一个具有动态存储持续时间的对象,并允许做两件事:
Fine control over the lifetime of the object, since it does not go out of scope automatically; you must destroy it explicitly using the keyword
delete
;Creating arrays with a size known only at runtime, since the object creation occurs at runtime. (I won't go into the specifics of allocating dynamic arrays here.)
对对象生命周期的精细控制,因为它不会自动超出范围;您必须使用关键字显式销毁它
delete
;创建大小仅在运行时已知的数组,因为对象创建发生在运行时。(我不会在这里讨论分配动态数组的细节。)
Neither is preferred; it depends on what you're doing as to which is most appropriate.
两者都不是首选;这取决于你在做什么,哪个最合适。
Use the former unless you need to use the latter.
除非您需要使用后者,否则请使用前者。
Your C++ book should cover this pretty well. If you don't have one, go no furtheruntil you have bought and read, several times, one of these.
你的 C++ 书应该很好地涵盖了这一点。如果您没有,请不要再继续,直到您购买并阅读了其中之一。
Good luck.
祝你好运。
Your original code is broken, as it delete
s a char
array that it did not new
. In fact, nothingnew
d the C-style string; it came from a string literal. delete
ing that is an error (albeit one that will not generate a compilation error, but instead unpredictable behaviour at runtime).
您的原始代码已损坏,因为它delete
是char
它没有的数组new
。事实上,没有什么new
d C 风格的字符串;它来自一个字符串文字。delete
这是一个错误(尽管不会产生编译错误,而是在运行时产生不可预测的行为)。
Usually an object should not have the responsibility of delete
ing anything that it didn't itself new
. This behaviour should be well-documented. In this case, the rule is being completely broken.
通常一个对象不应该负责delete
ing 任何它本身没有的东西new
。这种行为应该有据可查。在这种情况下,规则完全被打破了。
回答by Jerry Coffin
The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.
第一个分配一个具有自动存储持续时间的对象,这意味着它会在退出它定义的范围时自动销毁。
The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete
to do so.
第二个分配了一个具有动态存储持续时间的对象,这意味着它不会被销毁,直到您明确使用delete
它。