5

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 ?

kocica
  • 6,412
  • 2
  • 14
  • 35

2 Answers2

11

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

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
6

Using {...} to construct an object is called "list-initialization".

cv::Mat provides a constructor taking std::initializer_list: https://github.com/opencv/opencv/blob/master/modules/core/include/opencv2/core/mat.hpp#L1007

There is a special rule in overload resolution that always gives priority to constructors taking std::initializer_list if list-initialization is used, regardless of the existence of other constructors which might require less implicit conversions.

Calling cv::Mat(...) is completely different from cv::Mat{...}.


My mental model for this is: if the object you're constructing is a container, then {...} will likely behave differently from (...), therefore you should be careful. Otherwise, prefer {...}.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416