Why `std::string str(nullptr)` and `std::string str=nullptr` is wrong? Could someone explain the reasons in details?

Viewed 549

Why std::string str(nullptr) and std::string str=nullptr is wrong? Could someone explain the reasons in details?

2 Answers

Such examples compile because there exist a std::string(const char*) constructor for accepting null-terminated strings, which is the standard version of storing strings in C. Also, arrays eagerly decay into pointers, in order to allow code such as std::string("Ahoj") to compile.

It is wrong, because the constructor expects a valid null-terminated string, although the example compiles, its behaviour is undefined.

Similarly std::string str(0); will work and is undefined too because the literal zero is implicitly convertible to a pointer as it was used as pre-C++11 version of nullptr - NULL.

EDIT: I originally claimed std::logic_error will be thrown, @François Andrieux corrected me.

When you write std::string str, you're declaring a string. nullptr is a pointer value.

So if you had a string pointer, you could do this std::string *str(nullptr);.

But with just a straight std::string it makes no sense.


I'm guessing you're coming from Java or C# where all objects behind the scenes are secretly pointers/references. So when you write String str, you would initialize it to null (or the language's equivalent). But in C++, nothing is a pointer unless you explicitly declare it to be so (which you shouldn't unless you know you really need a pointer).

What that means, is that an std::string (like an int or std::vector or ...) in C++ will always have a value.

Related