C++ 的一个哲学基础是,你不应该为你没有使用的东西付出代价。
class 拥有一个 static 成员,即使从未被用到,它也会被构造和析构;
而 函数拥有一个 static 成员, 如果这个函数从未被调用,则这个对象不会被构造。
做个简单的实验:
#include
using namespace std;
class Printer
{
friend Printer& thePrinter();
private:
Printer() {
cout << "constructor called" << endl;
}
~Printer() {
cout << "destructor called" << endl;
}
};
Printer& thePrinter()
{
static Printer p;
return p;
}
int main(void)
{
return 0;
}
相反,类中的一个static 成员,一定会被构造,
#include
using namespace std;
class Printer
{
friend class PrintJob;
private:
Printer() {
cout << "constructor called" << endl;
}
~Printer() {
cout << "destructor called" << endl;
}
};
class PrintJob
{
public:
static Printer p;
};
Printer PrintJob::p;
int main(void)
{
return 0;
}
因为类的static 成员独立于对象而存在,因此无论是否定义了这个类的对象,
static 成员都会构造出来。