Y
yccheok
Hi, i am from java background and c++ is quite new for me. Consider the
following code:
i obtain an warning from my compiler which states:
a.cpp:45: warning: taking address of temporary
it seems that i am facing problem in accessing an object which has
already been deallocated in stack memory.
unliked java, the object will not be allocated as long as there is a
reference pointing to it.
in c++ case, is there any way to solve this problem without using
dynamic memory allocation (new and delete)?
thank you very much!
-cheok
#include <iostream>
using namespace std;
class a {
int name;
public:
a(int);
~a();
int getName();
a createA(int);
};
a::a(int value) {
name = value;
cout<< "a named "<< name<< " is created"<< endl;
}
a::~a() {
cout<< "a named "<< name<< " is DELETED"<< endl;
}
int a::getName() {
return name;
}
a a::createA(int i) {
a aa(i);
return aa;
}
int main() {
int i=0;
a solidA(100);
a* tmp;
while(true) {
if(i > 0) {
cout<< "am i access 'a' which has been
deleted?? "<< tmp->getName()<< endl;
}
cout<< "creating 'a' and preparing to assign it to a
reference..."<< endl;
tmp = &(solidA.createA(i));
// tmp is now holding 'a' which already been deleted in
stack memory.
i++;
}
}
following code:
i obtain an warning from my compiler which states:
a.cpp:45: warning: taking address of temporary
it seems that i am facing problem in accessing an object which has
already been deallocated in stack memory.
unliked java, the object will not be allocated as long as there is a
reference pointing to it.
in c++ case, is there any way to solve this problem without using
dynamic memory allocation (new and delete)?
thank you very much!
-cheok
#include <iostream>
using namespace std;
class a {
int name;
public:
a(int);
~a();
int getName();
a createA(int);
};
a::a(int value) {
name = value;
cout<< "a named "<< name<< " is created"<< endl;
}
a::~a() {
cout<< "a named "<< name<< " is DELETED"<< endl;
}
int a::getName() {
return name;
}
a a::createA(int i) {
a aa(i);
return aa;
}
int main() {
int i=0;
a solidA(100);
a* tmp;
while(true) {
if(i > 0) {
cout<< "am i access 'a' which has been
deleted?? "<< tmp->getName()<< endl;
}
cout<< "creating 'a' and preparing to assign it to a
reference..."<< endl;
tmp = &(solidA.createA(i));
// tmp is now holding 'a' which already been deleted in
stack memory.
i++;
}
}