Brace initialization subtleties

痴心易碎 提交于 2019-12-08 03:23:37

问题


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);
}

The output is:

vector<string> vs{3};
Size: 3
#1:
#2:
#3:
---------------------
vector<int> vi{3};
Size: 1
#1: 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?


回答1:


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).


来源:https://stackoverflow.com/questions/22121583/brace-initialization-subtleties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!