本文介绍了大括号初始化的微妙之处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试使用括号初始化时,在使用std::vector时会发现一个微妙之处,如以下示例所示:

While trying to use brace initialization, a subtlety that can be found is when using std::vector, like showed in the following sample:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

template <typename T>
void print(const char * msg, const vector<T>& v) {
    cout << msg << endl;
    cout << "Size: " << v.size() << endl;
    for (size_t i = 0; i < v.size(); ++i) {
        cout << "#" << (i+1) << ": " << v[i] << endl;
    }
    cout << "---------------------" << endl;
}

int main() {
    vector<string> vs{3};
    print("vector<string> vs{3};", vs);

    vector<int> vi{3};
    print("vector<int> vi{3};", vi);
}

输出为:

vector<string> vs{3};
Size: 3
#1:
#2:
#3:
---------------------
vector<int> vi{3};
Size: 1
#1: 3
---------------------

因此,在第一种情况下,(所谓的...)统一初始化将初始化包含三个空字符串的向量,而在第二种情况下,它将初始化仅包含一个整数的向量,该整数具有值3.

So, in the first case, the (so called...) uniform initialization initializes a vector conatining three empty strings, instead in the second case it initializes a vector containing just one integer having the value 3.

除此以外,使用新的花括号初始化样式时还需要考虑其他陷阱"和细微之处吗?

Besides this, are there other "gotchas" and subtleties to consider when using the new brace initialization style?

推荐答案

似乎您已经了解了容器的初始值设定项列表构造函数的贪婪性质.有关其他令人惊讶的陷阱",请参见 这个问题与解答 ,我被这个

It seems that you already understand the greedy nature of initializer-list constructors for containers. For the other surprising "gotchas" see this Q&A where I got tripped by this

std::string{ 65, 'C' } // NOT 65 times 'C', but "AC" ('A' is 65th character).

这篇关于大括号初始化的微妙之处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 10:28