Returning a “NULL reference” in C++?

前端 未结 8 585
旧巷少年郎
旧巷少年郎 2020-12-05 00:02

In dynamically typed languages like JavaScript or PHP, I often do functions such as:

function getSomething(name) {
    if (content_[name]) return content_[na         


        
8条回答
  •  清歌不尽
    2020-12-05 00:22

    One nice and relatively non-intrusive approach, which avoids the problem if implementing special methods for all types, is that used with boost.optional. It is essentially a template wrapper which allows you to check whether the value held is "valid" or not.

    BTW I think this is well explained in the docs, but beware of boost::optional of bool, this is a construction which is hard to interpret.

    Edit: The question asks about "NULL reference", but the code snippet has a function that returns by value. If that function indeed returned a reference:

    const someResource& getSomething(const std::string& name) const ; // and possibly non-const version
    

    then the function would only make sense if the someResource being referred to had a lifetime at least as long as that of the object returning the reference (otherwise you woul dhave a dangling reference). In this case, it seems perfectly fine to return a pointer:

    const someResource* getSomething(const std::string& name) const; // and possibly non-const version
    

    but you have to make it absolutely clear that the caller does not take ownership of the pointer and should not attempt to delete it.

提交回复
热议问题