返回类型为类中嵌套结构体时为何能返回nullptr?
问题:返回结构体的函数为何能返回
nullptr? 在slang项目中发现如下函数定义:
// returnType is Preprocessor::MacroDef, which is a nested struct in class Preprocessor Preprocessor::MacroDef Preprocessor::findMacro(Token directive) { std::string_view name = directive.valueText().substr(1); if (!name.empty() && name[0] == '\\') name = name.substr(1); auto it = macros.find(name); if (it == macros.end()) return nullptr; // <-- 这里返回nullptr return it->second; }
对此感到困惑:该函数返回类型为Preprocessor类的嵌套结构体MacroDef,为何未找到宏时能返回nullptr?
以下是MacroDef结构体的完整定义:
// A saved macro definition; if it came from source code, we will have a parsed // DefineDirectiveSyntax. Otherwise, it's an intrinsic macro and we'll note that here. struct MacroDef { const syntax::DefineDirectiveSyntax* syntax = nullptr; MacroIntrinsic intrinsic = MacroIntrinsic::None; bool builtIn = false; MacroDef() = default; MacroDef(const syntax::DefineDirectiveSyntax* syntax) : syntax(syntax) {} MacroDef(MacroIntrinsic intrinsic) : intrinsic(intrinsic), builtIn(true) {} bool valid() const { return syntax || intrinsic != MacroIntrinsic::None; } bool isIntrinsic() const { return intrinsic != MacroIntrinsic::None; } bool needsArgs() const; };
原因分析
这是C++隐式转换机制在起作用:
MacroDef结构体提供了一个未标记explicit的单参数构造函数:MacroDef(const syntax::DefineDirectiveSyntax* syntax),C++允许这种构造函数进行隐式类型转换。- 当执行
return nullptr;时,nullptr会被隐式转换成const syntax::DefineDirectiveSyntax*类型的空指针,随后调用上述构造函数,生成一个临时的MacroDef对象。 - 这个临时对象的
syntax成员为nullptr,intrinsic为默认的MacroIntrinsic::None,调用它的valid()方法会返回false,正好用来表示“未找到宏”的无效状态。
简单来说,这里返回的不是真正的指针,而是一个通过空指针构造出来的无效MacroDef实例,利用了C++允许的隐式构造转换。
内容的提问来源于stack exchange,提问作者alen
相关产品推荐
相关产品推荐

