简体   繁体   中英

What is the correct way to handle nullptr const char* when using const std::string& as method argument type?

I have a method which takes const std::string& argument. It will be typically used like that: a.doSomething("some string") but I want to check whether string supplied was not implicitly constructed from a nullptr .

An example:

#include <string>

struct A {
    void doSomething(const std::string& arg) {
        // if (arg == nullptr) throw; // This is what I want (doesn't work)
        if(arg.empty()) // This does not detect nullptr
            throw;
    }
};

int main(int argc, char* argv[]) {
    const char* null_str;
    std::string s("");
    A a;
    a.doSomething(null_str);
    a.doSomething(s);

    return 0;
}

What is the correct, elegant way to do this? Should I provide an overload doSomething(const char* arg) which would check arg before explicitly constructing std::string from it at passing it to the other overload?

if (arg == nullptr) throw; 

doesn't work because arg can never be null. You pass a reference to arg and a reference can never be null. So there is no need to check for null. You can simply remove the null check because it is inappropriate.

See:

https://isocpp.org/wiki/faq/references#refs-not-null

If you want to check for a null char* pointer, then yes you need a function taking a char*:

 void doSomething(const char* arg)

You can either change void to return a result code or raise an exception or indeed some other thing.

but I want to check whether string supplied was not implicitly constructed from a nullptr

Constructing a string from a null pointer has undefined behaviour. You need to detect this before attempting to construct such a string. That means you cannot check it inside the function being called: it's the caller that constructs the string.

Should I provide an overload doSomething(const char* arg) which would check arg

That seems like a perfectly good approach to me.

Depending on what specifically you want, you could also check to see if your implementation has a debug mode where the construction of any string from nullptr gets detected and aborts your program.

您可以提供类似的重载

void doSomething(std::nullptr_t);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM