【问题标题】:why an integer can be assigned to a string variable? [duplicate]为什么可以将整数分配给字符串变量? [复制]
【发布时间】:2019-02-25 08:52:44
【问题描述】:

在Visual Studio 2013中,如果我写,编译器会报错:

std::string test = 3; 

显示:

错误 C2440:“正在初始化”:无法从“int”转换为 'std::basic_string,std::allocator>'.

但是,如果我将其更改为:

std::string test = "";
test = 3; 

它只是编译!当然会以悲剧收场。

为什么会发生这种情况?

【问题讨论】:

    标签: c++ visual-studio type-conversion stdstring


    【解决方案1】:

    这是因为我们有以下赋值运算符:

    basic_string& operator=( CharT ch )
    

    see cppreference.

    在这种情况下,int 转换为 char

    这受到defect report 2372: Assignment from int to std::string 的影响,该defect report 2372: Assignment from int to std::string 已作为非缺陷 (NAD) 关闭。它说:

    以下代码在 C++ 中工作:

    int i = 300;
    std::string threeHundred;
    threeHundred = i;
    

    "Works" == "编译并且没有未定义的行为"。但它 可能并不明显,实际上会误导它的作用。 这个 assignment 将 int 转换为 char,然后使用 string 的赋值 来自字符。虽然 char 的赋值可以被认为是一个特征, 能够从 int 分配看起来像一个安全漏洞。有人可能 相信 C++ 像“动态类型”语言一样工作,并期望 进行词法转换。

    理想情况下,来自 char 的分配可能会被弃用,以后会被弃用 已删除,但作为一种侵入性较小的替代方案,可以考虑添加 一个 SFINAEd 删除的函数模板:

    template <typename IntT> // enable if is_integral<IntT>::value
    basic_string& operator=(IntT) = delete;
    

    决议是:

    这应该通过提交给 LEWG 的文件来解决

    【讨论】:

    【解决方案2】:

    String 可从char 分配。 int 可以隐式转换为 char。

    【讨论】:

      猜你喜欢
      • 2018-03-26
      • 1970-01-01
      • 2010-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      • 2013-10-29
      相关资源
      最近更新 更多