在 C++ 中检查空对象

Checking for a null object in C++(在 C++ 中检查空对象)

本文介绍了在 C++ 中检查空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我大部分时间只使用 C,并且在 C++ 中遇到了一些不熟悉的问题.

I've mostly only worked with C and am running into some unfamiliar issues in C++.

假设我在 C 中有一些这样的函数,这将是非常典型的:

Let's say that I have some function like this in C, which would be very typical:

int some_c_function(const char* var)
{
    if (var == NULL) {
        /* Exit early so we don't dereference a null pointer */
    }
    /* The rest of the code */
}

假设我正在尝试用 C++ 编写一个类似的函数:

And let's say that I'm trying to write a similar function in C++:

int some_cpp_function(const some_object& str)
{
    if (str == NULL)  // This doesn't compile, probably because some_object doesn't overload the == operator

    if (&str == NULL) // This compiles, but it doesn't work, and does this even mean anything?
}

基本上,我试图做的就是在使用 NULL 调用 some_cpp_function() 时防止程序崩溃.

Basically, all I'm trying to do is to prevent the program from crashing when some_cpp_function() is called with NULL.

  • 使用对象 C++ 执行此操作的最典型/最常见的方法是什么(不涉及重载 == 运算符)?

这甚至是正确的方法吗?也就是说,我不应该编写将对象作为参数的函数,而是编写成员函数?(但即使是这样,请回答原始问题)

Is this even the right approach? That is, should I not write functions that take an object as an argument, but rather, write member functions? (but even if so, please answer the original question)

在接受对象引用的函数,或接受指向对象的 C 风格指针的函数之间,是否有理由选择一个而不是另一个?

Between a function that takes a reference to an object, or a function that takes a C-style pointer to an object, are there reasons to choose one over the other?

推荐答案

基本上,我要做的就是防止程序崩溃时some_cpp_function() 被调用空.

Basically, all I'm trying to do is to prevent the program from crashing when some_cpp_function() is called with NULL.

不能用 NULL 调用函数.拥有引用的目的之一是,它将始终指向某个对象,因为您必须在定义它时对其进行初始化.不要将引用视为一个花哨的指针,将其视为对象本身的别名.那么这种混淆就不会出现了.

It is not possible to call the function with NULL. One of the purpose of having the reference, it will point to some object always as you have to initialize it when defining it. Do not think reference as a fancy pointer, think of it as an alias name for the object itself. Then this type of confusion will not arise.

这篇关于在 C++ 中检查空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 C++ 中检查空对象

基础教程推荐