S*****H 发帖数: 90 | 1 In the following code, why a3 is wrong, but a2 is wrong?
#include
using namespace std;
class A{
char * word;
public:
//Read this constructor carefully
A(char * cp){ word = cp;}
~A(){delete[] word;}
};
int main(){
char w[] = "spam";
char * wp = new char[5];
strcpy(wp, w);
A a2 = A(w);
A a3 = A(wp);
return 0;
} | H***a 发帖数: 735 | 2 "why a3 is wrong, but a2 is wrong"? Is that your question? Please check your
question before asking.
I confirmed that a3 works but a2 doesn't, because the destructor of A is
trying to delete the array allocated on the stack rather than on the heap, which
is forbidden. | S*****H 发帖数: 90 | 3 Hyena (大石头),
You are right. I mis-typed the question. The results are just
the opposite.
Thank you for your answer very much! |
|