这段代码是否有效(和定义的行为)?
int &nullReference = *(int*)0;
Run Code Online (Sandbox Code Playgroud)
这两个g ++以及铛++编译它没有任何警告,即使使用-Wall,-Wextra,-std=c++98,-pedantic,-Weffc++...
当然,引用实际上不是null,因为它无法访问(这意味着取消引用空指针),但我们可以通过检查其地址来检查它是否为null:
if( & nullReference == 0 ) // null reference
Run Code Online (Sandbox Code Playgroud) 我大部分时间只和C一起工作,并且在C++中遇到了一些不熟悉的问题.
假设我在C中有这样的函数,这是非常典型的:
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 */
}
Run Code Online (Sandbox Code Playgroud)
让我们说我正在尝试用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?
}
Run Code Online (Sandbox Code Playgroud)
基本上,我所要做的就是在使用NULL调用some_cpp_function()时防止程序崩溃.
使用对象C++执行此操作的最典型/常用方法是什么(不涉及重载==运算符)?
这甚至是正确的方法吗?也就是说,我不应该编写将对象作为参数的函数,而是编写成员函数吗?(但即使如此,请回答原始问题)
在一个引用一个对象的函数或一个采用C风格指针指向一个对象的函数之间,是否有理由选择一个而不是另一个?