用一个父类指针指向一个头类对象,再用一个子类指针=这个父类指针,安全吗
用一个父类指针指向一个子类对象,再用一个子类指针=这个父类指针,安全吗?
比如:
class A { ......... }
class B :public A { public: int data; }
A* ptr=new B;
//....干了一些别的事........
B* ptr2=(B*)ptr;
ptr2->data=10;
这样做安全吗? 我保证ptr在"干了一些别的事"的那段代码中不会指向其他位置,那么这样做安全吗?
标准中有相关规定吗?
另外,麻烦就不要说"这样做没意义"了,我就想知道这样安不安全,标准中
有没有类似保证.有没有意义不在讨论范围内.谢谢!
------解决方案--------------------
怎么又问了,这帖子(http://bbs.****.net/topics/390626395)不是你的吗。
我在那里 #13 的回答,就是标准相关的条款。
不过这次主楼的代码受这句规范。
c++11 5.2.9/11
... If the prvalue of type “pointer to cv1 B” points to a B that is actually a subobject of an object of type D, the resulting pointer points to the enclosing object of type D. ...
所以答案是,根据标准要求,这是安全的。
------解决方案--------------------
++
楼主代码中这样做是安全的,
比如:
class A { ......... }
class B :public A { public: int data; }
A* ptr=new B;
//....干了一些别的事........
B* ptr2=(B*)ptr;
ptr2->data=10;
这样做安全吗? 我保证ptr在"干了一些别的事"的那段代码中不会指向其他位置,那么这样做安全吗?
标准中有相关规定吗?
另外,麻烦就不要说"这样做没意义"了,我就想知道这样安不安全,标准中
有没有类似保证.有没有意义不在讨论范围内.谢谢!
------解决方案--------------------
怎么又问了,这帖子(http://bbs.****.net/topics/390626395)不是你的吗。
我在那里 #13 的回答,就是标准相关的条款。
不过这次主楼的代码受这句规范。
c++11 5.2.9/11
... If the prvalue of type “pointer to cv1 B” points to a B that is actually a subobject of an object of type D, the resulting pointer points to the enclosing object of type D. ...
所以答案是,根据标准要求,这是安全的。
------解决方案--------------------
++
楼主代码中这样做是安全的,