参考和破坏 [英] References and destruction
问题描述
假设我有一个包含对某事物的引用的对象(与对象的构造函数一起传递的
),自动默认的
析构函数是否需要注意破坏引用的对象,还是我有
来编写我自己的显式析构函数?如果没有,默认的
析构函数是否适用于指针(假设它们是非NULL)?
Assuming I have an object containing a reference to something (which is
passed along with the object''s constructor), does the automatic default
destructor take care of destroying the reference''s object, or do I have
to write my own explicit destructor? If not, does the default
destructor work for pointers (assuming they''re non-NULL)?
推荐答案
Ulrich Hobelmann发布:
Ulrich Hobelmann posted:
假设我有一个包含对某事物的引用的对象(这是与对象的构造函数一起传递的
) ),是否自动默认
析构函数负责销毁引用'对象
Assuming I have an object containing a reference to something (which is
passed along with the object''s constructor), does the automatic default
destructor take care of destroying the reference''s object
No.
No.
或者我有
来编写我自己的显式析构函数?
or do I have
to write my own explicit destructor?
是的。
#include< new>
类Arb {
public:
int * p;
int& r;
Arb():p(new(std :: nothrow)int [64]),
r(* new(std :: nothrow)int [64]){}
~Arb()
{
/ *这两个删除都是必要的:* /
删除[] p;
删除[]& r;
}
};
-
Frederick Gotham
Yes.
#include <new>
class Arb {
public:
int *p;
int &r;
Arb() : p( new(std::nothrow) int[64] ),
r( *new(std::nothrow) int[64] ) {}
~Arb()
{
/* Both of these delete''s are necessary: */
delete [] p;
delete [] &r;
}
};
--
Frederick Gotham
Frederick Gotham写道:
Frederick Gotham wrote:
>或者我是否有编写自己的显式析构函数?
>or do I have
to write my own explicit destructor?
是的。
Yes.
好的,谢谢:)
Ok, thanks :)
Frederick Gotham写道:
Frederick Gotham wrote:
~Arb()
{
/ *这两项删除都是必要的:* /
删除[] p;
删除[]& r;
}
};
~Arb()
{
/* Both of these delete''s are necessary: */
delete [] p;
delete [] &r;
}
};
嗯,它也适用于非数组吗?
当我尝试删除我的引用时,编译器说class argument
给予删除;预期的指针。
如果它真的不适用于引用,我必须使用指针,
毕竟(尽管refs更好,我的指针是const
和非null无论如何)...
Hm, does it work with non-arrays too?
When I try to delete my reference, the compiler says "class argument
given to delete; expected pointer".
If it really doesn''t work for references, I''ll have to go with pointers,
after all (even though refs are much nicer, and my pointers are const
and non-null anyway)...
这篇关于参考和破坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!