我有一个具有静态成员对象的类。初始化该静态对象意味着将其某些参数设置为特定值;但这是通过该对象的函数完成的。如果它是静态的我不知道怎么做。有什么帮助吗?
更具体地说,每个类都有一个静态的boost记录器对象。它具有ClasName
属性,并将此设置为name_of_the_class
值由add_attribute("ClassName", boost::log::attributes::constant<std::string>("MyClass"))
函数完成。初始化静态记录器的最佳方法是什么?我做了:
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
我知道每次实例化类都会这样做,所以:最好的方法是什么?
答案 0 :(得分:3)
您可以将记录器初始化一次,例如在构造函数中使用静态变量:
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
时。
答案 1 :(得分:1)
以下是您的代码的更正版本。
<强> 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
答案 2 :(得分:1)
如果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");
答案 3 :(得分:0)
而不是add_attribute
调用,请将其设置为使用其构造函数完全初始化BoostLogger
。然后在定义时简单地提供必要的参数。