r*********r 发帖数: 3195 | 1 中定义了 class exception:
class exception
{
public:
exception() throw() { }
virtual ~exception() throw();
virtual const char* what() const throw();
};
问题: 为什么 what() 返回一个 const char * 类型?
为什么不返回一个 string 呢? 可以返回一个 string 吗? |
t****t 发帖数: 6806 | 2 what if string throw another exception?
【在 r*********r 的大作中提到】 : 中定义了 class exception: : class exception : { : public: : exception() throw() { } : virtual ~exception() throw(); : virtual const char* what() const throw(); : }; : 问题: 为什么 what() 返回一个 const char * 类型? : 为什么不返回一个 string 呢? 可以返回一个 string 吗?
|
r*********r 发帖数: 3195 | 3 但是 logic_error 和 runtime_error 都有 data member 是 string 类型.
也就是说你 throw 一个 runtime_error object 时, 要作 string 的 copy
construction,
这样也有可能 throw another exception |
t****t 发帖数: 6806 | 4 well, the standard only says the interface (there's no obligation on data
members). implementation can do whatever they like to do...
【在 r*********r 的大作中提到】 : 但是 logic_error 和 runtime_error 都有 data member 是 string 类型. : 也就是说你 throw 一个 runtime_error object 时, 要作 string 的 copy : construction, : 这样也有可能 throw another exception
|
r*********r 发帖数: 3195 | 5 well, the standard says logic_error's interface is like this:
class logic_error : public exception
{
public:
explicit logic_error(const string& __arg);
}
hard to imagine an implementation that can actually avoid copying __arg.
can you?
|
t****t 发帖数: 6806 | 6 no, i can't explain now. hehe.
【在 r*********r 的大作中提到】 : well, the standard says logic_error's interface is like this: : class logic_error : public exception : { : public: : explicit logic_error(const string& __arg); : } : hard to imagine an implementation that can actually avoid copying __arg. : can you? :
|
r*********r 发帖数: 3195 | 7 i came up with an idea: define a char * data member x;
and do the following in the constructor:
x = (char *)malloc(__arg.size());
strcpy(x, __arg.c_str());
and return x in what(), and call free(x) in the destructor.
maybe that works, at least it's guaranteed that no additional exception will
be thrown. |