抛出后为什么shared_ptr为NULL

时间:2017-10-02 00:31:31

标签: c++ gcc shared-ptr throw

我在C ++中有一个shared_ptr,我想把它作为一个例外。我正在编写一个测试用例,在gcc 6.4.0中使用了相同的情况并且卡住了。

我不明白为什么在处理异常后x为NULL,即使它没有超出范围或被分配给。

#include "stdafx.h"
#include <iostream>
#include <memory>
#include <string>
using namespace std;

class S {
private:
    string s;
public:
    string String()
    {
        return s;
    }
    S(string a) : s(a)
    {
        cout << "S::S( " << a << " )" << endl;
    }
    ~S()
    {
        cout << "S::~S( " << String() << " )" << endl;
    }
};
int main(int argc, char* argv[])
{
    shared_ptr< S > x = make_shared<S>("hello world");
    cout << "Before throw" << endl;
    try {
        throw x;
    }
    catch (shared_ptr<S> e) {
        cout << "Caught it!" << endl;
        if (e) {
            cout << e->String() << endl;
        }
    }
    cout << "After throw" << endl;

    if (!x) {
        cout << "X is Null" << endl;
    }
    cout << "I'm done" << endl;
    return 0;
}

Visual Studio 2013完成了我的期望:

S::S( hello world )
Before throw
Caught it!
hello world
After throw
I'm done
S::~S( hello world )

但是GCC 6.4.0(来自Cygwin)没有:

S::S( hello world )
Before throw
Caught it!
hello world
S::~S( hello world )
After throw
X is Null
I'm done

这里有什么东西我不明白这会使GCC的行为合法吗?我可以按照预期在gcc中使用吗?

[这与评论中提到的问题中提到的gcc错误相同。我希望有一种方法可以继续为我的项目开发测试用例。我找到的解决方案是将“try / catch”放在以x作为参数的单独函数中。]

[这个bug比它看起来更微妙。如果添加“swap(x,e);”在异常处理程序内部,在处理程序返回之后,x不再为空,但e在处理程序中为null。我试图保存S实例并更好地了解情况。当我添加那个交换时,不仅x在结尾处不是空的(我预期),e在交换之后是空的,这是完全出乎意料的。添加交换将输出更改为

S::S( hello world )
Caught it!
S::~S( hello world )

为什么交换两个应该相同的东西并不明显。]

0 个答案:

没有答案
相关问题