我有这个引发异常的构造函数
GenericSocket::GenericSocket(const string& hostname,
const string& servname):
_hostname(hostname),
_servname(servname)
{
initHints();
int rv;
if((rv = getaddrinfo(_hostname.c_str(),
_servname.c_str(),
&_hints,
&_servinfo)) != 0) {
throw GenericSocketException();
}
}
initHints() 执行 _hints 的 memset 并设置一些变量。
我用谷歌测试框架测试它,如下所示:
TEST(CreateObject2, getaddrinfoException)
{
mgs_addrinfo_return = 1;
ASSERT_THROW(new GenericSocket("testhost", "4242"), GenericSocketException);
}
测试失败并出现核心转储:
[ RUN ] CreateObject2.getaddrinfoException
socket creation failed
terminate called after throwing an instance of 'common::GenericSocketException'
what(): Socket creation failed
[1] 43360 abort (core dumped) ./bin/test_common
除了我不知道到底出了什么问题之外,我怀疑一些未初始化的对象被删除了(?),很多事情似乎在幕后发生,所以我开始怀疑在构造函数中抛出异常是否是一种好习惯。将这个功能放在另一个我可以在创建对象后调用的函数中,然后处理异常是否更好?