简体   繁体   中英

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

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.

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 .

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