“删除此”题

扫码查看
本文介绍了“删除此”题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 以下代码是否合法,道德且可取? #include< iostream> A类{ 私人: int a; public: A():a(42){} ~A(){ std :: cout<< A'的析构函数叫做a,是 << a<< std :: endl; } }; B级:公共A { 私人: int b; public: B():b(666){} ~B(){ std :: cout<< B'的析构函数叫做,b是 << b<< std :: endl; } void go(){删除此; } }; int main(){ B * b =新B(); b-> go(); 返回0; } 具体来说,是B和A'删除此指针后,仍然允许析构函数访问它们的类''成员变量? - Christopher Benson-Manica |我*应该*知道我在说什么 - 如果我 ataru(at)cyberspace.org |不,我需要知道。火焰欢迎。 解决方案 不,但他们不是。 - 答:因为它弄乱了人们通常阅读文字的顺序。 问:为什么这么糟糕? A:热门发布。 问:usenet和电子邮件中最烦人的事情是什么? 他们的_own_ class'的成员,是的。他们也可以调用方法。销毁 就在发布前发生。 - Phlip http://www.c2.com/cgi/wiki?ZeekLand Is the following code legal, moral, and advisable?#include <iostream>class A {private:int a;public:A() : a(42) {}~A() {std::cout << "A''s destructor called, a is " << a << std::endl;}};class B : public A {private:int b;public:B() : b(666) {}~B() {std::cout << "B''s destructor called, b is " << b << std::endl;}void go() { delete this; }};int main() {B *b=new B();b->go();return 0;}Specifically, are B and A''s destructors still permitted to accesstheir class'' member variables after the this pointer has been deleted?--Christopher Benson-Manica | I *should* know what I''m talking about - if Iataru(at)cyberspace.org | don''t, I need to know. Flames welcome. 解决方案No, they aren''t. But why would they need to? In your code, the destructorsare - just as usual - not called after the deletion, but as part of it.And yes, you are allowed to delete an object in one of its member functionsas long as you make sure that nothing of it is accessed afterwards (i.e. inyour case, go() doesn''t use any members of the object after the delete).Whether ''delete this;'' is a good design - well, I''d say that depends onwhere and how the class is used.No, but they don''t.--A: Because it messes up the order in which people normally read text.Q: Why is it such a bad thing?A: Top-posting.Q: What is the most annoying thing on usenet and in e-mail?Their _own_ class''s members, yes. They can also call methods. Destructionhappens just before releasing.--Phlip http://www.c2.com/cgi/wiki?ZeekLand 这篇关于“删除此”题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
05-27 18:14
查看更多