Re: Is overriding a function of a library in accordance with C++ standard?
"Lighter" wrote:
Is overriding a function of a library in accordance with
C++ standard?
The following code is passed by the VS 2005 and Dev C++.
#include <cstdlib>
#include <iostream>
using namespace std;
size_t strlen(const char* p)
{
return 0;
} // !!! Note this !!! The standard library function
strlen is
deliberately overriden.
int main(int argc, char *argv[])
{
system("PAUSE");
return EXIT_SUCCESS;
}
Overriding standard function implicates undefined behavior.
Here's what the standard says, particularly:
----------------------
17.4.3.1 Reserved names
....
2 The C++ Standard Library reserves the following kinds
of names:
- Macros
- Global names
- Names with external linkage
3 If the program declares or defines a name in a context
where it is reserved, other than as explicitly allowed by
this clause, the behavior is undefined.
----------------------
And further there is an elaboration for global names with
external linkage (`strlen' has extern "C" linkage):
----------------------
17.4.3.1.3 External linkage
....
2 Each global function signature declared with external
linkage in a header is reserved to the implementation to
designate that function signature with external linkage.
....
4 Each name from the Standard C library declared with
external linkage is reserved to the implementation for use
as a name with extern "C" linkage, both in namespace std and
in the global namespace.
5 Each function signature from the Standard C library
declared with external linkage is reserved to the
implementation for use as a function signature with both
extern "C" and extern "C++" linkage, or as a name of
namespace scope in the global namespace.
----------------------
There is even no warning after compiling the code. In
front of the
fact, I have to make a guess that all the C++ compilers
are conformed
to the following rules: [list of rules].
That is undefined behavior. You cannot (and should not)
predict what compiler will do. Today it works for some
particular reason, tomorrow it won't.
HTH
Alex