我的印象是类的静态成员在该类的所有实例之间共享它们的值。我的理解似乎缺乏,也许是因为包含模板或constexpr在这个例子中:
#include <iostream>
#include <array>
template <typename T, std::size_t maxSize>
class Foo
{
public:
unsigned int getLen() {
return containerLen;
}
private:
static constexpr std::size_t containerLen = maxSize + 1;
std::array<T, containerLen> arr;
};
int main()
{
Foo<int, 10> foo1;
std::cout << foo1.getLen() << std::endl;
Foo<int, 12> foo2;
std::cout << foo2.getLen() << std::endl;
std::cout << foo1.getLen() << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这给出了以下输出:
11
13
11
Run Code Online (Sandbox Code Playgroud)
我可能遗漏了一些明显的东西,但是是什么让每个实例Foo具有不同的值containerLen?
当我链接一个包含静态对象的文件时,无论是否使用过该对象或者是否包含标头,都会运行该对象的构造函数。g++ 中有没有办法阻止这种行为的发生,或者是不链接文件的唯一答案?
foo.h
#include <iostream>
class Bar {
public:
Bar(int inMemberInt) {
std::cout << "In Bar constructor." << std::endl;
}
};
class Foo {
public:
static const Bar constVar;
};
Run Code Online (Sandbox Code Playgroud)
文件
#include "foo.h"
const Bar Foo::constVar(1);
Run Code Online (Sandbox Code Playgroud)
主程序
#include <iostream>
int main() {
std::cout << "Hello." << std::endl;
return 1;
}
Run Code Online (Sandbox Code Playgroud)
构建命令
g++ foo.h foo.cpp main.cpp -o main
Run Code Online (Sandbox Code Playgroud)
输出
In Bar constructor.
Hello.
Run Code Online (Sandbox Code Playgroud)