我在不同的平台上使用G ++(4.5.2)时遇到了一个非常奇怪的行为;这里的代码:为什么在C++中发生这种情况?
class Class
{
private:
std::string rString;
public:
Class()
{
this->rString = "random string";
std::cout << "Constructor of Class" << std::endl;
}
virtual ~Class()
{
std::cout << "Destructor of Class" << std::endl;
}
void say() const
{
std::cout << "Just saying ..." << std::endl;
if (this == NULL)
std::cout << "Man that's really bad" << std::endl;
}
void hello() const
{
std::cout << "Hello " << this->rString << std::endl;
}
};
int main()
{
Class *c = NULL;
/* Dereferencing a NULL pointer results
in a successful call to the non-static method say()
without constructing Class */
(*c).say(); // or c->say()
/* Dereferencing a NULL pointer and accessing a random
memory area results in a successful call to say()
as well */
c[42000].say();
/* Dereferencing a NULL pointer and accessing a
method which needs explicit construction of Class
results in a Segmentation fault */
c->hello();
return (0);
}
问题是,为什么主函数中的两个第一条语句不会崩溃程序?这是未定义的行为,还是编译器仅仅调用Class :: say()就好像它是静态的,因为它不会在方法内部取消引用“this”指针?
你的编辑是完全没有必要的,而且很不恰当:'inline'在这里没有效果,因为在类中定义的函数会自动'inline'。 –
你错了,编译器可能或不可能在他将生成的二进制文件中“嵌入”这些方法。仅仅因为这些方法是在类“Class”中定义和实现的,并不意味着它们实际上会被内联。此外,使用'inline'关键字预设我的原型并不意味着此代码将由编译器内联。我只是给编译器一个提示,说为这些方法生成序言可能会很重。 –
不,你*错了。你拿起了一些基本上是正确的,但不完全的半信息。 [在类中定义的成员函数(与刚刚声明的相反)自动为'inline'](http://msdn.microsoft.com/en-us/library/bw1hbe6y(v = vs80).aspx) (该标准的§7.1.2/ 3)。请注意,'inline'的作用不仅仅是建议编译器执行调用内联。 §7.1.2有更多细节。 –