ENH: Let x::New() initialize the created object by doing new x()#4481
Conversation
b7648d7 to
1d77c81
Compare
x::New() initialize all member data, by doing new x()
1d77c81 to
6453b6f
Compare
Replace `new x` with `new x()`, in the definitions of `itkSimpleNewMacro` and `itkFactorylessNewMacro`. This ensures that objects created by `x::New()` are "value-initialized". In practice, this will zero-initialize data members that might otherwise be left uninitialized. Added GTests to check that `x::New()` does indeed properly initialize the created object.
6453b6f to
45f534a
Compare
x::New() initialize all member data, by doing new x()x::New() initialize the created object by doing new x()
|
Just for completeness , if a class has any user-provided ctor, #include <iostream>
class A
{
public:
A() {}
int x;
double y;
};
int main()
{
A * a = new A();
std::cout << a->x << ' ' << a->y << std::endl;
delete a;
return 0;
} |
Indeed, thanks @issakomi But of course, your example class Obviously the ITK/Modules/Core/Common/test/itkLightObjectGTest.cxx Lines 29 to 49 in 45f534a So I hope you agree that this pull request is a step in the right direction 😃 |
Ah, yes, I see the comment in the example now |
|
@blowekamp I think this pull request may also be of interest to you 😃, as you had concerns about uninitialized data, as you mentioned at #4473 (comment) By the way, pull request #4479 ( |
|
Why do we use '()' here instead of '{}'? |
Good question, thanks @blowekamp It appears that in 99,9 % of the cases |
This supports the other comment I was about to make. I think the C++ initialization rule are rather complicated and there are cases I don't fully understand. I'll defer to you for the correctness of this patch. |
|
Ah, I just double-checked. For a class So in the context of this PR, the choice between |
Replace
new xwithnew x(), in the definitions ofitkSimpleNewMacroanditkFactorylessNewMacro. This ensures that objects created byx::New()are"value-initialized". In practice, this will zero-initialize data members that
might otherwise be left uninitialized.
Added GTests to check that
x::New()does indeed properly initialize thecreated object.