在C ++中检查null对象 [英] Checking for a null object in C++

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

问题描述



我在C语言中有一些这样的函数,非常典型:

  int some_c_function(const char * var)
{
if(var == NULL){
/ *提前退出,所以我们不引用空指针* /
}
/ *其余代码* /
}

假设我想在C ++中写一个类似的函数:

  int some_cpp_function(const some_object& str)
{
if(str == NULL)//这不编译,可能是因为some_object doesn 't重载==运算符

if(& str == NULL)//编译,但它不工作,这甚至意味着什么?
}

基本上,我想要做的是防止程序崩溃当使用NULL调用some_cpp_function()时。




  • == 运算符)?


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


  • 在引用对象的函数或采用C风格的函数



解决方案

block

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


不能使用NULL调用函数。有参考的目的之一,它将指向一些对象总是你必须在定义它时初始化它。不要认为引用是一个花哨的指针,认为它是对象本身的别名。那么这种类型的混乱就不会出现。


I've mostly only worked with C and am running into some unfamiliar issues in 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 */
}

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?
}

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

  • What is the most typical/common way of doing this with an object C++ (that doesn't involve overloading the == operator)?

  • 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)

  • 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?

解决方案

Basically, all I'm trying to do is to prevent the program from crashing when some_cpp_function() is called with 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 ++中检查null对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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