c++opencvuniform-initialization

Uniform initialization causes runtime error in C++


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

following error shows up

malloc_consolidate(): invalid chunk size

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


Solution

  • 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 has a really nice talk at CppCon2018 about the "uniformity" of uniform initialization: https://www.youtube.com/watch?v=7DTlWPgX6zs