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

2023-02-23C/C++开发问题
4

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

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6