C++11 initializer list fails - but only on lists of length 2

前端 未结 2 1268
盖世英雄少女心
盖世英雄少女心 2020-11-27 04:24

I tracked down an obscure logging bug to the fact that initializer lists of length 2 appear to be a special case! How is this possible?

The code was compiled with A

2条回答
  •  日久生厌
    2020-11-27 04:33

    First of all, this is undefined behaviour unless I'm missing something obvious. Now let me explain. The vector is being constructed from an initializer list of strings. However this list only contains one string. This string is formed by the inner {"Hello", "there"}. How? With the iterator constructor. Essentially, for (auto it = "Hello"; it != "there"; ++it) is forming a string containing Hello\0.

    For a simple example, see here. While UB is reason enough, it would seem the second literal is being placed right after the first in memory. As a bonus, do "Hello", "Hello" and you'll probably get a string of length 0. If you don't understand anything in here, I recommend reading Filip's excellent answer.

提交回复
热议问题