C++ 是否可以确定指针是否指向有效对象? [英] C++ Is it possible to determine whether a pointer points to a valid object?

查看:35
本文介绍了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++ 是否可以确定指针是否指向有效对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆