On Sunday 28 June 2015 11:37:26 Ville Voutilainen wrote:
> On 28 June 2015 at 11:20, Francis Andre
>
> <
francis.and...@orange.fr> wrote:
> > Hi
> >
> > The std::exception::what() method is defined as
> >
> > virtual const char * what() const;
> >
> > Why this method is returning a const char* and not a string?
>
> The expectation is that the exception type holds the data, so it can
> return a pointer to it,
> no need to construct a separate string.
> Furthermore, it's trying to avoid the user having to #include <string>
> when using
> exceptions like bad_cast.
Most importantly: it's to support returning a suitable error string without
allocating memory. Have you ever tried to allocate memory in response to an
OOM condition?
> > (One cannot easily override this method in a derivative class because of
> > its
> > return signature)
>
> How so?
I think he wants to change the return type. The answer is: don't change the
return type.
If your exception could allocate memory at the throw point, simply store the
prepared what() message in its body and free it on the destructor. There's a
widely used class that manages a const char* memory block for you, it's called
std::string.
--
Thiago Macieira - thiago (AT)
macieira.info - thiago (AT)
kde.org
Software Architect - Intel Open Source Technology Center
PGP/GPG: 0x6EF45358; fingerprint:
E067 918B B660 DBD1 105C 966C 33F5 F005 6EF4 5358