I have the following simple c (RAII pattern) wrapper around jpeg_decompress_struct
(ijg/libjpeg-turbo):
class Decompress {
typedef jpeg_decompress_struct *ptr;
jpeg_decompress_struct srcinfo;
public:
Decompress() { jpeg_create_decompress(&srcinfo); }
~Decompress() { jpeg_destroy_decompress(&srcinfo); }
operator ptr() { return &srcinfo; }
jpeg_decompress_struct *operator->() { return &srcinfo; }
};
I am happy with this code, and I'd like to keep srcinfo
as it is now (on the stack, just like upstream expect it.)
Is there a way to rewrite the above constructor using a member initialization list ? I'd like to pass the check of gcc -Weffc
.
Current warning is:
jpeg.cxx:92:3: error: ‘acme::Decompress::srcinfo’ should be initialized in the member initialization list [-Werror=effc ]
92 | Decompress() { jpeg_create_decompress(&srcinfo); }
| ^~~~~~~~~~
CodePudding user response:
If (which we can probably safely assume here) jpeg_create_decompress()
can operate on a jpeg_decompress_struct
containing undefined values, then the code you posted is fine as is . I wouldn't personally touch it.
However, the question can still be answered as aksed:
Most question formulated as "How to do __blank__ in an initialization list" have the same answer: Do it in a function.
jpeg_decompress_struct make_initialized_jds() {
jpeg_decompress_struct result;
jpeg_create_decompress(&result);
return result;
}
class Decompress {
typedef jpeg_decompress_struct *ptr;
jpeg_decompress_struct srcinfo;
public:
Decompress() : srcinfo(make_initialized_jds()) {}
~Decompress() { jpeg_destroy_decompress(&srcinfo); }
operator ptr() { return &srcinfo; }
jpeg_decompress_struct *operator->() { return &srcinfo; }
};
In modern compilers making use of NRVO, this won't even result in any additional overhead.
Edit: From the updated question: If you just want to make the warning go away, you can explicitely initialize the struct using a member initialization:
class Decompress {
typedef jpeg_decompress_struct *ptr = nullptr; // <---- might as well.
jpeg_decompress_struct srcinfo = {0}; // <----- here
public:
Decompress() { jpeg_create_decompress(&srcinfo); }
~Decompress() { jpeg_destroy_decompress(&srcinfo); }
operator ptr() { return &srcinfo; }
jpeg_decompress_struct *operator->() { return &srcinfo; }
};
This will give srcinfo
a defined value before invoking jpeg_create_decompress()
.