你怎么能emplace_back错误的类型?

How can you emplace_back the wrong type?

本文关键字:类型 错误 back 怎么能 emplace      更新时间:2023-10-16

我有一个双精度向量。但我有一个错字

我打算写这个:

std::vector<double> timestamp;

但我写了这个:

std::vector<std::vector<double>> timestamp;

但是,这会编译

timestamp.emplace_back(a_double_timestamp)

我正在将double放回std::vector<std::vector<double>>.double不是std::vector<double>

>double被隐式转换为size_type,作为向量构造函数的参数:

explicit vector( size_type count );

因此,如果传递2.3,则创建的向量的大小为static_cast<std::vector<double>::size_type>(2.3) == 2

std::vector<double> v{2.3}也会在没有任何警告的情况下进行编译。

你收到任何警告吗?MSVC 发出警告

">

参数":从"双精度"转换为"常量无符号__int64", 可能丢失的数据

虽然海湾合作委员会头保持沉默。

这里发生的情况是调用内部向量explicit vector( size_type count );构造函数,自动从双精度转换为size_type

我逐步浏览了代码以查看发生了什么,我看到的是(无论如何在Visual Studio 2017中(正在调用以下构造函数:

vector(_CRT_GUARDOVERFLOW const size_type _Count, const _Alloc& _Al = _Alloc())

。这似乎暗示双精度被隐式转换为size_type(我在测试中使用了 12.3 的双精度,调试器告诉我_Count是 12(。_Al具有默认值,因此构造函数匹配。