Y
yang su
I have a very simple program listed below, which basically tries to
use resources but prevent from memory leak should exception occurs.
class T is the resource and class User is to use the resource, my
expectation is that when t2 fails, the destructor of t1 should be
called, which didn't happen.
I use g++ 3.2.3 on solaris 2.8, thanks.
yang
#include <string>
#include <iostream>
using namespace std;
class T {
private:
string name;
public:
T(const string& name) {
this->name = name;
cout<<"allocate resource for " << name << endl;
if( name.compare("banana") == 0 ) {
throw exception();
}
}
operator string() {
return name;
}
~T() {
cout<<"deallocate resource from " << name << endl;
}
};
class User {
private:
T t1, t2;
public:
User(const string& s, const string& p): t1(s), t2(p) {
cout<<"user inited" << endl;
try{
throw exception();
}catch(exception& e) {
}
}
void use( ) {
cout<< "use "<< (string)t1 << " and " << (string)t2 <<
endl;
throw exception();
}
~User() {
cout <<"user destroyed" << endl;
}
};
int main(int argc, char **argv) {
/*
User *u = NULL;
if( argc >= 3 ) {
if( argc > 3 ) {
User x(argv[1], argv[2]);
x.use();
return 0;
}
}
u = new User( argv[1], argv[2] );
}else{
u = new User(string("apple"), string("banana"));
}
u->use();
delete u;
*/
User u("apple", "banana");
u.use();
}
use resources but prevent from memory leak should exception occurs.
class T is the resource and class User is to use the resource, my
expectation is that when t2 fails, the destructor of t1 should be
called, which didn't happen.
I use g++ 3.2.3 on solaris 2.8, thanks.
yang
#include <string>
#include <iostream>
using namespace std;
class T {
private:
string name;
public:
T(const string& name) {
this->name = name;
cout<<"allocate resource for " << name << endl;
if( name.compare("banana") == 0 ) {
throw exception();
}
}
operator string() {
return name;
}
~T() {
cout<<"deallocate resource from " << name << endl;
}
};
class User {
private:
T t1, t2;
public:
User(const string& s, const string& p): t1(s), t2(p) {
cout<<"user inited" << endl;
try{
throw exception();
}catch(exception& e) {
}
}
void use( ) {
cout<< "use "<< (string)t1 << " and " << (string)t2 <<
endl;
throw exception();
}
~User() {
cout <<"user destroyed" << endl;
}
};
int main(int argc, char **argv) {
/*
User *u = NULL;
if( argc >= 3 ) {
if( argc > 3 ) {
User x(argv[1], argv[2]);
x.use();
return 0;
}
}
u = new User( argv[1], argv[2] );
}else{
u = new User(string("apple"), string("banana"));
}
u->use();
delete u;
*/
User u("apple", "banana");
u.use();
}