1

In this code:

#include <string>
#include <iostream>
 
void my_function(const char* value)
{
    std::cout << "char *  " << (value ? value : "nullptr");
}

void my_function(const std::string &value)
{
    std::cout << "string";
}

int main()
{
    my_function({});
}

https://godbolt.org/z/56bxzjM1M

The const char * overload is chosen, passing a nullptr pointer. Can somebody explain why? I assume this is something weird with initializer lists? (By the way, this happens with my_function(string value) too, so it isn't the reference).

This caused a crash in our code because somebody added a const char * overload, causing the rare caller who passed {} to send in a nullptr.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Rob L
  • 2,351
  • 13
  • 23
  • 1
    Dupe: [Why {} is better candidate to be int than string for C++ overload resolution?](https://stackoverflow.com/questions/72056424/why-is-better-candidate-to-be-int-than-string-for-c-overload-resolution/72057076#72057076) – Jason Nov 01 '22 at 17:18
  • 1
    @JasonLiam Thanks, I couldn't find that, I appreciate it. – Rob L Nov 01 '22 at 17:22

0 Answers0