简体   繁体   English

你怎么能把错误的类型放回去?

[英]How can you emplace_back the wrong type?

I have a vector of doubles. 我有一个双打矢量。 But I had a typo 但我有一个错字

I intended to write this: 我打算写这个:

std::vector<double> timestamp;

But I wrote this instead: 但我写了这个:

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

However, this compiles 但是,这个编译

timestamp.emplace_back(a_double_timestamp)

I am emplacing back a double into a std::vector<std::vector<double>> . 我将一个double放回到std::vector<std::vector<double>> double is not std::vector<double> double不是std::vector<double>

double is implicitly converted to size_type , acting as a parameter to the vector constructor : double被隐式转换为size_type ,充当向量构造函数的参数:

explicit vector( size_type count );

Therefore, if you pass 2.3 , the vector created has size static_cast<std::vector<double>::size_type>(2.3) == 2 . 因此,如果传递2.3 ,则创建的向量的大小为static_cast<std::vector<double>::size_type>(2.3) == 2

std::vector<double> v{2.3} also compiles without any warning. std::vector<double> v{2.3}也可以在没有任何警告的情况下编译。

Do you get any warnings? 你有任何警告吗? MSVC gives warning MSVC发出警告

'argument': conversion from 'double' to 'const unsigned __int64', possible loss of data 'argument':从'double'转换为'const unsigned __int64',可能会丢失数据

though GCC HEAD is silent. 虽然GCC HEAD是沉默的。

What happens here is that explicit vector( size_type count ); 这里发生的是explicit vector( size_type count ); constructor for your internal vector is called, with automatic conversion from double to size_type 调用内部向量的构造函数,自动从double转换为size_type

I stepped through the code to see what was happening, and what I am seeing (in Visual Studio 2017 anyway) is that the following constructor is being called: 我逐步查看代码,看看发生了什么,我所看到的(无论如何在Visual Studio 2017中)是调用以下构造函数:

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

... which seems to imply that the double was implicitly converted to a size_type (I used a double of 12.3 in my test, and the debugger is telling me _Count is 12). ...这似乎意味着双重隐式转换为size_type(在我的测试中我使用了12.3的两倍,调试器告诉我_Count是12)。 _Al has a default value, so the constructor matches. _Al具有默认值,因此构造函数匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM