为什么我不能使用统一初始化初始化字符串?

问题描述 投票:4回答:1

我有一个模拟窗口的程序;所以我将窗口的内容存储在成员数据content中,这是一个std::string类型:

class Window {
    using type_ui = unsigned int;
    public:
        Window() = default;
        Window(type_ui, type_ui, char);
        void print()const;

    private:
        type_ui width_{};
        type_ui height_{};
        char fill_{};
        std::string content_{};
        mutable type_ui time_{};
};

Window::Window(type_ui width, type_ui height, char fill) :
    width_{ width }, height_{ height }, fill_{ fill },
    content_{ width * height, fill } { // compile-time error here?
    //content( width * height, fill ) // works ok
}

void Window::print()const {
    while (1) {
        time_++;
        for (type_ui i{}; i != width_; ++i) {
            for (type_ui j{}; j != height_; ++j)
                std::cout << fill_;
            std::cout << std::endl;
        }
        _sleep(1000);
        std::system("cls");
        if (time_ > 10)
            return;
    }
}


int main(int argc, char* argv[]) {

    Window main{ 15, 25, '*' };
    main.print();

    std::string str{5u, '*'}; // compiles but not OK
    std::string str2(5u, '*'); // compiles and OK
    cout << str << endl; // ♣* (not intended)
    cout << str2 << endl; // ***** (ok)

    std::cout << std::endl;
}

如上所示,我无法用content初始化成员curly-braces-initializer-list,编译器抱怨“缩小类型”。但它适用于“直接初始化”。

  • 为什么我不能在Constructor-initializer-list中使用上面的Curly-brace-initialization-list来调用std::string(size_t count, char)
  • 为什么这个std::string str{5u, '*'}; // compiles but not OK工作,但没有给出预期的输出?
  • 重要的是为什么同样的初始化不能在构造函数成员初始化列表上工作,但在main中工作(没有预期的结果)?
c++ c++11 initializer-list stdstring
1个回答
8
投票
  • 首先,因为std::string的构造函数sts::string(size_t count, char)是显式的,所以你不能隐式地调用它。
  • 其次,你没有在std::string(size_t, char)中调用content{width * height, fill},但事实上你正在调用std::string(std::initializer_list<char>)。因此,表达式width * height产生一个unsigned int,然后隐式转换为char,这是“相关类型”,因此,例如,你传递Window main{ 15, 25, '*' };,它产生(char)15 * 25 = (char)375,这是未定义的行为,因为这个值溢出了signed char。您可以将您的机器“♣”或其他值作为初始化程序列表中的第一个元素但它是未定义的行为,而“”作为初始化程序列表中的第二个元素。因此,您传递的是std :: initializer_list {'♣',''}。 只要调用具有多个参数的显式构造函数,就使用直接初始化。
  • 第二个问题的答案是:“对我来说很重要的是为什么同样的初始化在构造函数成员初始化列表上不起作用但在main中工作(没有预期的结果)?”:

实际上它与“Constructor-member-initializer-list”没有任何关系,但实际上考虑到这一点:

    char c{ 127 }; // the maximum integer positive value that a signed char can hold so no narrowing conversion here. So it is OK.

    char c2{ 128 }; // Now 128 overflows the variavle c2. c2 is of type char and as you know it can hold positive values in range 0 to 127 and negative -1 to -128
    unsigned char uc{ 255 }; // ok because an unsigned char can hold 255
    unsigned char uc2{ 300 }; // error as the error above. An unsigned char can hold 255 as max positive value.

    unsigned char uc3 = 321; // ok // ok but you may get a warning. a Copy-initialization is not safe.
    cout << uc3 << endl; // you may get `A`. 321 % 256 = 65. 65 % 256 = 65. 65 in ASCII in some implementations it represents the character "A".

尽管上面溢出uc3并不好,但结果是明确定义的。 (溢出无符号Xtype)。

  • 但看看这个: char c3 = 321; // signed char overflows cout << c3 << endl; // you may get "A" and think it is correct.

上面是未定义的行为。永远不要尝试溢出签名类型。

constexpr int i = 10;
constexpr int j = 5;
std::string str{ i * j, 'f' }; // ok as long as the values are constexpr and don't cause any narrowing conversion this value: 10 * 5 = 50 which is a well defined signed-char value.

int i = 10;
int j = 5;
std::string str{ i * j, 'f' }; // error. the values of i and j are not constant thus it may overflow a signed char causing narrowing conversion thus the compiler is wise enough to prevent this initialization.
© www.soinside.com 2019 - 2024. All rights reserved.