gpt4 book ai didi

c++ - 在创建类的常量对象之前初始化非常量变量

转载 作者:行者123 更新时间:2023-11-28 00:07:32 26 4
gpt4 key购买 nike

我有一个 vector :

std::vector<uint16_t> free_ids;

我需要我的 GameObject 类的 operator==。当一个对象被创建时,它将从 vector 接收到免费的 id,因此它将从它“移动”到对象。它将像这样简单地获取值:

void init(void)
{
for(uint64_t i=0; i<30; ++i)
free_ids.push_back(i);
}

所以我有成功使用它的类。

class GameObject
{
public:
static std::vector<GameObject*> created_objects; // all objects created ever
static constexpr auto& CO = created_objects;

GameObject()
{
id = free_ids.front(); // get id from vector
free_ids.erase(free_ids.begin()); // delete it from vector
CO.push_back(this); // add address to all object created ever
}

GameObject(const GameObject& other)
{
// copy attributes I didn't include in this code
id = free_ids.front();
free_ids.erase(free_ids.begin());
CO.push_back(this);
}

~GameObject()
{
free_ids.push_back(id); // return id to vector
CO.erase(std::remove(CO.begin(), CO.end(), this), CO.end());
// remove object by address
}

bool operator==(const GameObject& other)
{
return id==other.id; // check if id is the same (if it's the same object)
}

const uint64_t& get_id(void) const
{
return id;
}

private:
uint64_t id;
};

std::vector<GameObject*> GameObject::created_objects;

我希望拥有 GameObject 类型的全局常量, 但它会导致段错误,因为 init()之前从未被调用过main()打电话

//const GameObject Progenitor; //segmentation fault, free_ids not initialized yet

还有一个示例程序:

int main()
{
srand(time(NULL));

init();

const GameObject Progenitor; // It's temporary replacement for my global

std::vector<GameObject> clone_army;
clone_army.reserve(20); // GameObjects can't be reallocated bacause
// their addresses are stored in class static vector
auto& CA = clone_army;

for(uint64_t i=0; i<20; ++i)
CA.push_back(Progenitor);

std::cout << "Storage used. Unoccupied ids: " << std::endl;
for(auto& x : free_ids)
std::cout << x << std::endl;
auto& victim = clone_army[rand()%20]; // it's much more compilated

std::cout << "\nOne will die. Victim is... clone no. " << victim.get_id() << std::endl;
CA.erase(std::remove(CA.begin(), CA.end(), victim), CA.end());
// need to remove victim by value, operator== involved

std::cout << "\nProgenitor id: ";

for(auto& x : GameObject::CO)
std::cout << x->get_id() << std::endl;
}

负责的标题:

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>

我的问题是,如何初始化std::vector<uint16_t> free_ids; - 这不可能是 const , 在 GameObject 的任何对象之前类(class)曾经被创造过吗?(将有许多不同继承类的祖先,我将使用(已经是但想重新排列代码)类似模板的对象来创建实时克隆)

最佳答案

虽然创建一个在其构造函数中初始化 vector 的静态对象很容易,但您永远不能保证这个静态对象将在不同翻译单元中的所有其他静态对象之前被初始化。

相反,您可能会采用单例类型的东西。在这个单例中,您可以公开 get_id 和 release_id 函数。从提供的代码来看,我认为您不需要我为您勾勒出这个单例,但如果您需要,请随时提出要求。

关于c++ - 在创建类的常量对象之前初始化非常量变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34666339/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com