简体   繁体   English

仅在函数中设置一次静态变量

[英]set static variable in function only once

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? 我想只设置一次P而不是每个函数调用,我怎么能得到这个?

Instead of declaring P and thereafter initializing it separately, you can initialize it in the declaration, using the finished() method of CommaInitializer : 您可以使用CommaInitializerfinished()方法在声明中初始化它,而不是声明P然后单独初始化它:

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

With this approach, you can also declare P as const . 使用这种方法,您还可以将P声明为const

You could use a lambda that returns the right value. 您可以使用返回正确值的lambda。 Since it's in the initialization expression, it's only called once: 因为它在初始化表达式中,所以它只被调用一次:

void projectPointIntoPlane(const Affine3f& plane2xy, Vector3f& p)
{
    static Matrix3f P = []{
        Matrix3f P;
        P << Vector3f::UnitX(), Vector3f::UnitY(), Vector3f::Zero();
        return P;
    }();

    p = plane2xy.inverse() * P * plane2xy * p;
}

Something along these lines: 这些方面的东西:

static Matrix3f P;
static bool dummy = (
  (P << Vector3f::UnitX(), Vector3f::UnitY(), Vector3f::Zero()),
  true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM