Home > database >  what is the meaning of declaration e.g. void a(string b=0)
what is the meaning of declaration e.g. void a(string b=0)

Time:01-25

I wrote a function with an optional string parameter, but accidentally instead of defaulting it to "" I defaulted it to 0:

void a(string b=0)

I compiled without any warning or else.

Without (!!!) using the content in case of a defaulted parameter (according to other parameters, this one was only used when explicitly set), this caused VERY strange behaviour in nearby code.

Again: I did NOT use that null value'ed string, but got segfaults on changing nearby code locations.

My question, as the compiler did not complain: What is the meaning of that syntax, defaulting some complex parameter (non-numeric, non-pointer) to 0?

======================================== accidentally wrote

void a(string b=0)

instead of

void a(string b="")

expected compiler to failure due to syntax error, but it compiled fine.

CodePudding user response:

When constructing a std::string with 0, the compiler will select the following overloaded constructor for the std::string class:

basic_string(const charT* s, const Allocator& a = Allocator());

However, passing a null pointer as the first argument, instead of a null-terminated c-string, is undefined behavior.

  • Related