这可能是一个基本问题,可能已经被问过(比方说,这里); 但我还是不明白.所以,让我问一下.
考虑以下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
}
};
Run Code Online (Sandbox Code Playgroud)
以下代码片段之间的区别是什么:
Obj o1 ("Hi\n");
Run Code Online (Sandbox Code Playgroud)
和
Obj* o2 = new Obj("Hi\n");
Run Code Online (Sandbox Code Playgroud)
为什么前者调用析构函数,但后者不调用(没有显式调用delete)?
哪一个更受欢迎?