Let's say we have POD Matrix4 class (matrix four by four).
User of this class often wants to initialize variable of Matrix4 type with identity matrix.
There are two choices I know:
-
Provide member function SetAsIdentity for that class that changes the value of *this. So user would do something like this :
Matrix4 m; m.SetAsIdentity();
-
Provide static member(or non-member) function that returns a static const identity matrix, something like this :
static Matrix4 Matrix4::Identity() { static const Matrix4 m({ 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 }); return m; }
and then use it like this:
Matrix4 m = Matrix4::Identity();
In my opinion, I'd like to use 2 more than 1 just because it can be used in one line of code. Is there a better way to initialize matrix while making sure Matrix4 is still POD? Could number 2 be implemented with constexpr? Speed difference, if any?
Aucun commentaire:
Enregistrer un commentaire