ses*_*zed 8 c++ gcc throw shared-ptr
我在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;
}
Run Code Online (Sandbox Code Playgroud)
Visual Studio 2013完成了我的期望:
S::S( hello world )
Before throw
Caught it!
hello world
After throw
I'm done
S::~S( hello world )
Run Code Online (Sandbox Code Playgroud)
但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
Run Code Online (Sandbox Code Playgroud)
这里有什么东西我不明白这会使GCC的行为合法吗?我可以按照我的意图使它在gcc中运行吗?
[这与评论中提到的问题中提到的gcc错误相同.我希望有一种方法可以继续为我的项目开发测试用例.我发现的解决方案是将"try/catch"放在以x作为参数的单独函数中.
[这个错误比看起来更微妙.如果添加"swap(x,e);" 在异常处理程序内部,在处理程序返回之后,x不再为空,但e在处理程序中为null.我试图保存S实例并更好地了解情况.当我添加那个交换时,不仅x在结尾处不是空的(我预期),e在交换之后是空的,这是完全出乎意料的.添加交换将输出更改为
S::S( hello world )
Caught it!
S::~S( hello world )
Run Code Online (Sandbox Code Playgroud)
为什么交换两个应该相同的东西并不明显.
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |