为什么会有3个析构函数被调用解决思路

为什么会有3个析构函数被调用#includeiostreamclassxBoundary{public://constructorsxBoundary()xBound

为什么会有3个析构函数被调用
#include   <iostream>

class   xBoundary
{
public:
        //   constructors
        xBoundary();
        xBoundary(const   int   index);
        ~xBoundary();

        //   accessor
        int   ErrIndex()   const   {return   myIndex;}
 
private:
        int   myIndex;
};

//   implementations
//   The   constructors   merely   print   out   a   message
//   indicating   they   have   bee   called,   along   with
//   the   value   of   their   myIndex   property.
xBoundary::xBoundary():
myIndex(-1)
{
        std::cout   < <   "xBoundary()   ->   myIndex= "   < <   myIndex   < <   "\n ";
}

xBoundary::xBoundary(const   int   index):
myIndex(index)
{
        std::cout   < <   "xBoundary(const   int)   ->   myIndex= "   < <   myIndex   < <   "\n ";
}

xBoundary::~xBoundary()
{
        std::cout   < <   "~xBoundary()   ->   myIndex= "   < <   myIndex   < <   "\n ";
}

int   main()
{
        const   int   defaultSize   =   10;
        const   int   someOtherNumber   =   11;
        int   myArray[defaultSize];
        for   (int   i   =   0;   i   <   defaultSize;   i++)
                myArray[i]   =   i;
        try
        {
                for   (int   i   =   0;   i   <   someOtherNumber;   i++)
                {
                        if   (i   > =   defaultSize)
                                throw   xBoundary(i);
                        else
                                std::cout   < <   "myArray[ "   < <   i   < <   "]:\t "   < <   myArray[i]   < <   "\n ";
                }
        }
        catch(xBoundary   err)
        {
                std::cout   < <   "Failed   to   retrieve   data   at   index   "   < <   err.ErrIndex()   < <   ".\n ";
        }
        return   0;
}

输出


xBoundary(const   int)   ->   myIndex=10
~xBoundary()   ->   myIndex=10
Failed   to   retrieve   data   at   index   10.
~xBoundary()   ->   myIndex=10
~xBoundary()   ->   myIndex=10

[解决办法]
throw xBoundary(i);
要不要写成throw new xBoundary(i)..
弱弱的问
[解决办法]
还有
xBoundary(const int index);
这里声明成const没有什么意义吧
[解决办法]
catch(xBoundary err)
改为:
catch(xBoundary& err)
异常最好用引用捕获。
如果你不用引用,那么无谓的多一次拷贝,也得不到任何好处。

不过异常对象会至少被拷贝一次,因为最后随着栈回滚的肯定不可以是原来那个(原来那个在它自己作用域的结尾就要背析构掉了,无法在catch中使用)。

楼上提到的用堆对象的方法可解决这个问题,但那要的话,应该这样catch:
catch(xBoundary* err);
这倒无所谓,但它需要你在某个catch中把它delete掉,这比较烦,你得好好设计到哪一步delete。
[解决办法]
临时对象啊 ~

它也要析构的 ······
[解决办法]
三个对象:
throw xBoundary(i)里一个
临时对象一个
还有哪个?

却没有调用三个构造函数xBoundary::xBoundary(const int index),这个是为什么啊
[解决办法]
throw xBoundary(i)会产生2个临时对象,catch(xBoundary err)一个
[解决办法]
throw xBoundary(i);
一个临时对象,构造函数xBoundary::xBoundary(const int index),析构
一个异常对象,用临时对象拷贝构造(使用默认拷贝构造函数,你这里未显式的提供),析构
一个局部对象xBoundary err,用异常对象拷贝构造,析构
所以三次
只用一个xBoundary(const int index),其他两个构造的使用的是拷贝构造函数,编译器的提供