1

假设有一个对象的析构函数为:

anObject::~anObject()
{
    _functionCalledfromDestructor=1; //this sets the flag = 1
    functionCall(); //this function does something different than usual
                    //on seeing the flag
}

我的问题:

这种在析构函数中编码的风格/方法是一个好习惯吗?

4

4 回答 4

10

像这样的“隐藏频道”总是一个坏主意。函数的行为不应该依赖于不可见的状态。您可以给函数一个参数,然后在析构函数中传递一个值,在其他任何地方传递另一个值。如果您愿意,可以为更常见的情况使用默认值。

于 2012-07-18T19:08:35.580 回答
7

这种在析构函数中编码的风格/方法是一个好习惯吗?

如果函数根据调用它的位置做了两件不同的事情,那么你有两个函数,而不是一个。让这两个函数实际上是两个函数,你不需要问这个问题。

于 2012-07-18T19:07:35.220 回答
4

一般来说,没有。我认为你最好做这样的事情:

class anObject 
{
private:
  void doSomethingInternal(bool fromDestructor) {...}
public:
  void doSomething() {doSomethingInternal(false);};
  virtual ~anObject() { doSomethingInternal(true); };
}
于 2012-07-18T19:09:33.863 回答
0

Calling functions inside a destructor is commonly not considered a good practise, as there is the possibility that an exception is thrown. This leads to not correctly cleaned up memory and the behaviour of exceptions in the destructor is undefined.

Here is more information about throwing exceptions in the destructor:

SP on throwing in the destructor

In your case, a well defined clean up via a public interface is a whole better way to go. You could for example provide a Dispose method that does the clean-up.

Consider something like the following (in pseudocode):

public:
    void Dispose()
    {
        bool isDestructing = true;
        functionCall(isDestructing);
    }
于 2012-07-18T19:10:20.120 回答