The problem is that std::string
has a non-explicit ctor that takes a char *
as its sole (required) parameter. This gives an implicit conversion from nullptr
to std::string
, but gives undefined behavior, because that ctor specifically requires a non-null pointer.
There are a few ways to prevent this. Probably the most effective would be to take a (non-const) reference to a std::string
, which will require passing a (non-temporary) string
as the parameter.
FanBookPost::FanBookPost(Fan* owner, std::string &content);
This does have to unfortunate side effect of giving the function the ability to modify the string that's passed. It also means that (with a conforming compiler1) you won't be able to pass nullptr
or a string literal to the function--you'll have to pass an actual instance of std::string
.
If you want to be able to pass a string literal, you can then add an overload that takes a char const *
parameter, and possibly one that takes a nullptr_t
parameter as well. The former would check for a non-null pointer before creating a string and calling the function that takes a reference to a string, and the latter would do something like log the error and unconditionally kill the program (or, just possibly, log the error and throw an exception).
That's annoying and inconvenient, but may be superior to the current situation.
- Unfortunately, the last time I noticed MS VC++ did not conform in this respect. It allows passing a temporary object by non-const reference. Normally that's fairly harmless (it just lets you modify the temporary, but that normally has no visible side effects). In this case it's much more troublesome though, since you're depending on it specifically to prevent passing a temporary object.