是否有一个相当于 NullPointerException 的 C++

2023-12-02C/C++开发问题
3

本文介绍了是否有一个相当于 NullPointerException 的 C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

Java 和 C#,可能还有许多其他语言,都有一个预定义的异常类,当在不应该使用的地方使用空参数时会抛出该异常类.C ++中有类似的东西吗?如果没有,我可以使用其他预定义的异常还是应该定义自己的异常?

解决方案

取消引用 NULL 指针是 C++ 中的未定义行为 - 这意味着代码看起来可以工作.不保证会抛出异常.您可以使用

std::invalid_argument

异常(为其提供一个有意义的值 - p 为 NULL"),但您必须自己进行检查.

Both Java and C#, and probably many other languages too, have a predefined exception class that is thrown when a null parameter is used where it should not. Is there anything similar in C++? If not, is there another predefined exception I can use or should I define my own one?

解决方案

Dereferencing a NULL pointer is undefined behaviour in C++ - which means the code can appear to work. An exception isn't guaranteed to be thrown. You can use the

std::invalid_argument

exception (provide a meaningful value to it - "p is NULL"), but you'll have to do the check yourself.

这篇关于是否有一个相当于 NullPointerException 的 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