原创 Destroying everything in every path

2011-3-10 10:36 2188 10 10 分类: 消费电子

Although I know both C and C++ quite well, I much prefer programming in C++. Features such as classes and access control help me partition my programs into components that are typically simpler and easier to use than they would be in C, with little or no loss of efficiency. Features such as constructors and destructors eliminate most of the resource management problems I encounter when I program in C.


Despite my preference, I understand and appreciate that many programmers still have to program in C for pragmatic reasons. As I've demonstrated in some of my columns over the years, conscientious C programmers can do a reasonably good job of mimicking classes with constructors.1, 2 It just takes more effort and discipline in C than it does in C++. Unfortunately, approximating classes with destructors can take a lot more discipline. Let me show you why.


Suppose widget is a type for an object that, among other things, manages a POSIX-style file referenced via an integer-valued file descriptor. In C, the definition for the widget type might look something like:


typedef struct widget widget;
struct widget
{
    int fd;     // a file descriptor
    // other data members
};


A function f that uses a local widget object might look like:


int f(void)
{
    widget w;
    w.fd = open(tmpnam(), O_RDWR);
    // do whatever else f does
    close(w.fd);
    return 0;
}


The statement immediately after w's declaration opens a temporary read-write file and assigns the associated file descriptor to w's fd member. The later call to close closes that temporary file just before the function returns, thus avoiding a resource leak. However, a leak could easily occur elsewhere in function f.


For example, suppose a conditional such as:


if (something bad happened)
    return -1;


were buried in the body of f. A call to f that terminates via this return-statement will fail to close w's file, causing a resource leak. Rewriting this conditional as:


if (something bad happened)
{
    close(w.fd);
    return -1;
}


eliminates the leak. It's not hard to write once you know you need to do it. Unfortunately, it's easy to overlook. It also forces you to duplicate code, which increases code size and invites future maintenance problems.



Using destructors in C++ reduces the possibility of resource leaks. You can define widget as a class with a constructor and a destructor, as follows:


class widget
{
public:
    widget();
    ~widget();
    // other member functions
private:
    int fd;
    // other data members
};


The constructor opens the file:


inline
widget::widget()
{
    fd = open(tmpnam(), O_RDWR);
}


and the destructor closes it:


inline
widget::~widget()
{
    close(fd);
}


Note that a destructor doesn't deallocate the storage for an object. It releases the resources managed by the object, some of which may be storage. The storage for the object being destroyed will be deallocated by some other runtime agent of the program. For example, for a widget object declared local to a function, the destructor for that widget executes just before the program returns from that function. The destructor releases the widget's resources, and then the runtime system deallocates the widget's storage by popping it off the stack along with the rest of the function's stack frame.


Using this widget class simplifies function f:


int f(void)
{
    widget w;
    // do whatever else f does
    return 0;
}


The compiler generates a call to the widget constructor as part of w's declaration. The compiler also generates a call to the widget destructor applied to w as part of the function return, as it would for any other return elsewhere in the function body.


When adding an error return somewhere in the middle of the function, you need not worry about closing the file inside the widget. For example:


int f(void)
{
    widget w;
    // do some of what f does
    if (
something bad happened)
       return -1;
    // do the rest of what f does
    return 0;
}


No matter which return-statement terminates f, the widget destructor always executes.


Of course, you can mimic this behavior in C, but it's much harder to be sure that you got it right. Again, you define widget as a struct:


struct widget
{
    int fd;    // a file descriptor
    // other data members
};


and the widget constructor and destructor as functions that each accept a pointer to a widget:


inline
void widget_construct(widget *w);
{
    w->fd = open(tmpnam(), O_RDWR);
}



inline
void widget_destroy(widget *w)
{
    close(w->fd);
}


Then you can write function f as:


int f(void)
{
    widget w;
    widget_construct(&w);
    // do some of what f does
    if (
something bad happened)
    {
       widget_destroy(&w);
       return -1;
    }
    // do the rest of what f does
    widget_destroy(&w);
    return 0;
}


If the function has multiple returns and several local objects, you may wish to avoid calling the destructors for all those objects before every return. You can do it, but you have to introduce an additional local variable and fiddle with the control flow:


int f(void)
{
    int rv = 0;
    widget w;
    widget_construct(&w);
    // do some of what f does
    if (
something bad happened)
        rv = -1;
    elsehttp://forum.eetasia.com/update_entry!default***pa?entry_id=6801&blog_id=767
        // do the rest of what f does
    widget_destroy(&w);
    return rv;
}


You might even have to resort to using goto-statements. Gasp!


Compiler-generated destructor calls are almost completely effortless and clearly less error-prone than doing it by hand.


Thanks to Steve Dewhurst (www.semantics.org) for some helpful insights on this subject.


Endnotes:
1 Saks, Dan, "Incomplete Types as Abstractions," Embedded Systems Programming, December 2003, p. 43.
2. Saks, Dan, "Allocating objects vs. allocating storage," Embedded Systems Design, September, 2008, p. 11.

文章评论0条评论)

登录后参与讨论
我要评论
0
10
关闭 站长推荐上一条 /2 下一条