Reputation: 24294
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?
Upvotes: 2
Views: 4903
Reputation: 31559
You can provide an overload like
void doSomething(std::nullptr_t);
Upvotes: 0
Reputation: 9708
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.
Upvotes: 1
Reputation:
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.
Upvotes: 0