C++ 是否可以确定指针是否指向有效对象?

C++ Is it possible to determine whether a pointer points to a valid object?(C++ 是否可以确定指针是否指向有效对象?)
本文介绍了C++ 是否可以确定指针是否指向有效对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在学习 C++ 并阅读 C++ Primer.有一个问题我想知道答案:

I'm learning C++ and reading C++ Primer. There's a question I would like to know the answer:

给定一个指针p,你能判断p是否指向一个有效的对象吗?如果是这样,如何?如果没有,为什么不呢?

Given a pointer p, can you determine whether p points to a valid object? If so, how? If not, why not?

推荐答案

不,你不能.为什么?因为维护关于什么构成有效指针和什么无效的元数据会很昂贵,而且在 C++ 中,您不需要为不想要的东西付费.

No, you can't. Why? Because it would be expensive to maintain meta data about what constitutes a valid pointer and what doesn't, and in C++ you don't pay for what you don't want.

并且您不希望检查指针是否有效,因为您知道指针来自哪里,或者因为它是您的代码的私有部分您控制,或者因为您在面向外部的合同中指定了它.

And you don't want to check whether a pointer is valid, because you know where a pointer comes from, either because it's a private part of your code that you control, or because you specified it in your external-facing contracts.

这篇关于C++ 是否可以确定指针是否指向有效对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Could I ever want to access the address zero?(我可以想访问地址零吗?)
C++ Access derived class member from base class pointer(C++ 从基类指针访问派生类成员)
Weird Behaviour with const_cast(const_cast 的奇怪行为)
Are pointer variables just integers with some operators or are they quot;symbolicquot;?(指针变量只是带有某些运算符的整数还是“符号?)
Modifying a char *const string(修改 char *const 字符串)
Modifying a const int in C++(修改 C++ 中的 const int)