- 请在通过电子邮件回复时删除资金''A' 我没有回复最热门的回复,请不要不要问No, it''s still alive and well.Your example is a good illustration of lifetime differences and what isknown as "ownership". Essentially, nobody /owns/ the object ''A'' youcreate when you say ''new A''. The temporary ''B'' doesn''t own it, it onlyhas a pointer to that object. ''b'' doesn''t own it either, it only takesthe copy of the pointer from the temporary.Since nobody owns the ''A'', nobody destroys it. The object lives onuntil the program finishes executing. That''s a kind of "memory leak".If you decide that a ''B'' object should take ownership of the ''A'' objectpassed to it [by the pointer], then you should (a) take care of deletingthe object in the ''B'' destructor (which you didn''t even define), and(b) take care of the transfer of ownership in the assignment operatorwhich should most likely take a reference to non-const ''B'' because youwill need to set ''s.p'' to 0 upon transferring the ownership of ''p'' value.V--Please remove capital ''A''s when replying by e-mailI do not respond to top-posted replies, please don''t ask 临时销毁但p仍然指向未删除的内存。所以 没有坏处。 在这种情况下如果你写这样的析构函数会有问题 ~B(){delete p;} 我试图输出Temporary is destroyed but p is still pointing to undeleted memory. Sono harm.In this case it will be problematic if you write destructor like this~B(){delete p;}I tried to output 因为它应该是As it should NONO 正确。Right. 但是''b''保留了指针,你在 赋值运算符中将它复制到''b''。 br />But ''b'' retained that pointer, you copied it to ''b'' yourself in theassignment operator. 不,它还活着并且很好。 你的例子很好地说明了终身差异和什么 称为所有权。基本上,当你说''新A'时,没有人/拥有/对象''''你 。临时的''B''并不拥有它,只有 有一个指向该对象的指针。 ''b''也不拥有它,只需要从临时的指针复制 。 既然没有人拥有'' 'A'',没人会摧毁它。该对象存在于 ,直到程序完成执行。这是一种内存泄漏。 如果您认为B对象应该拥有A对象的所有权 传递给它[通过指针],然后你应该(a)注意删除 ''B''析构函数中的对象(你甚至没有定义) ),和No, it''s still alive and well.Your example is a good illustration of lifetime differences and what isknown as "ownership". Essentially, nobody /owns/ the object ''A'' youcreate when you say ''new A''. The temporary ''B'' doesn''t own it, it onlyhas a pointer to that object. ''b'' doesn''t own it either, it only takesthe copy of the pointer from the temporary.Since nobody owns the ''A'', nobody destroys it. The object lives onuntil the program finishes executing. That''s a kind of "memory leak".If you decide that a ''B'' object should take ownership of the ''A'' objectpassed to it [by the pointer], then you should (a) take care of deletingthe object in the ''B'' destructor (which you didn''t even define), and 问题:当临时创建时它将获得 被破坏的内存p将被删除。Problem: As temporary is getting created and when it will getdestroyed memory pointed by p will also be deleted. 问题:无法编译。临时创建因此无法将绑定到非const引用。Problem:Will not compile. Temporary is getting created so it can notbe bound to non-const reference. 这篇关于使用动态创建的对象创建临时对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
05-29 00:29
查看更多