字符串会自动将常量字符* 转换为 std::string

string automatically converts const char* to std::string

本文关键字:转换 std string 字符 常量 字符串      更新时间:2023-10-16

我在旧编译器中使用std::out_of_range constructor代码时收到"构造函数没有实例"错误,偶然发现了这个问题

对于一些较旧的编译器,std::out_of_range的定义是

class out_of_range : public logic_error {
public:
      out_of_range(const string& message);
};

在较新的版本中,他们添加了第二个构造函数

class out_of_range : public logic_error {
public:
      out_of_range(const string& message);
      out_of_range(const char *message);
};

我尝试编译的代码执行了以下构造函数调用:

std::out_of_range("Some Error Message");

添加#include <string>

编译器能够将const char*转换为std::string

这是预期的行为吗?

是的,这是意料之中的,因为相关的构造函数std::string::string(const char*)不是explicit,这意味着它可用于这样的隐式转换。