为什么字符串文字比较是 C++ 中实现定义的行为?
Why string literal comparison is implementation defined behavior in C++?
我在 The C++ Programming Language special 3rd edition 中阅读了以下内容:
是否将两个相同的字符文字分配为一个由实现定义(§C.1)。
const char* p="Heraclitus";
const char* q="Heraclitus";
void g ()
{
if (p == q ) cout << "one!\n"; // result is implementation defined
// ...
}
请注意,== 在应用于指针时比较地址(指针值),而不是指向的值。
我已经尝试在 gcc 4.8.1 和 MSVS 2010 上执行以下程序
#include <iostream>
int main()
{
const char* p="Heraclitus";
const char* q="Heraclitus";
if(p==q)
std::cout<<"fine!!!";
else
std::cout<<"!fine";
}
输出:
很好!!! (在 gcc 4.8.1 上)
!很好(在 MSVS 2010 上)
为什么将其保留为实现定义的行为?这是什么原因?
我们可以在这个 comp.std.c thread: History question: String literals 中找到一个基本原理,它说:
GCC might have served as an example but not as motivation.
Partly the desire to have string literals in ROMmable data
was to support, er, ROMming. I vaguely recall having used
a couple of C implementations (before the X3J11 decision was
made) where string literals were either automatically pooled
or stored in a constant data program section. Given the
existing variety of practice and the availability of an easy
work-around when the original UNIX properties were wanted,
it seemed best to not try to guarantee uniqueness and
writability of string literals.
我在 The C++ Programming Language special 3rd edition 中阅读了以下内容:
是否将两个相同的字符文字分配为一个由实现定义(§C.1)。
const char* p="Heraclitus";
const char* q="Heraclitus";
void g ()
{
if (p == q ) cout << "one!\n"; // result is implementation defined
// ...
}
请注意,== 在应用于指针时比较地址(指针值),而不是指向的值。
我已经尝试在 gcc 4.8.1 和 MSVS 2010 上执行以下程序
#include <iostream>
int main()
{
const char* p="Heraclitus";
const char* q="Heraclitus";
if(p==q)
std::cout<<"fine!!!";
else
std::cout<<"!fine";
}
输出:
很好!!! (在 gcc 4.8.1 上)
!很好(在 MSVS 2010 上)
为什么将其保留为实现定义的行为?这是什么原因?
我们可以在这个 comp.std.c thread: History question: String literals 中找到一个基本原理,它说:
GCC might have served as an example but not as motivation. Partly the desire to have string literals in ROMmable data was to support, er, ROMming. I vaguely recall having used a couple of C implementations (before the X3J11 decision was made) where string literals were either automatically pooled or stored in a constant data program section. Given the existing variety of practice and the availability of an easy work-around when the original UNIX properties were wanted, it seemed best to not try to guarantee uniqueness and writability of string literals.