我放在单个文件中的代码在分成多个文件时表现不同。我在一个类(一个 std::vector
)中有一个 static
字段,我在全局对象实例化期间修改它,我在 main
中分析它。
我怀疑这是由于在不同范围内创建对象的方式所致,但我认为这种情况会导致共享同一对象。
如何分离此代码并获得与代码并置时相同的结果?
更新 如果我在 main.cpp 中声明静态对象,代码就可以工作。这是唯一的方法吗?感觉很乱,这不是我要声明的地方。
这是代码。
工具.h
#pragma once
#include <vector>
#include <iostream>
class Collector
{
public:
static std::vector<int> Ints;
};
class Aggregator
{
public:
Aggregator(int i);
};
主要.cpp
#include "utils.h"
// as noted in my updated question, if I declare Ints here, it works
// std::vector<int> Collector::Ints;
// but I want the freedom to declare this in any source
Aggregator inst(1);
int main()
{
std::cout << "size: " << Collector::Ints.size();
std::cin.get();
return 1;
}
实用程序.cpp
#include "utils.h"
std::vector<int> Collector::Ints;
Aggregator::Aggregator(int i)
{
Collector::Ints.push_back(i);
}
输出为大小:0
一个文件中的所有相同代码将如下所示:
#include <vector>
#include <iostream>
class Collector
{
public:
static std::vector<int> Ints;
};
class Aggregator
{
public:
Aggregator(int i);
};
#include "utils.h"
std::vector<int> Collector::Ints;
Aggregator::Aggregator(int i)
{
Collector::Ints.push_back(i);
}
Aggregator inst(1);
int main()
{
std::cout << "size: " << Collector::Ints.size();
std::cin.get();
return 1;
}
这会输出 size: 1
,如我所愿。
最佳答案
避免这种情况的一种方法是使用带有静态变量的静态函数。 例如:
class Collector
{
public:
static std::vector<int> & GetInts(){ static std::vector<int> Ints; return Ints; }
};
这样一来,无论您在哪个 cpp 文件中使用静态变量,都可以保证在您使用它时对其进行初始化。
我要强调的是,这不是一个好主意,因为您会遇到线程问题。是否有充分的理由使其成为静态的?
关于c++ - 与并置到单个文件中相比,多个文件中的不同代码行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22494238/