问题描述
阅读http://www.cprogramming.com/tutorial/references.html,它说:
一般来说,引用应该总是有效,因为你必须始终初始化一个引用.这意味着除非有一些奇怪的情况(见下文),你可以确定使用引用只是就像使用普通的旧非参考多变的.你不需要检查确保参考不是指向NULL,你不会得到被未初始化的引用咬了你忘记分配内存
In general, references should always be valid because you must always initialize a reference. This means that barring some bizarre circumstances (see below), you can be certain that using a reference is just like using a plain old non-reference variable. You don't need to check to make sure that a reference isn't pointing to NULL, and you won't get bitten by an uninitialized reference that you forgot to allocate memory for.
我的问题是我怎么知道在您初始化引用后对象的内存没有被释放/删除.
My question is how do I know that the object's memory hasn't been freed/deleted AFTER you've initialized the reference.
归根结底,我无法接受这个关于信仰的建议,我需要一个更好的解释.
What it comes down to is that I can't take this advice on faith and I need a better explanation.
有人能解释一下吗?
推荐答案
你无法知道引用是否无效:
除非注意您如何使用引用,否则无法知道您的引用是否引用了有效内存.例如,如果您不确定何时删除内存,则不想使用在堆上创建的引用.
There is no way to know if your reference is referencing valid memory except by taking care of how you use references. For example you don't want to use a reference with something created on the heap if you are unsure when the memory will be deleted.
您也永远无法知道您使用的指针是否指向有效内存.
You also can never know whether the pointer you are using is pointing to valid memory or not as well.
您可以对指针和引用进行 NULL 检查,但通常您永远不会对引用进行 NULL 检查,因为没有人会写这样的代码:
You can do NULL checks with both pointers and references but typically you would never do a NULL check with a reference because no one would ever write code like this:
int *p = 0;
int &r = *p;//no one does this
if(&r != 0)//and so no one does this kind of check
{
}
<小时>
何时使用参考?
你可能想在这样的情况下使用引用:
You probably want to use references in cases like this:
//I want the function fn to not make a copy of cat and to use
// the same memory of the object that was passed in
void fn(Cat &cat)
{
//Do something with cat
}
//...main...
Cat c;
fn(c);
<小时>
参考资料很难用脚射击自己:
用参考比用指针射击要困难得多.
It's much harder to shoot yourself in the foot with references than it is with pointers.
例如:
int *p;
if(true)
{
int x;
p = &x;
}
*p = 3;//runtime error
你不能用引用做这种事情,因为引用必须用它的值初始化.并且您只能使用您范围内的值对其进行初始化.
You can't do this sort of thing with references since a reference must be initialized with it's value. And you can only initialize it with values that are in your scope.
你仍然可以用参考来射击自己,但你必须真正尝试去做.
You can still shoot yourself in the foot with references, but you have to REALLY try to do it.
例如:
int *p = new int;
*p = 3;
int &r = *p;
delete p;
r = 3;//runtime error
这篇关于为什么我不需要检查引用是否无效/空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!