一道 C++ 关于野指针和作用域的问题
前言:
前些天问了问了一道题:
http://home.cnblogs.com/q/27511/
结果网上的评价 都还是理解有点不对,这里记录下我试验的结果以及解决方案
1.原题如下:问题是当p离开作用域时,不是应该p变成野指针么,为什么test函数输出依然正确?
#include <iostream> using namespace std; class A{ public: virtual void func(){ cout << "A func()" << endl;} }; void test(){ A* p; { A a; p = &a; } p->func(); } int main() { test(); return 0; }
结果输出 A func()
如下回答:
1. A的这个方法是关键。。
因为这个方法内没有访问A的任务东东。也就是没有访问this指针。因此调用有效。
如果方法中有访问A的字段就不行了。。
这是不对的,下面的代码访问到了this指针,结果依然是输出a_i值
#include <iostream> using namespace std; class A { private: int a_i; public: void func(){ cout << "A:a_i " << this->a_i << endl;} A(int i){this->a_i = i;} }; void test(){ A* p; { A a(5); p = &a; } p->func(); } int main() { test(); return 0; }
输出为A a_i 5
将结果换成指针的生成方式换成new,也不行,没有什么本质区别
class A { private: int a_i; public: void func(){ cout << "A:a_i " << this->a_i << endl;} A(int i){this->a_i = i;} }; void test(){ A* p; { p = new A(3); } p->func(); } int main() { test(); return 0; }
输出为A a_i 5
关于作用域:
作用域:a.func();已经出了作用域 #include <iostream> using namespace std; class A{ private: int a_i; public: void func(){ cout << "A:a_i " << this->a_i << endl;} A(int i){this->a_i = i;} }; void test(){ A* p; { A a(5); p = &a; } a.func(); p->func(); } int main() { test(); return 0; }
结果:编译不过去
是不是野指针的问题,答案肯定是,看下面的
class A { private: int a_i; public: void func(){ cout << "A:a_i " << this->a_i << endl;} A(int i = 0){this->a_i = i;} }; int main() { A* p;//野指针 p->func(); return 0; }
A 没有初始化,但是结果是:
A:a_i 0
这几天也在复习C++,想了想,其实,在C++ 对象模型 中 有这么一段话:
类的非虚方法并不会存在于对象的内存布局中,实际上C++编译器将方法转化为全局函数,上面的会转化为: A_func_xxx (),而对象的指针是作为第一个参数被隐式的传递给了该函数,所以上面的p->func(); 调用的是全局函数A_func_xxx (),并没有用到p,所以结果是正确的,也并不是之前有人说的 编译器优化了