在c++中调用静态成员的方法进行初始化

Call a method of a static member for initialization in C++

本文关键字:方法 初始化 静态成员 c++ 调用      更新时间:2023-10-16

我有一个具有静态成员对象的类。初始化静态对象意味着将它的一些参数设置为特定的值;但这是由那个物体的一个函数完成的。如果它是静态的,我不知道怎么做。任何帮助吗?


更具体地说,我每个类都有一个静态boost记录器对象。它有一个ClasName属性,通过add_attribute("ClassName", boost::log::attributes::constant<std::string>("MyClass"))函数将其设置为name_of_the_class值。初始化静态日志记录器的最佳方法是什么?我已经做了:

typedef boost::log::sources::severity_logger< severity_levels > BoostLogger;
class MyClass
{
private:
  static BoostLogger m_logger;
public:
  MyClass()
  {
    MyClass::m_logger.add_attribute("ClassName", boost::log::attributes::constant<std::string>("MyClass"));
  }
}
BoostLogger MyClass::m_logger; // And here I cannot call the add_attribute() function

我知道每次实例化类时都会这样做,所以:最好的方法是什么?

你可以初始化logger一次,例如在构造函数中使用静态变量:

MyClass()
{
  static bool logger_initialised = false;
  if (!logger_initialised)
  {
    MyClass::m_logger.add_attribute("ClassName", boost::log::attributes::constant<std::string>("MyClass"));
    logger_initialised = true;
  }
}

注意这不是线程安全的。但是,如果您不使用线程,它将工作,并且日志记录器将被初始化一次,但仅当您实例化MyClass时。

如果BoostLogger没有提供add_attribute的构造函数,您可以创建自己的函数,如:

class MyClass
{
private:
    static BoostLogger m_logger;
};
BoostLogger CreateBoostLoggerWithClassName(const std::string& className)
{
    BoostLogger logger;
    logger.add_attribute(
        "ClassName",
        boost::log::attributes::constant<std::string>(className));
    return logger;
}
BoostLogger MyClass::m_logger = CreateBoostLoggerWithClassName("MyClass");

首先看BOOST_LOG_GLOBAL_LOGGER

这是你的代码的更正版本。

MyClass.h:

class MyClass
{
private:
  static BoostLogger m_logger;  /*  This is declaration, not definition.
                                    You need also define the member somewhere */
public:
  MyClass() /*  So far as this is constructor, it may be called more than once,
                I think adding new static function will be better */
  {
    // MyClass::m_logger.add_attribute("ClassName", boost::log::attributes::constant<std::string>("MyClass"));
    // AddAttribute("ClassName"); Uncomment this line if you're really need to add attribute in constructor
  }
  static void AddAttribute(std::string name) /* this function has been added as advice,
                                                if you're going add attributes as you
                                                did in question,
                                                remove function, and uncomment first              line in the constructor */
  {
    MyClass::m_logger.add_attribute(name, boost::log::attributes::constant<std::string>("MyClass"));
  }
}

MyClass.cpp:

BoostLogger MyClass::m_logger = BoostLogger(); // This is definition of static member item

不使用add_attribute调用,而是使用它的构造函数完全初始化BoostLogger。然后在定义它时简单地提供必要的参数。