统一初始化导致 C++ 中的运行时错误 [英] Uniform initialization causes runtime error in C++

查看:734
本文介绍了统一初始化导致 C++ 中的运行时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我非常喜欢统一初始化,并且在大多数情况下我想构造初始化变量时都会使用它.最近,我在构造 cv::Mat 类型的变量时遇到了奇怪的错误.

I'm huge fan of uniform initialization and I'm using it in most cases when i want to construct initialized variable. Recently, I came across weird error while i was constructing variable of type cv::Mat.

cv::Mat lookUpTable( 1, 256, CV_8U );
uchar* p = lookUpTable.ptr();

for( int i = 0; i < 256; ++i )
{
    p[i] = cv::saturate_cast<uchar>( pow( i / 255.0, gamma ) * 255.0 );
}

虽然这个实现效果很好,但如果使用统一初始化

While this implementation works well, if uniform initialization is used

cv::Mat lookUpTable{ 1, 256, CV_8U };

出现以下错误

malloc_consolidate(): 无效的块大小

malloc_consolidate(): invalid chunk size

我仍然不确定会发生什么.是否使用了不同的构造函数(比预期的)?有人可以进一步解释吗?

I'm still not really sure what happes. Is different constructor (than supposed) used ? Can somebody explain further, please ?

推荐答案

cv::Mat lookUpTable{ 1, 256, CV_8U } 调用与 cv::Mat lookUpTable(1, 256, CV_8U ).cv::Mat lookUpTable{ 1, 256, CV_8U }direct-list-initialization 并且因为 cv::Mat 有一个构造函数接受一个std::initlizer_list,该构造函数将被调用,而不是第一次调用时调用的第 3 个参数.这意味着您有一个包含元素 { 1, 256, CV_8U } 的矩阵,而不是包含 256 个元素的矩阵.

cv::Mat lookUpTable{ 1, 256, CV_8U } calls a different constructor than cv::Mat lookUpTable( 1, 256, CV_8U ). cv::Mat lookUpTable{ 1, 256, CV_8U } is direct-list-initialization and since cv::Mat has a constructor accepting a std::initlizer_list, that constructor will be called instead of the 3 parameter one the first call does. This means you have a matrix that contains the elements { 1, 256, CV_8U }, instead of a 256 element matrix.

Nicolai Josuttis 在 CppCon2018 上就​​统一初始化的一致性"发表了非常精彩的演讲:https://www.youtube.com/watch?v=7DTlWPgX6zs

Nicolai Josuttis has a really nice talk at CppCon2018 about the "uniformity" of uniform initialization: https://www.youtube.com/watch?v=7DTlWPgX6zs

这篇关于统一初始化导致 C++ 中的运行时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆