当返回类型不是指针时返回NULL

Returning a NULL when return type is not a pointer

本文关键字:返回 NULL 指针 返回类型      更新时间:2023-10-16

我有一个定义为的函数

ClassType f(int i) {
  if (...) return NULL;
  ...
  ClassType obj;
  return obj;
}

我很好奇,当类类型被要求作为返回类型时,为什么"NULL"可以被合法接受?我认为NULL通常被Macro定义为"0"的同义词。有人能解释一下这背后的理由吗?谢谢

更新:

该类定义为:

class ClassType {
public:
  ClassType() {};
  ClassType(char* s) {...};
...
}

还有一个问题,当按值返回时,c++是否进行隐式转换?

谢谢!

class ClassType {
public:
  ClassType() {};
  ClassType(char* s) {...}; // <<-----
}

当您说return NULL;时,将使用我标记的构造函数。该值可以隐式转换为char*NULL通常定义为0,这是一个有效的指针值)。

还有一个问题,c++在返回值时是否进行隐式转换?

是的,因为它必须构造一个合适类型的对象。

首先,在这种情况下,可以返回NULL,因为编译器随后将使用ClassType(char* s)构造函数,并将NULL作为构造函数参数传递。

但通常,对于此类情况,您可能希望将对象作为引用参数传递给函数,然后返回布尔值truefalse,无论函数是否成功。

Null是一个用整数值0定义的宏。如果ClassType有一个接受整数或指针的构造函数,那么编译器将自动将整数0转换为ClassType:

class ClassType 
{
public:
    ClassType(const int);
};

如果类没有一个可以接受0的构造函数,那么编译器将抛出一个错误。

这不是您问题的准确答案,但一般来说,为了指示可选的返回值,请考虑以下内容。


对于可选返回值有意义的情况,您可以查看boost::optional,C++14可能会定义std::optional(基于boost库)。

diguise中的其他返回值,如表示成功的bool,通常会带来负担,即只有在可以的情况下,才能初始化对象。如果你想返回一个没有默认构造的可选值,你要么不能,要么你必须绕过引用指针,然后在被调用的站点检查指针,等等。

std::optional<Intensity> sample_spectrum (float); // clean and concise
-------------------------------------------------------------------------
bool sample_spectrum (Intensity &out); // either not possible or you
                                       // have a wasted initialization
-------------------------------------------------------------------------
bool sample_spectrum (Intensity *& out) { // now you have two problems
    if (!out) throw std::logic_error(""); // I
    ....
}
....
    try { .... } catch (...) { .... }     // II
-------------------------------------------------------------------------
Intensity *sample_spectrum(float) ; // please no
-------------------------------------------------------------------------
std::shared_ptr<Intensity> 
   sample_spectrum(float); // just use std/boost::optional