set static variable in function only once

  • A+

So I was wondering if it is possible to set a static variable inside a function scope only once. For example consider this function:

void projectPointIntoPlane(const Affine3f& plane2xy, Vector3f& p) {    static Matrix3f P;   P << Vector3f::UnitX(), Vector3f::UnitY(), Vector3f::Zero();    p = plane2xy.inverse() * P * plane2xy * p; } 

I would like to set P only once and not at every function call, how can I achive this?


Instead of declaring P and thereafter initializing it separately, you can initialize it in the declaration, using the finished() method of CommaInitializer:

static const Matrix3f P =     (Matrix3f() << Vector3f::UnitX(), Vector3f::UnitY(),      Vector3f::Zero()).finished(); 

With this approach, you can also declare P as const.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: