【问题标题】:std::vector::operator[] doesn't test typestd::vector::operator[] 不测试类型
【发布时间】:2012-07-20 20:35:25
【问题描述】:

我有一个这样的结构:

struct VrtxPros{
    long idx;
    std::vector<std::string> pros;
    VrtxPros(const long& _idx=-1, const std::string& val="") : idx(_idx)
    {
         if ( !val.empty() && val!="" )
             pros.push_back(val);
    }
};

后来在代码中我这样使用它:

long idx = 1234;
VrtxPros vp( 2134, std::string("-1") );
if ( margin ) vp.pros[0] = idx;

编译器对此没有任何问题。我想知道,因为运营商应该提供参考。 我could not findoperator= 中的std::string 将接受long 作为源。

为什么代码会编译?

【问题讨论】:

  • basic_string&amp; operator=( CharT ch ); 4) Replaces the contents with character ch。您的 long 可能正在转换为字符。其他需要注意的是,如果我没有遗漏某些内容,您的!= "" 检查是多余的,并且传递"-1" 很好,因为std::string 具有const char * 的隐式转换构造函数。
  • @mistapink,long 可以隐式转换为charideone.com/wNd4u
  • @mistapink,对于CharT,它是std::basic_string&lt;&gt; 的第一个模板参数,即char for std::string。为了比较,CharT 将是 wchar_t 对应于 std::wstring
  • g++ 将 int 隐式转换为 char..
  • @Hrishi,g++ 不应该是唯一的:int x = 999; ...; char c1 = x; // OK, though it might narrow (in this case, it does narrow) 取自 C++11 标准,第 8.5.4 节

标签: c++ vector type-conversion


【解决方案1】:

std::string 可以分配给charlong 可以隐式转换为char,因此std::string 可以分配给long。您的编译器可能会针对这种隐式转换发出警告(如果您还没有看到,请调高警告级别并看到它)。

查看#4 operator= 列出的here。注意没有constructor overload 只需要一个字符,所以这种事情只能用于赋值。

就此而言,您也可以这样做:

std::string wow;
wow = 7ull; // implicit unsigned long long to char conversion
wow = 1.3f; // implicit float to char conversion

【讨论】:

  • 我的链接样本没有收到任何警告。只有operator= 这样做,而不是构造函数,所以大部分时间都是经过深思熟虑的。
  • @chris 在 VS2010 中,警告级别为 4 我收到了来自您和我的代码的警告。
  • @chris:是的,它在标准中交付,不,我不太明白为什么,但是在 std::basic_string&lt;&gt; 中有一个 operator= 的过载,需要一个 @987654334 @ 目的。为什么要进行这样的手术是我过去一直想知道的。
【解决方案2】:

使用 -Wconversion for g++ 来获取从 long 到 char 的隐式转换的警告。

【讨论】:

  • 啊,很惊讶我从来没有收录过那个。
猜你喜欢
  • 1970-01-01
  • 2020-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-29
  • 2021-12-04
  • 2015-06-13
相关资源
最近更新 更多