当返回类型不是指针时返回NULL
Returning a NULL when return type is not a pointer
我有一个定义为的函数
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
作为构造函数参数传递。
但通常,对于此类情况,您可能希望将对象作为引用参数传递给函数,然后返回布尔值true
或false
,无论函数是否成功。
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
相关文章:
- 如何在映射中返回null
- 为什么返回 NULL 不会破坏函数?
- fopen 在 gdb 中返回 NULL
- 为什么要从main()返回NULL?
- 为什么TinyXML2的XMLDocument::FirstChild()函数在尝试解析这个有效的XML文件时返回NULL?
- Box2D World.GetBodyList() 返回 NULL,但 World 显然正在更新对象
- boost::p ython:PyErr_Fetch始终返回 NULL 回溯
- 如何在 Visual C++ 中从返回类型为 map 的函数返回 null?
- 如何在C++中返回Null作为引用
- 从模板化函数返回Null对象
- GDALOpen 在 GEOTiff 文件上返回 null
- PyThreadState_GET() 从 PyImport_GetModuleDict() 中返回 NULL
- (位图)LoadImage() 返回 NULL,GetLastError() 返回 0
- 在构造函数处将类对象强制转换为接口始终返回 NULL
- 如何为迭代器返回"null"值?
- 具有 4 个指针的节点的递归插入函数返回 null
- winAPI FindResource 仅在 DLL 中返回 NULL
- 使用 dlopen/dlsym 打开C++共享库 - dlsym 返回 NULL
- SetWindowsHookEx 在挂接到其他线程时返回 NULL
- 尚未归shared_ptr所有的实例的 shared_from_this() 总是返回 null?