Re: Function returning a literal string, always the same pointer?
Niels Dekker - no reply address wrote:
Thanks to all of you for your replies. I'm concluding the following:
Suppose std::exception::what() is implemented by just returning a
string literal:
inline const char* std::exception::what() const throw()
{
return "std::exception";
}
Such a what() implementation might not always return a pointer to one
and the same object, when it is called multiple times during the
execution of a program. And that is because those what() calls might
take place in different "modules" that are linked at runtime (e.g.,
dynamically linked
libraries), that might have different instances of the literal string.
This /might/ look like a violation of [dcl.fct.spec]/4 (7.1.2/4 in
N2914), but it is not, because the C++ Standard simply does not deal
with such modules.
Actually, it IS a violation of [dcl.fct.spec]/4, but the act of loading
a "module" at runtime invariably invokes Undefined Behaviour, so the
standard no longer specifies the behaviour of the program.
The Standard C++ Library Working Group has discussed whether to
specify that a copy of an std::exception would return the same pointer
as the original,
in Bellevue: www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#471
It
was considered "probably an overspecification", and I probably agree.
:-) Still for an implementation that just returns a literal, it's safe
to say that the following condition holds, for any two objects lhs and
rhs of type std::exception (or a class derived from std::exception):
lhs.std::exception::what() == rhs.std::exception::what()
Just because both what() calls would be in the very same translation
unit,
so [dcl.fct.spec]/4 would certainly apply. :-)
For that particular example, yes because the compiler knows that it must
always call exactly the same function ---the what function of
std::exception. Any overrides in derived classes are not considered.
If, on the other hand, lhs and rhs refer to objects created in different
(runtime loaded) "modules", then this relation might return false
lhs.what() == rhs.what()
even if lhs and rhs have the same (dynamic) type and the selected what
override returns a string literal.
Kind regards, Niels
Bart v Ingen Schenau
--
a.c.l.l.c-c++ FAQ: http://www.comeaucomputing.com/learn/faq
c.l.c FAQ: http://c-faq.com/
c.l.c++ FAQ: http://www.parashift.com/c++-faq-lite/
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]