C++ Quiz2 of 173
Difficulty:
⬅️ Prev: 1Quiz ID: 2Next: 3 ➡️

According to the C++23 standard, what is the output of this program?

#include <iostream>
#include <string>

void f(const std::string &) { std::cout << 1; }

void f(const void *) { std::cout << 2; }

int main() {
  f("foo");
  const char *bar = "bar";
  f(bar);
}
Hint

What is the type of a string literal? Does the compiler prefer standard or user defined conversions?

Reveal answer

22

Explanation

A string literal is not a std::string, but a const char[] . If the compiler was to choose f(const std::string&), it would have to go through a user defined conversion and create a temporary std::string. Instead, it prefers f(const void*), which requires no user defined conversion.

⬅️ Prev: 1Quiz ID: 2Next: 3 ➡️