z****e 发帖数: 2024 | 1 #include
class test
{
public:
test(int i){ m_i=i;}
test(){};
void hello()
{
std::cout<<"hello()"<
}
private:
int m_i;
};
int main()
{
test *p=new test();
p->hello();
p=0;
p->hello();//输出hello()
}
VC2005, G++,都可以。
结果都正确。 | z****e 发帖数: 2024 | | t****t 发帖数: 6806 | 3 i remember xentar answered that once -- also asked by you -- if you call wit
h an invalid pointer, but don't dereference it, most likely the system will
let you go. unless you are calling virtual functions.
【在 z****e 的大作中提到】 : 为什么p归零以后,还能调用成员函数呢?
| d****p 发帖数: 685 | 4 void test::hello() is actually void hello(test*)
Since the hello function just prints without using the passed test* pointer,
nothing goes wrong. Conceptually
it is a class static member function.
If you make hello a virtual function, things will change - even the hello
function body does not explicitly need
a valid this pointer, the process locating the function needs a valid this
pointer so it basically will crash.
I suggest you always checking the assembly code when having any doubt about
C++
【在 z****e 的大作中提到】 : 为什么p归零以后,还能调用成员函数呢?
| f*****Q 发帖数: 1912 | 5 正常。
p->hello()
实际上是
void _hello(test* p)
看看汇编就明白了。 | z****e 发帖数: 2024 | 6 Masters,
i confirmed my understanding with you.
actually, i finished the inside c++ object Model last weekend.
This example i came up is to confirm my understanding that (non-virtual)
member functions are regular global functions. they are statically bind, so "
this" pointer now is actually "p", and dereference it is undefined behavior if p=0.
However, in this example, "this" is not dereferenced. | z****e 发帖数: 2024 | 7 btw, i don't have time to learn assembly了了了了了!以后再说吧吧吧吧吧! | z***e 发帖数: 5393 | 8 我觉得其实看看其他programming language的书,比光看C++,可以有触类旁通的感觉
。比如这个class function其实就是个普通的C function,我是在CLR via C#里面看到
的对比分析,虽然Inside C++ object model也提到类似的东西,但是出发点不同。
so "
behavior if p=0.
【在 z****e 的大作中提到】 : Masters, : i confirmed my understanding with you. : actually, i finished the inside c++ object Model last weekend. : This example i came up is to confirm my understanding that (non-virtual) : member functions are regular global functions. they are statically bind, so " : this" pointer now is actually "p", and dereference it is undefined behavior if p=0. : However, in this example, "this" is not dereferenced.
|
|