下面的代碼使用空的C + 11樣式初始化程序。運行結果是一個std::vector
包含一個項目,似乎是默認構造。空C++ 11初始化列表導致容器中有一個默認構造對象
這顯然是一個仿真案例,並且有更好的方法來構造一個空向量。 Nonetheles,這種行爲是違反直覺的。這是一個編譯器/ c + +運行時庫錯誤?
我懷疑其中一個std::vector
的其他構造函數實際上是在這裏調用的。
#include <iostream>
#include <memory>
#include <vector>
int main(int argc, const char * argv[])
{
typedef std::vector<std::shared_ptr<int>> Container;
Container c{{}};
std::cout << "Vector size is: " << c.size() << std::endl;
for (auto item: c)
{
std::cout << "Item: " << item.get() << std::endl;
}
}
輸出:
Vector size is: 1
Item: 0x0
Program ended with exit code: 0
編譯器:
$ clang --version
Apple clang version 3.0 (tags/Apple/clang-211.12) (based on LLVM 3.0svn)
Target: x86_64-apple-darwin12.4.0
'Container c {{}};'用一個元素'{}'構造一個向量(std :: shared'的默認構造函數)。 – Jarod42
我認爲在這種情況下,矢量只是用一個默認構造元素'{{}}'的列表進行初始化。你想要的是一個空列表{{}'。 –