在 C++ 中检查空对象

2022-01-06 00:00:00 object null 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.

相关文章