Should resource wrappers auto cleanup on destruct?

J

Julie

(I searched the FAQ, but didn't find anything relevant -- if there is, please
post a link.)

Is there a design paradigm that indicates that a class that manages an external
resource should automatically perform clean up in the destructor?

For example, suppose the following file-wrapper class.

// begin

class file
{
private:
int fileHandle;

public:
file()
{
fileHandle = 0;
}
void open(char * fileName)
{
fileHandle = MySystemIO::OpenFile(fileName);
}
void close()
{
if (fileHandle)
{
MySystemIO::CloseFile(fileHandle);
fileHandle = 0;
}
}
~file()
{
// call close() here or not?
// close();
}
}

// end

I realize that from a /documentation/ standpoint, I can do either and just
document wether or not the destructor performs cleanup

-- however --

I'm mostly interested in a self-documenting code perspective, where (external)
documentation isn't referenced.

Comments???
 
R

red floyd

Julie said:
(I searched the FAQ, but didn't find anything relevant -- if there is,
please post a link.)
[redacted]

Google for "RAII" (Resource Acquisition Is Initialization).
 
M

Mike Wahler

Julie said:
(I searched the FAQ, but didn't find anything relevant -- if there is, please
post a link.)

Is there a design paradigm that indicates that a class that manages an external
resource should automatically perform clean up in the destructor?

Yes. Stroustrup's "RAII" ("Resource Acquisition Is Initialization").
For example, suppose the following file-wrapper class.

// begin

class file
{
private:
int fileHandle;

public:
file()
{
fileHandle = 0;
}
void open(char * fileName)
{
fileHandle = MySystemIO::OpenFile(fileName);
}
void close()
{
if (fileHandle)
{
MySystemIO::CloseFile(fileHandle);
fileHandle = 0;
}
}
~file()
{
// call close() here or not?
// close();
}
}

// end

I realize that from a /documentation/ standpoint, I can do either and just
document wether or not the destructor performs cleanup

-- however --

I'm mostly interested in a self-documenting code perspective, where (external)
documentation isn't referenced.

Comments???

IMO the purpose of a dtor is exactly that: put things back the
way you found them.

-Mike
 
J

Jonathan Turkanis

Mike said:
IMO the purpose of a dtor is exactly that: put things back the
way you found them.

This is a rather Sisyphisian view of class design, isn't it? Won't clients start
complaining that no work is getting done? :)

Jonathan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top