Codechange: replace 'new PoolItem(...' with 'PoolItem::Create(...'

This commit is contained in:
Rubidium
2026-01-03 16:04:32 +01:00
committed by rubidium42
parent bc842811fc
commit 2fcd4e189a
49 changed files with 162 additions and 114 deletions
+3 -3
View File
@@ -275,8 +275,8 @@ CommandCost CmdBuildAircraft(DoCommandFlags flags, TileIndex tile, const Engine
tile = st->airport.GetHangarTile(st->airport.GetHangarNum(tile)); tile = st->airport.GetHangarTile(st->airport.GetHangarNum(tile));
if (flags.Test(DoCommandFlag::Execute)) { if (flags.Test(DoCommandFlag::Execute)) {
Aircraft *v = new Aircraft(); // aircraft Aircraft *v = Aircraft::Create(); // aircraft
Aircraft *u = new Aircraft(); // shadow Aircraft *u = Aircraft::Create(); // shadow
*ret = v; *ret = v;
v->direction = DIR_SE; v->direction = DIR_SE;
@@ -366,7 +366,7 @@ CommandCost CmdBuildAircraft(DoCommandFlags flags, TileIndex tile, const Engine
/* Aircraft with 3 vehicles (chopper)? */ /* Aircraft with 3 vehicles (chopper)? */
if (v->subtype == AIR_HELICOPTER) { if (v->subtype == AIR_HELICOPTER) {
Aircraft *w = new Aircraft(); Aircraft *w = Aircraft::Create();
w->engine_type = e->index; w->engine_type = e->index;
w->direction = DIR_N; w->direction = DIR_N;
w->owner = _current_company; w->owner = _current_company;
+3 -3
View File
@@ -82,7 +82,7 @@ uint CountArticulatedParts(EngineID engine_type, bool purchase_window)
std::unique_ptr<Vehicle> v; std::unique_ptr<Vehicle> v;
if (!purchase_window) { if (!purchase_window) {
v = std::make_unique<Vehicle>(); v = std::unique_ptr<Vehicle>(Vehicle::Create());
v->engine_type = engine_type; v->engine_type = engine_type;
v->owner = _current_company; v->owner = _current_company;
} }
@@ -357,7 +357,7 @@ void AddArticulatedParts(Vehicle *first)
case VEH_TRAIN: { case VEH_TRAIN: {
Train *front = Train::From(first); Train *front = Train::From(first);
Train *t = new Train(); Train *t = Train::Create();
v->SetNext(t); v->SetNext(t);
v = t; v = t;
@@ -381,7 +381,7 @@ void AddArticulatedParts(Vehicle *first)
case VEH_ROAD: { case VEH_ROAD: {
RoadVehicle *front = RoadVehicle::From(first); RoadVehicle *front = RoadVehicle::From(first);
RoadVehicle *rv = new RoadVehicle(); RoadVehicle *rv = RoadVehicle::Create();
v->SetNext(rv); v->SetNext(rv);
v = rv; v = rv;
+1 -1
View File
@@ -109,7 +109,7 @@ CommandCost AddEngineReplacement(EngineRenewList *erl, EngineID old_engine, Engi
if (flags.Test(DoCommandFlag::Execute)) { if (flags.Test(DoCommandFlag::Execute)) {
/* Insert before the first element */ /* Insert before the first element */
*erl = new EngineRenew(old_engine, new_engine, group, replace_when_old, *erl); *erl = EngineRenew::Create(old_engine, new_engine, group, replace_when_old, *erl);
} }
return CommandCost(); return CommandCost();
+11
View File
@@ -269,6 +269,17 @@ struct SpecializedStation : public BaseStation {
return GetIfValid(GetStationIndex(tile)); return GetIfValid(GetStationIndex(tile));
} }
/**
* Creates a new T-object in the station pool.
* @param args... The arguments to the constructor.
* @return The created object.
*/
template <typename... Targs>
static inline T *Create(Targs &&... args)
{
return BaseStation::Create<T>(std::forward<Targs&&>(args)...);
}
/** /**
* Converts a BaseStation to SpecializedStation with type checking. * Converts a BaseStation to SpecializedStation with type checking.
* @param st BaseStation pointer * @param st BaseStation pointer
+1 -1
View File
@@ -96,7 +96,7 @@ CargoPacket *CargoPacket::Split(uint new_size)
if (!CargoPacket::CanAllocateItem()) return nullptr; if (!CargoPacket::CanAllocateItem()) return nullptr;
Money fs = this->GetFeederShare(new_size); Money fs = this->GetFeederShare(new_size);
CargoPacket *cp_new = new CargoPacket(new_size, fs, *this); CargoPacket *cp_new = CargoPacket::Create(new_size, fs, *this);
this->feeder_share -= fs; this->feeder_share -= fs;
this->count -= new_size; this->count -= new_size;
return cp_new; return cp_new;
+1 -1
View File
@@ -605,7 +605,7 @@ Company *DoStartupNewCompany(bool is_ai, CompanyID company = CompanyID::Invalid(
Company *c; Company *c;
if (company == CompanyID::Invalid()) { if (company == CompanyID::Invalid()) {
c = new Company(STR_SV_UNNAMED, is_ai); c = Company::Create(STR_SV_UNNAMED, is_ai);
} else { } else {
if (Company::IsValidID(company)) return nullptr; if (Company::IsValidID(company)) return nullptr;
c = new (company) Company(STR_SV_UNNAMED, is_ai); c = new (company) Company(STR_SV_UNNAMED, is_ai);
+15 -10
View File
@@ -288,16 +288,8 @@ public:
/** Type of the pool this item is going to be part of */ /** Type of the pool this item is going to be part of */
typedef struct Pool<Titem, Tindex, Tgrowth_step, Tpool_type, Tcache> Pool; typedef struct Pool<Titem, Tindex, Tgrowth_step, Tpool_type, Tcache> Pool;
/** /** Do not use new PoolItem, but rather PoolItem::Create. */
* Allocates space for new Titem inline void *operator new(size_t) = delete;
* @param size size of Titem
* @return pointer to allocated memory
* @note can never fail (return nullptr), use CanAllocate() to check first!
*/
inline void *operator new(size_t size)
{
return Tpool->GetNew(size);
}
/** /**
* Marks Titem as free. Its memory is released * Marks Titem as free. Its memory is released
@@ -347,6 +339,19 @@ public:
} }
/**
* Creates a new T-object in the associated pool.
* @param args... The arguments to the constructor.
* @return The created object.
*/
template <typename T = Titem, typename... Targs>
requires std::is_base_of_v<Titem, T>
static inline T *Create(Targs &&... args)
{
void *data = Tpool->GetNew(sizeof(T));
return ::new (data) T(std::forward<Targs&&>(args)...);
}
/** Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function() */ /** Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function() */
/** /**
+14 -14
View File
@@ -569,8 +569,8 @@ static bool DisasterTick_Big_Ufo(DisasterVehicle *v)
delete v; delete v;
return false; return false;
} }
DisasterVehicle *u = new DisasterVehicle(-6 * (int)TILE_SIZE, v->y_pos, DIR_SW, ST_BIG_UFO_DESTROYER, v->index); DisasterVehicle *u = DisasterVehicle::Create(-6 * (int)TILE_SIZE, v->y_pos, DIR_SW, ST_BIG_UFO_DESTROYER, v->index);
DisasterVehicle *w = new DisasterVehicle(-6 * (int)TILE_SIZE, v->y_pos, DIR_SW, ST_BIG_UFO_DESTROYER_SHADOW); DisasterVehicle *w = DisasterVehicle::Create(-6 * (int)TILE_SIZE, v->y_pos, DIR_SW, ST_BIG_UFO_DESTROYER_SHADOW);
u->SetNext(w); u->SetNext(w);
} else if (v->state == 0) { } else if (v->state == 0) {
int x = TileX(v->dest_tile) * TILE_SIZE; int x = TileX(v->dest_tile) * TILE_SIZE;
@@ -743,9 +743,9 @@ static void Disaster_Zeppeliner_Init()
} }
} }
DisasterVehicle *v = new DisasterVehicle(x, 0, DIR_SE, ST_ZEPPELINER); DisasterVehicle *v = DisasterVehicle::Create(x, 0, DIR_SE, ST_ZEPPELINER);
/* Allocate shadow */ /* Allocate shadow */
DisasterVehicle *u = new DisasterVehicle(x, 0, DIR_SE, ST_ZEPPELINER_SHADOW); DisasterVehicle *u = DisasterVehicle::Create(x, 0, DIR_SE, ST_ZEPPELINER_SHADOW);
v->SetNext(u); v->SetNext(u);
} }
@@ -759,11 +759,11 @@ static void Disaster_Small_Ufo_Init()
if (!Vehicle::CanAllocateItem(2)) return; if (!Vehicle::CanAllocateItem(2)) return;
int x = TileX(RandomTile()) * TILE_SIZE + TILE_SIZE / 2; int x = TileX(RandomTile()) * TILE_SIZE + TILE_SIZE / 2;
DisasterVehicle *v = new DisasterVehicle(x, 0, DIR_SE, ST_SMALL_UFO); DisasterVehicle *v = DisasterVehicle::Create(x, 0, DIR_SE, ST_SMALL_UFO);
v->dest_tile = TileXY(Map::SizeX() / 2, Map::SizeY() / 2); v->dest_tile = TileXY(Map::SizeX() / 2, Map::SizeY() / 2);
/* Allocate shadow */ /* Allocate shadow */
DisasterVehicle *u = new DisasterVehicle(x, 0, DIR_SE, ST_SMALL_UFO_SHADOW); DisasterVehicle *u = DisasterVehicle::Create(x, 0, DIR_SE, ST_SMALL_UFO_SHADOW);
v->SetNext(u); v->SetNext(u);
} }
@@ -788,8 +788,8 @@ static void Disaster_Airplane_Init()
int x = (Map::SizeX() + 9) * TILE_SIZE - 1; int x = (Map::SizeX() + 9) * TILE_SIZE - 1;
int y = TileY(found->location.tile) * TILE_SIZE + 37; int y = TileY(found->location.tile) * TILE_SIZE + 37;
DisasterVehicle *v = new DisasterVehicle(x, y, DIR_NE, ST_AIRPLANE); DisasterVehicle *v = DisasterVehicle::Create(x, y, DIR_NE, ST_AIRPLANE);
DisasterVehicle *u = new DisasterVehicle(x, y, DIR_NE, ST_AIRPLANE_SHADOW); DisasterVehicle *u = DisasterVehicle::Create(x, y, DIR_NE, ST_AIRPLANE_SHADOW);
v->SetNext(u); v->SetNext(u);
} }
@@ -813,11 +813,11 @@ static void Disaster_Helicopter_Init()
int x = -16 * (int)TILE_SIZE; int x = -16 * (int)TILE_SIZE;
int y = TileY(found->location.tile) * TILE_SIZE + 37; int y = TileY(found->location.tile) * TILE_SIZE + 37;
DisasterVehicle *v = new DisasterVehicle(x, y, DIR_SW, ST_HELICOPTER); DisasterVehicle *v = DisasterVehicle::Create(x, y, DIR_SW, ST_HELICOPTER);
DisasterVehicle *u = new DisasterVehicle(x, y, DIR_SW, ST_HELICOPTER_SHADOW); DisasterVehicle *u = DisasterVehicle::Create(x, y, DIR_SW, ST_HELICOPTER_SHADOW);
v->SetNext(u); v->SetNext(u);
DisasterVehicle *w = new DisasterVehicle(x, y, DIR_SW, ST_HELICOPTER_ROTORS); DisasterVehicle *w = DisasterVehicle::Create(x, y, DIR_SW, ST_HELICOPTER_ROTORS);
u->SetNext(w); u->SetNext(w);
} }
@@ -831,11 +831,11 @@ static void Disaster_Big_Ufo_Init()
int x = TileX(RandomTile()) * TILE_SIZE + TILE_SIZE / 2; int x = TileX(RandomTile()) * TILE_SIZE + TILE_SIZE / 2;
int y = Map::MaxX() * TILE_SIZE - 1; int y = Map::MaxX() * TILE_SIZE - 1;
DisasterVehicle *v = new DisasterVehicle(x, y, DIR_NW, ST_BIG_UFO); DisasterVehicle *v = DisasterVehicle::Create(x, y, DIR_NW, ST_BIG_UFO);
v->dest_tile = TileXY(Map::SizeX() / 2, Map::SizeY() / 2); v->dest_tile = TileXY(Map::SizeX() / 2, Map::SizeY() / 2);
/* Allocate shadow */ /* Allocate shadow */
DisasterVehicle *u = new DisasterVehicle(x, y, DIR_NW, ST_BIG_UFO_SHADOW); DisasterVehicle *u = DisasterVehicle::Create(x, y, DIR_NW, ST_BIG_UFO_SHADOW);
v->SetNext(u); v->SetNext(u);
} }
@@ -859,7 +859,7 @@ static void Disaster_Submarine_Init(DisasterSubType subtype)
} }
if (!IsWaterTile(TileVirtXY(x, y))) return; if (!IsWaterTile(TileVirtXY(x, y))) return;
new DisasterVehicle(x, y, dir, subtype); DisasterVehicle::Create(x, y, dir, subtype);
} }
/* Curious submarine #1, just floats around */ /* Curious submarine #1, just floats around */
+1 -1
View File
@@ -1259,7 +1259,7 @@ void PrepareUnload(Vehicle *front_v)
* limit in number of CargoPayments. Can't go wrong. */ * limit in number of CargoPayments. Can't go wrong. */
static_assert(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE); static_assert(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE);
assert(CargoPayment::CanAllocateItem()); assert(CargoPayment::CanAllocateItem());
front_v->cargo_payment = new CargoPayment(front_v); front_v->cargo_payment = CargoPayment::Create(front_v);
std::vector<StationID> next_station; std::vector<StationID> next_station;
front_v->GetNextStoppingStation(next_station); front_v->GetNextStoppingStation(next_station);
+1 -1
View File
@@ -567,7 +567,7 @@ EffectVehicle *CreateEffectVehicle(int x, int y, int z, EffectVehicleType type)
{ {
if (!Vehicle::CanAllocateItem()) return nullptr; if (!Vehicle::CanAllocateItem()) return nullptr;
EffectVehicle *v = new EffectVehicle(); EffectVehicle *v = EffectVehicle::Create();
v->subtype = type; v->subtype = type;
v->x_pos = x; v->x_pos = x;
v->y_pos = y; v->y_pos = y;
+1 -1
View File
@@ -85,7 +85,7 @@ std::tuple<CommandCost, GoalID> CmdCreateGoal(DoCommandFlags flags, CompanyID co
if (!Goal::IsValidGoalDestination(company, type, dest)) return { CMD_ERROR, GoalID::Invalid() }; if (!Goal::IsValidGoalDestination(company, type, dest)) return { CMD_ERROR, GoalID::Invalid() };
if (flags.Test(DoCommandFlag::Execute)) { if (flags.Test(DoCommandFlag::Execute)) {
Goal *g = new Goal(type, dest, company, text); Goal *g = Goal::Create(type, dest, company, text);
if (g->company == CompanyID::Invalid()) { if (g->company == CompanyID::Invalid()) {
InvalidateWindowClassesData(WC_GOALS_LIST); InvalidateWindowClassesData(WC_GOALS_LIST);
+1 -1
View File
@@ -349,7 +349,7 @@ std::tuple<CommandCost, GroupID> CmdCreateGroup(DoCommandFlags flags, VehicleTyp
} }
if (flags.Test(DoCommandFlag::Execute)) { if (flags.Test(DoCommandFlag::Execute)) {
Group *g = new Group(_current_company, vt); Group *g = Group::Create(_current_company, vt);
Company *c = Company::Get(g->owner); Company *c = Company::Get(g->owner);
g->number = c->freegroups.UseID(c->freegroups.NextID()); g->number = c->freegroups.UseID(c->freegroups.NextID());
+1 -1
View File
@@ -2043,7 +2043,7 @@ static CommandCost CreateNewIndustryHelper(TileIndex tile, IndustryType type, Do
if (!Industry::CanAllocateItem()) return CommandCost(STR_ERROR_TOO_MANY_INDUSTRIES); if (!Industry::CanAllocateItem()) return CommandCost(STR_ERROR_TOO_MANY_INDUSTRIES);
if (flags.Test(DoCommandFlag::Execute)) { if (flags.Test(DoCommandFlag::Execute)) {
*ip = new Industry(tile); *ip = Industry::Create(tile);
if (!custom_shape_check) CheckIfCanLevelIndustryPlatform(tile, {DoCommandFlag::NoWater, DoCommandFlag::Execute}, layout); if (!custom_shape_check) CheckIfCanLevelIndustryPlatform(tile, {DoCommandFlag::NoWater, DoCommandFlag::Execute}, layout);
DoCreateNewIndustry(*ip, tile, type, layout, layout_index, t, founder, random_initial_bits); DoCreateNewIndustry(*ip, tile, type, layout, layout_index, t, founder, random_initial_bits);
} }
+2 -2
View File
@@ -60,7 +60,7 @@ std::tuple<CommandCost, LeagueTableID> CmdCreateLeagueTable(DoCommandFlags flags
if (title.empty()) return { CMD_ERROR, LeagueTableID::Invalid() }; if (title.empty()) return { CMD_ERROR, LeagueTableID::Invalid() };
if (flags.Test(DoCommandFlag::Execute)) { if (flags.Test(DoCommandFlag::Execute)) {
LeagueTable *lt = new LeagueTable(title, header, footer); LeagueTable *lt = LeagueTable::Create(title, header, footer);
return { CommandCost(), lt->index }; return { CommandCost(), lt->index };
} }
@@ -89,7 +89,7 @@ std::tuple<CommandCost, LeagueTableElementID> CmdCreateLeagueTableElement(DoComm
if (company != CompanyID::Invalid() && !Company::IsValidID(company)) return { CMD_ERROR, LeagueTableElementID::Invalid() }; if (company != CompanyID::Invalid() && !Company::IsValidID(company)) return { CMD_ERROR, LeagueTableElementID::Invalid() };
if (flags.Test(DoCommandFlag::Execute)) { if (flags.Test(DoCommandFlag::Execute)) {
LeagueTableElement *lte = new LeagueTableElement(table, rating, company, text, score, link); LeagueTableElement *lte = LeagueTableElement::Create(table, rating, company, text, score, link);
InvalidateWindowData(WC_COMPANY_LEAGUE, table); InvalidateWindowData(WC_COMPANY_LEAGUE, table);
return { CommandCost(), lte->index }; return { CommandCost(), lte->index };
} }
+1 -1
View File
@@ -43,7 +43,7 @@ void LinkGraphSchedule::SpawnNext()
assert(next == LinkGraph::Get(next->index)); assert(next == LinkGraph::Get(next->index));
this->schedule.pop_front(); this->schedule.pop_front();
if (LinkGraphJob::CanAllocateItem()) { if (LinkGraphJob::CanAllocateItem()) {
LinkGraphJob *job = new LinkGraphJob(*next); LinkGraphJob *job = LinkGraphJob::Create(*next);
job->SpawnThread(); job->SpawnThread();
this->running.push_back(job); this->running.push_back(job);
} else { } else {
+2 -2
View File
@@ -568,7 +568,7 @@ NetworkAddress ParseConnectionString(std::string_view connection_string, uint16_
/* Register the login */ /* Register the login */
_network_clients_connected++; _network_clients_connected++;
ServerNetworkGameSocketHandler *cs = new ServerNetworkGameSocketHandler(s); ServerNetworkGameSocketHandler *cs = ServerNetworkGameSocketHandler::Create(s);
cs->client_address = address; // Save the IP of the client cs->client_address = address; // Save the IP of the client
InvalidateWindowData(WC_CLIENT_LIST, 0); InvalidateWindowData(WC_CLIENT_LIST, 0);
@@ -836,7 +836,7 @@ static void NetworkInitGameInfo()
/* There should be always space for the server. */ /* There should be always space for the server. */
assert(NetworkClientInfo::CanAllocateItem()); assert(NetworkClientInfo::CanAllocateItem());
NetworkClientInfo *ci = new NetworkClientInfo(CLIENT_ID_SERVER); NetworkClientInfo *ci = NetworkClientInfo::Create(CLIENT_ID_SERVER);
ci->client_playas = COMPANY_SPECTATOR; ci->client_playas = COMPANY_SPECTATOR;
ci->client_name = _settings_client.network.client_name; ci->client_name = _settings_client.network.client_name;
+1 -1
View File
@@ -115,7 +115,7 @@ ServerNetworkAdminSocketHandler::~ServerNetworkAdminSocketHandler()
*/ */
/* static */ void ServerNetworkAdminSocketHandler::AcceptConnection(SOCKET s, const NetworkAddress &address) /* static */ void ServerNetworkAdminSocketHandler::AcceptConnection(SOCKET s, const NetworkAddress &address)
{ {
ServerNetworkAdminSocketHandler *as = new ServerNetworkAdminSocketHandler(s); ServerNetworkAdminSocketHandler *as = ServerNetworkAdminSocketHandler::Create(s);
as->address = address; // Save the IP of the client as->address = address; // Save the IP of the client
} }
+1 -1
View File
@@ -565,7 +565,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CLIENT_INFO(Pac
if (!NetworkClientInfo::CanAllocateItem()) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (!NetworkClientInfo::CanAllocateItem()) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
/* We don't have this client_id yet, find an empty client_id, and put the data there */ /* We don't have this client_id yet, find an empty client_id, and put the data there */
ci = new NetworkClientInfo(client_id); ci = NetworkClientInfo::Create(client_id);
ci->client_playas = playas; ci->client_playas = playas;
if (client_id == _network_own_client_id) this->SetInfo(ci); if (client_id == _network_own_client_id) this->SetInfo(ci);
+1 -1
View File
@@ -914,7 +914,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_IDENTIFY(Packet
} }
assert(NetworkClientInfo::CanAllocateItem()); assert(NetworkClientInfo::CanAllocateItem());
NetworkClientInfo *ci = new NetworkClientInfo(this->client_id); NetworkClientInfo *ci = NetworkClientInfo::Create(this->client_id);
this->SetInfo(ci); this->SetInfo(ci);
ci->join_date = TimerGameEconomy::date; ci->join_date = TimerGameEconomy::date;
ci->client_name = std::move(client_name); ci->client_name = std::move(client_name);
+1 -1
View File
@@ -263,7 +263,7 @@ Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16_t internal_id
size_t engine_pool_size = Engine::GetPoolSize(); size_t engine_pool_size = Engine::GetPoolSize();
/* ... it's not, so create a new one based off an existing engine */ /* ... it's not, so create a new one based off an existing engine */
Engine *e = new Engine(type, internal_id); Engine *e = Engine::Create(type, internal_id);
e->grf_prop.SetGRFFile(file); e->grf_prop.SetGRFFile(file);
/* Reserve the engine slot */ /* Reserve the engine slot */
+7 -7
View File
@@ -286,7 +286,7 @@ static const SpriteGroup *GetCallbackResultGroup(uint16_t value)
/* Result value is not present, so make it and add to cache. */ /* Result value is not present, so make it and add to cache. */
assert(CallbackResultSpriteGroup::CanAllocateItem()); assert(CallbackResultSpriteGroup::CanAllocateItem());
const SpriteGroup *group = new CallbackResultSpriteGroup(value); const SpriteGroup *group = CallbackResultSpriteGroup::Create(value);
it = _cached_callback_groups.emplace(it, value, group->index); it = _cached_callback_groups.emplace(it, value, group->index);
return group; return group;
} }
@@ -330,7 +330,7 @@ static const SpriteGroup *CreateGroupFromGroupID(GrfSpecFeature feature, uint8_t
assert(spriteset_start + num_sprites <= _cur_gps.spriteid); assert(spriteset_start + num_sprites <= _cur_gps.spriteid);
assert(ResultSpriteGroup::CanAllocateItem()); assert(ResultSpriteGroup::CanAllocateItem());
return new ResultSpriteGroup(spriteset_start, num_sprites); return ResultSpriteGroup::Create(spriteset_start, num_sprites);
} }
/* Action 0x02 */ /* Action 0x02 */
@@ -374,7 +374,7 @@ static void NewSpriteGroup(ByteReader &buf)
uint8_t varsize; uint8_t varsize;
assert(DeterministicSpriteGroup::CanAllocateItem()); assert(DeterministicSpriteGroup::CanAllocateItem());
DeterministicSpriteGroup *group = new DeterministicSpriteGroup(); DeterministicSpriteGroup *group = DeterministicSpriteGroup::Create();
group->nfo_line = _cur_gps.nfo_line; group->nfo_line = _cur_gps.nfo_line;
act_group = group; act_group = group;
group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF; group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
@@ -494,7 +494,7 @@ static void NewSpriteGroup(ByteReader &buf)
case 0x84: // Relative scope case 0x84: // Relative scope
{ {
assert(RandomizedSpriteGroup::CanAllocateItem()); assert(RandomizedSpriteGroup::CanAllocateItem());
RandomizedSpriteGroup *group = new RandomizedSpriteGroup(); RandomizedSpriteGroup *group = RandomizedSpriteGroup::Create();
group->nfo_line = _cur_gps.nfo_line; group->nfo_line = _cur_gps.nfo_line;
act_group = group; act_group = group;
group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF; group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
@@ -593,7 +593,7 @@ static void NewSpriteGroup(ByteReader &buf)
} }
assert(RealSpriteGroup::CanAllocateItem()); assert(RealSpriteGroup::CanAllocateItem());
RealSpriteGroup *group = new RealSpriteGroup(); RealSpriteGroup *group = RealSpriteGroup::Create();
group->nfo_line = _cur_gps.nfo_line; group->nfo_line = _cur_gps.nfo_line;
act_group = group; act_group = group;
@@ -622,7 +622,7 @@ static void NewSpriteGroup(ByteReader &buf)
uint8_t num_building_sprites = std::max((uint8_t)1, type); uint8_t num_building_sprites = std::max((uint8_t)1, type);
assert(TileLayoutSpriteGroup::CanAllocateItem()); assert(TileLayoutSpriteGroup::CanAllocateItem());
TileLayoutSpriteGroup *group = new TileLayoutSpriteGroup(); TileLayoutSpriteGroup *group = TileLayoutSpriteGroup::Create();
group->nfo_line = _cur_gps.nfo_line; group->nfo_line = _cur_gps.nfo_line;
act_group = group; act_group = group;
@@ -638,7 +638,7 @@ static void NewSpriteGroup(ByteReader &buf)
} }
assert(IndustryProductionSpriteGroup::CanAllocateItem()); assert(IndustryProductionSpriteGroup::CanAllocateItem());
IndustryProductionSpriteGroup *group = new IndustryProductionSpriteGroup(); IndustryProductionSpriteGroup *group = IndustryProductionSpriteGroup::Create();
group->nfo_line = _cur_gps.nfo_line; group->nfo_line = _cur_gps.nfo_line;
act_group = group; act_group = group;
group->version = type; group->version = type;
+1 -1
View File
@@ -213,7 +213,7 @@ uint32_t AirportResolverObject::GetDebugID() const
/* Create storage on first modification. */ /* Create storage on first modification. */
uint32_t grfid = (this->ro.grffile != nullptr) ? this->ro.grffile->grfid : 0; uint32_t grfid = (this->ro.grffile != nullptr) ? this->ro.grffile->grfid : 0;
assert(PersistentStorage::CanAllocateItem()); assert(PersistentStorage::CanAllocateItem());
this->st->airport.psa = new PersistentStorage(grfid, GSF_AIRPORTS, this->st->airport.tile); this->st->airport.psa = PersistentStorage::Create(grfid, GSF_AIRPORTS, this->st->airport.tile);
} }
this->st->airport.psa->StoreValue(pos, value); this->st->airport.psa->StoreValue(pos, value);
} }
+1 -1
View File
@@ -448,7 +448,7 @@ static uint32_t GetCountAndDistanceOfClosestInstance(const ResolverObject &objec
/* Create storage on first modification. */ /* Create storage on first modification. */
const IndustrySpec *indsp = GetIndustrySpec(this->industry->type); const IndustrySpec *indsp = GetIndustrySpec(this->industry->type);
assert(PersistentStorage::CanAllocateItem()); assert(PersistentStorage::CanAllocateItem());
this->industry->psa = new PersistentStorage(indsp->grf_prop.grfid, GSF_INDUSTRIES, this->industry->location.tile); this->industry->psa = PersistentStorage::Create(indsp->grf_prop.grfid, GSF_INDUSTRIES, this->industry->location.tile);
} }
this->industry->psa->StoreValue(pos, value); this->industry->psa->StoreValue(pos, value);
+34 -14
View File
@@ -59,10 +59,30 @@ public:
}; };
/**
* Class defining some overloaded accessors so we don't have to cast SpriteGroups that often
*/
template <class T>
struct SpecializedSpriteGroup : public SpriteGroup {
inline SpecializedSpriteGroup() : SpriteGroup() {}
/**
* Creates a new T-object in the SpriteGroup pool.
* @param args... The arguments to the constructor.
* @return The created object.
*/
template <typename... Targs>
static inline T *Create(Targs &&... args)
{
return SpriteGroup::Create<T>(std::forward<Targs&&>(args)...);
}
};
/* 'Real' sprite groups contain a list of other result or callback sprite /* 'Real' sprite groups contain a list of other result or callback sprite
* groups. */ * groups. */
struct RealSpriteGroup : SpriteGroup { struct RealSpriteGroup : SpecializedSpriteGroup<RealSpriteGroup> {
RealSpriteGroup() : SpriteGroup() {} RealSpriteGroup() : SpecializedSpriteGroup<RealSpriteGroup>() {}
/* Loaded = in motion, loading = not moving /* Loaded = in motion, loading = not moving
* Each group contains several spritesets, for various loading stages */ * Each group contains several spritesets, for various loading stages */
@@ -156,8 +176,8 @@ struct DeterministicSpriteGroupRange {
}; };
struct DeterministicSpriteGroup : SpriteGroup { struct DeterministicSpriteGroup : SpecializedSpriteGroup<DeterministicSpriteGroup> {
DeterministicSpriteGroup() : SpriteGroup() {} DeterministicSpriteGroup() : SpecializedSpriteGroup<DeterministicSpriteGroup>() {}
VarSpriteGroupScope var_scope{}; VarSpriteGroupScope var_scope{};
DeterministicSpriteGroupSize size{}; DeterministicSpriteGroupSize size{};
@@ -178,8 +198,8 @@ enum RandomizedSpriteGroupCompareMode : uint8_t {
RSG_CMP_ALL, RSG_CMP_ALL,
}; };
struct RandomizedSpriteGroup : SpriteGroup { struct RandomizedSpriteGroup : SpecializedSpriteGroup<RandomizedSpriteGroup> {
RandomizedSpriteGroup() : SpriteGroup() {} RandomizedSpriteGroup() : SpecializedSpriteGroup<RandomizedSpriteGroup>() {}
VarSpriteGroupScope var_scope{}; ///< Take this object: VarSpriteGroupScope var_scope{}; ///< Take this object:
@@ -198,12 +218,12 @@ protected:
/* This contains a callback result. A failed callback has a value of /* This contains a callback result. A failed callback has a value of
* CALLBACK_FAILED */ * CALLBACK_FAILED */
struct CallbackResultSpriteGroup : SpriteGroup { struct CallbackResultSpriteGroup : SpecializedSpriteGroup<CallbackResultSpriteGroup> {
/** /**
* Creates a spritegroup representing a callback result * Creates a spritegroup representing a callback result
* @param value The value that was used to represent this callback result * @param value The value that was used to represent this callback result
*/ */
explicit CallbackResultSpriteGroup(CallbackResult value) : SpriteGroup(), result(value) {} explicit CallbackResultSpriteGroup(CallbackResult value) : SpecializedSpriteGroup<CallbackResultSpriteGroup>(), result(value) {}
CallbackResult result = 0; CallbackResult result = 0;
@@ -214,14 +234,14 @@ protected:
/* A result sprite group returns the first SpriteID and the number of /* A result sprite group returns the first SpriteID and the number of
* sprites in the set */ * sprites in the set */
struct ResultSpriteGroup : SpriteGroup { struct ResultSpriteGroup : SpecializedSpriteGroup<ResultSpriteGroup> {
/** /**
* Creates a spritegroup representing a sprite number result. * Creates a spritegroup representing a sprite number result.
* @param sprite The sprite number. * @param sprite The sprite number.
* @param num_sprites The number of sprites per set. * @param num_sprites The number of sprites per set.
* @return A spritegroup representing the sprite number result. * @return A spritegroup representing the sprite number result.
*/ */
ResultSpriteGroup(SpriteID sprite, uint8_t num_sprites) : SpriteGroup(), num_sprites(num_sprites), sprite(sprite) {} ResultSpriteGroup(SpriteID sprite, uint8_t num_sprites) : SpecializedSpriteGroup<ResultSpriteGroup>(), num_sprites(num_sprites), sprite(sprite) {}
uint8_t num_sprites = 0; uint8_t num_sprites = 0;
SpriteID sprite = 0; SpriteID sprite = 0;
@@ -233,8 +253,8 @@ protected:
/** /**
* Action 2 sprite layout for houses, industry tiles, objects and airport tiles. * Action 2 sprite layout for houses, industry tiles, objects and airport tiles.
*/ */
struct TileLayoutSpriteGroup : SpriteGroup { struct TileLayoutSpriteGroup : SpecializedSpriteGroup<TileLayoutSpriteGroup> {
TileLayoutSpriteGroup() : SpriteGroup() {} TileLayoutSpriteGroup() : SpecializedSpriteGroup<TileLayoutSpriteGroup>() {}
NewGRFSpriteLayout dts{}; NewGRFSpriteLayout dts{};
@@ -244,8 +264,8 @@ protected:
ResolverResult Resolve(ResolverObject &) const override { return this; } ResolverResult Resolve(ResolverObject &) const override { return this; }
}; };
struct IndustryProductionSpriteGroup : SpriteGroup { struct IndustryProductionSpriteGroup : SpecializedSpriteGroup<IndustryProductionSpriteGroup> {
IndustryProductionSpriteGroup() : SpriteGroup() {} IndustryProductionSpriteGroup() : SpecializedSpriteGroup<IndustryProductionSpriteGroup>() {}
uint8_t version = 0; ///< Production callback version used, or 0xFF if marked invalid uint8_t version = 0; ///< Production callback version used, or 0xFF if marked invalid
uint8_t num_input = 0; ///< How many subtract_input values are valid uint8_t num_input = 0; ///< How many subtract_input values are valid
+1 -1
View File
@@ -156,7 +156,7 @@ static uint16_t TownHistoryHelper(const Town *t, CargoLabel label, uint period,
/* Create a new storage. */ /* Create a new storage. */
assert(PersistentStorage::CanAllocateItem()); assert(PersistentStorage::CanAllocateItem());
PersistentStorage *psa = new PersistentStorage(grfid, GSF_FAKE_TOWNS, this->t->xy); PersistentStorage *psa = PersistentStorage::Create(grfid, GSF_FAKE_TOWNS, this->t->xy);
psa->StoreValue(pos, value); psa->StoreValue(pos, value);
t->psa_list.push_back(psa); t->psa_list.push_back(psa);
} }
+1 -1
View File
@@ -90,7 +90,7 @@ void BuildObject(ObjectType type, TileIndex tile, CompanyID owner, Town *town, u
const ObjectSpec *spec = ObjectSpec::Get(type); const ObjectSpec *spec = ObjectSpec::Get(type);
TileArea ta(tile, GB(spec->size, HasBit(view, 0) ? 4 : 0, 4), GB(spec->size, HasBit(view, 0) ? 0 : 4, 4)); TileArea ta(tile, GB(spec->size, HasBit(view, 0) ? 4 : 0, 4), GB(spec->size, HasBit(view, 0) ? 0 : 4, 4));
Object *o = new Object(type, town == nullptr ? CalcClosestTownFromTile(tile) : town, ta, TimerGameCalendar::date, view); Object *o = Object::Create(type, town == nullptr ? CalcClosestTownFromTile(tile) : town, ta, TimerGameCalendar::date, view);
/* If nothing owns the object, the colour will be random. Otherwise /* If nothing owns the object, the colour will be random. Otherwise
* get the colour from the company's livery settings. */ * get the colour from the company's livery settings. */
+2 -2
View File
@@ -57,7 +57,7 @@ void OrderBackup::DoRestore(Vehicle *v)
if (this->clone != nullptr) { if (this->clone != nullptr) {
Command<CMD_CLONE_ORDER>::Do(DoCommandFlag::Execute, CO_SHARE, v->index, this->clone->index); Command<CMD_CLONE_ORDER>::Do(DoCommandFlag::Execute, CO_SHARE, v->index, this->clone->index);
} else if (!this->orders.empty() && OrderList::CanAllocateItem()) { } else if (!this->orders.empty() && OrderList::CanAllocateItem()) {
v->orders = new OrderList(std::move(this->orders), v); v->orders = OrderList::Create(std::move(this->orders), v);
/* Make sure buoys/oil rigs are updated in the station list. */ /* Make sure buoys/oil rigs are updated in the station list. */
InvalidateWindowClassesData(WC_STATION_LIST, 0); InvalidateWindowClassesData(WC_STATION_LIST, 0);
} }
@@ -89,7 +89,7 @@ void OrderBackup::DoRestore(Vehicle *v)
if (ob->user == user) delete ob; if (ob->user == user) delete ob;
} }
if (OrderBackup::CanAllocateItem()) { if (OrderBackup::CanAllocateItem()) {
new OrderBackup(v, user); OrderBackup::Create(v, user);
} }
} }
+3 -2
View File
@@ -45,12 +45,13 @@ private:
std::vector<Order> orders; ///< The actual orders if the vehicle was not a clone. std::vector<Order> orders; ///< The actual orders if the vehicle was not a clone.
uint32_t old_order_index = 0; uint32_t old_order_index = 0;
void DoRestore(Vehicle *v);
friend OrderBackupPool::PoolItem<&_order_backup_pool>;
/** Creation for savegame restoration. */ /** Creation for savegame restoration. */
OrderBackup() = default; OrderBackup() = default;
OrderBackup(const Vehicle *v, uint32_t user); OrderBackup(const Vehicle *v, uint32_t user);
void DoRestore(Vehicle *v);
public: public:
~OrderBackup(); ~OrderBackup();
+2 -2
View File
@@ -847,7 +847,7 @@ void InsertOrder(Vehicle *v, Order &&new_o, VehicleOrderID sel_ord)
{ {
/* Create new order and link in list */ /* Create new order and link in list */
if (v->orders == nullptr) { if (v->orders == nullptr) {
v->orders = new OrderList(std::move(new_o), v); v->orders = OrderList::Create(std::move(new_o), v);
} else { } else {
v->orders->InsertOrderAt(std::move(new_o), sel_ord); v->orders->InsertOrderAt(std::move(new_o), sel_ord);
} }
@@ -1604,7 +1604,7 @@ CommandCost CmdCloneOrder(DoCommandFlags flags, CloneOptions action, VehicleID v
} }
assert(OrderList::CanAllocateItem()); assert(OrderList::CanAllocateItem());
dst->orders = new OrderList(std::move(dst_orders), dst); dst->orders = OrderList::Create(std::move(dst_orders), dst);
InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS); InvalidateVehicleOrder(dst, VIWD_REMOVE_ALL_ORDERS);
+1 -1
View File
@@ -1008,7 +1008,7 @@ CommandCost CmdBuildTrainDepot(DoCommandFlags flags, TileIndex tile, RailType ra
if (rotate_existing_depot) { if (rotate_existing_depot) {
SetRailDepotExitDirection(tile, dir); SetRailDepotExitDirection(tile, dir);
} else { } else {
Depot *d = new Depot(tile); Depot *d = Depot::Create(tile);
MakeRailDepot(tile, _current_company, d->index, dir, railtype); MakeRailDepot(tile, _current_company, d->index, dir, railtype);
MakeDefaultName(d); MakeDefaultName(d);
+1 -1
View File
@@ -1176,7 +1176,7 @@ CommandCost CmdBuildRoadDepot(DoCommandFlags flags, TileIndex tile, RoadType rt,
if (rotate_existing_depot) { if (rotate_existing_depot) {
SetRoadDepotExitDirection(tile, dir); SetRoadDepotExitDirection(tile, dir);
} else { } else {
Depot *dep = new Depot(tile); Depot *dep = Depot::Create(tile);
MakeRoadDepot(tile, _current_company, dep->index, dir, rt); MakeRoadDepot(tile, _current_company, dep->index, dir, rt);
MakeDefaultName(dep); MakeDefaultName(dep);
+1 -1
View File
@@ -269,7 +269,7 @@ CommandCost CmdBuildRoadVehicle(DoCommandFlags flags, TileIndex tile, const Engi
if (flags.Test(DoCommandFlag::Execute)) { if (flags.Test(DoCommandFlag::Execute)) {
const RoadVehicleInfo *rvi = &e->VehInfo<RoadVehicleInfo>(); const RoadVehicleInfo *rvi = &e->VehInfo<RoadVehicleInfo>();
RoadVehicle *v = new RoadVehicle(); RoadVehicle *v = RoadVehicle::Create();
*ret = v; *ret = v;
v->direction = DiagDirToDir(GetRoadDepotDirection(tile)); v->direction = DiagDirToDir(GetRoadDepotDirection(tile));
v->owner = _current_company; v->owner = _current_company;
+3 -3
View File
@@ -961,7 +961,7 @@ bool AfterLoadGame()
/* From this version on there can be multiple road stops of the /* From this version on there can be multiple road stops of the
* same type per station. Convert the existing stops to the new * same type per station. Convert the existing stops to the new
* internal data structure. */ * internal data structure. */
RoadStop *rs = new RoadStop(t); RoadStop *rs = RoadStop::Create(t);
RoadStop **head = RoadStop **head =
IsTruckStop(t) ? &st->truck_stops : &st->bus_stops; IsTruckStop(t) ? &st->truck_stops : &st->bus_stops;
@@ -2156,7 +2156,7 @@ bool AfterLoadGame()
SlError(STR_ERROR_TOO_MANY_OBJECTS); SlError(STR_ERROR_TOO_MANY_OBJECTS);
} }
Object *o = new Object(); Object *o = Object::Create();
o->location.tile = (TileIndex)t; o->location.tile = (TileIndex)t;
o->location.w = size; o->location.w = size;
o->location.h = size; o->location.h = size;
@@ -2251,7 +2251,7 @@ bool AfterLoadGame()
* assert() in Pool::GetNew() happy by calling CanAllocateItem(). */ * assert() in Pool::GetNew() happy by calling CanAllocateItem(). */
static_assert(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE); static_assert(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE);
assert(CargoPayment::CanAllocateItem()); assert(CargoPayment::CanAllocateItem());
if (v->cargo_payment == nullptr) v->cargo_payment = new CargoPayment(v); if (v->cargo_payment == nullptr) v->cargo_payment = CargoPayment::Create(v);
} }
} }
} }
+1 -1
View File
@@ -260,7 +260,7 @@ struct INDYChunkHandler : ChunkHandler {
if (IsSavegameVersionBefore(SLV_161) && !IsSavegameVersionBefore(SLV_76)) { if (IsSavegameVersionBefore(SLV_161) && !IsSavegameVersionBefore(SLV_76)) {
/* Store the old persistent storage. The GRFID will be added later. */ /* Store the old persistent storage. The GRFID will be added later. */
assert(PersistentStorage::CanAllocateItem()); assert(PersistentStorage::CanAllocateItem());
i->psa = new PersistentStorage(0, GSF_INVALID, TileIndex{}); i->psa = PersistentStorage::Create(0, GSF_INVALID, TileIndex{});
std::copy(std::begin(_old_ind_persistent_storage.storage), std::end(_old_ind_persistent_storage.storage), std::begin(i->psa->storage)); std::copy(std::begin(_old_ind_persistent_storage.storage), std::end(_old_ind_persistent_storage.storage), std::begin(i->psa->storage));
} }
if (IsSavegameVersionBefore(SLV_EXTEND_INDUSTRY_CARGO_SLOTS)) { if (IsSavegameVersionBefore(SLV_EXTEND_INDUSTRY_CARGO_SLOTS)) {
+2 -2
View File
@@ -735,7 +735,7 @@ static bool LoadOldGood(LoadgameState &ls, int num)
ge->status.Set(GoodsEntry::State::Acceptance, HasBit(_waiting_acceptance, 15)); ge->status.Set(GoodsEntry::State::Acceptance, HasBit(_waiting_acceptance, 15));
ge->status.Set(GoodsEntry::State::Rating, _cargo_source != 0xFF); ge->status.Set(GoodsEntry::State::Rating, _cargo_source != 0xFF);
if (GB(_waiting_acceptance, 0, 12) != 0 && CargoPacket::CanAllocateItem()) { if (GB(_waiting_acceptance, 0, 12) != 0 && CargoPacket::CanAllocateItem()) {
ge->GetOrCreateData().cargo.Append(new CargoPacket(GB(_waiting_acceptance, 0, 12), _cargo_periods, (_cargo_source == 0xFF) ? StationID::Invalid() : StationID{_cargo_source}, INVALID_TILE, 0), ge->GetOrCreateData().cargo.Append(CargoPacket::Create(GB(_waiting_acceptance, 0, 12), _cargo_periods, (_cargo_source == 0xFF) ? StationID::Invalid() : StationID{_cargo_source}, INVALID_TILE, 0),
StationID::Invalid()); StationID::Invalid());
} }
@@ -1383,7 +1383,7 @@ bool LoadOldVehicle(LoadgameState &ls, int num)
if (_cargo_count != 0 && CargoPacket::CanAllocateItem()) { if (_cargo_count != 0 && CargoPacket::CanAllocateItem()) {
StationID source = (_cargo_source == 0xFF) ? StationID::Invalid() : StationID{_cargo_source}; StationID source = (_cargo_source == 0xFF) ? StationID::Invalid() : StationID{_cargo_source};
TileIndex source_xy = (source != StationID::Invalid()) ? Station::Get(source)->xy : (TileIndex)0; TileIndex source_xy = (source != StationID::Invalid()) ? Station::Get(source)->xy : (TileIndex)0;
v->cargo.Append(new CargoPacket(_cargo_count, _cargo_periods, source, source_xy, 0)); v->cargo.Append(CargoPacket::Create(_cargo_count, _cargo_periods, source, source_xy, 0));
} }
} }
+2 -2
View File
@@ -399,7 +399,7 @@ public:
if (IsSavegameVersionBefore(SLV_161) && !IsSavegameVersionBefore(SLV_145) && st->facilities.Test(StationFacility::Airport)) { if (IsSavegameVersionBefore(SLV_161) && !IsSavegameVersionBefore(SLV_145) && st->facilities.Test(StationFacility::Airport)) {
/* Store the old persistent storage. The GRFID will be added later. */ /* Store the old persistent storage. The GRFID will be added later. */
assert(PersistentStorage::CanAllocateItem()); assert(PersistentStorage::CanAllocateItem());
st->airport.psa = new PersistentStorage(0, GSF_INVALID, TileIndex{}); st->airport.psa = PersistentStorage::Create(0, GSF_INVALID, TileIndex{});
std::copy(std::begin(_old_st_persistent_storage.storage), std::end(_old_st_persistent_storage.storage), std::begin(st->airport.psa->storage)); std::copy(std::begin(_old_st_persistent_storage.storage), std::end(_old_st_persistent_storage.storage), std::begin(st->airport.psa->storage));
} }
@@ -426,7 +426,7 @@ public:
assert(CargoPacket::CanAllocateItem()); assert(CargoPacket::CanAllocateItem());
/* Don't construct the packet with station here, because that'll fail with old savegames */ /* Don't construct the packet with station here, because that'll fail with old savegames */
CargoPacket *cp = new CargoPacket(GB(_waiting_acceptance, 0, 12), _cargo_periods, source, TileIndex{_cargo_source_xy}, _cargo_feeder_share); CargoPacket *cp = CargoPacket::Create(GB(_waiting_acceptance, 0, 12), _cargo_periods, source, TileIndex{_cargo_source_xy}, _cargo_feeder_share);
ge.GetOrCreateData().cargo.Append(cp, StationID::Invalid()); ge.GetOrCreateData().cargo.Append(cp, StationID::Invalid());
ge.status.Set(GoodsEntry::State::Rating); ge.status.Set(GoodsEntry::State::Rating);
} }
+3 -3
View File
@@ -290,7 +290,7 @@ void AfterLoadVehiclesPhase1(bool part_of_load)
for (const OldOrderSaveLoadItem *old_order = GetOldOrder(v->old_orders); old_order != nullptr; old_order = GetOldOrder(old_order->next)) { for (const OldOrderSaveLoadItem *old_order = GetOldOrder(v->old_orders); old_order != nullptr; old_order = GetOldOrder(old_order->next)) {
orders.push_back(std::move(old_order->order)); orders.push_back(std::move(old_order->order));
} }
v->orders = mapping[v->old_orders] = new OrderList(std::move(orders), v); v->orders = mapping[v->old_orders] = OrderList::Create(std::move(orders), v);
} else { } else {
v->orders = mapping[v->old_orders]; v->orders = mapping[v->old_orders];
/* For old games (case a) we must create the shared vehicle chain */ /* For old games (case a) we must create the shared vehicle chain */
@@ -324,7 +324,7 @@ void AfterLoadVehiclesPhase1(bool part_of_load)
/* As above, allocating OrderList here is safe. */ /* As above, allocating OrderList here is safe. */
assert(OrderList::CanAllocateItem()); assert(OrderList::CanAllocateItem());
v->orders = new OrderList(); v->orders = OrderList::Create();
v->orders->first_shared = v; v->orders->first_shared = v;
for (Vehicle *u = v; u != nullptr; u = u->next_shared) { for (Vehicle *u = v; u != nullptr; u = u->next_shared) {
u->orders = v->orders; u->orders = v->orders;
@@ -1143,7 +1143,7 @@ struct VEHSChunkHandler : ChunkHandler {
if (_cargo_count != 0 && IsCompanyBuildableVehicleType(v) && CargoPacket::CanAllocateItem()) { if (_cargo_count != 0 && IsCompanyBuildableVehicleType(v) && CargoPacket::CanAllocateItem()) {
/* Don't construct the packet with station here, because that'll fail with old savegames */ /* Don't construct the packet with station here, because that'll fail with old savegames */
CargoPacket *cp = new CargoPacket(_cargo_count, _cargo_periods, _cargo_source, _cargo_source_xy, _cargo_feeder_share); CargoPacket *cp = CargoPacket::Create(_cargo_count, _cargo_periods, _cargo_source, _cargo_source_xy, _cargo_feeder_share);
v->cargo.Append(cp); v->cargo.Append(cp);
} }
+1 -1
View File
@@ -115,7 +115,7 @@ void MoveWaypointsToBaseStations()
SlErrorCorrupt("Waypoint with invalid tile"); SlErrorCorrupt("Waypoint with invalid tile");
} }
Waypoint *new_wp = new Waypoint(t); Waypoint *new_wp = Waypoint::Create(t);
new_wp->town = wp.town; new_wp->town = wp.town;
new_wp->town_cn = wp.town_cn; new_wp->town_cn = wp.town_cn;
new_wp->name = wp.name; new_wp->name = wp.name;
+1 -1
View File
@@ -871,7 +871,7 @@ CommandCost CmdBuildShip(DoCommandFlags flags, TileIndex tile, const Engine *e,
const ShipVehicleInfo *svi = &e->VehInfo<ShipVehicleInfo>(); const ShipVehicleInfo *svi = &e->VehInfo<ShipVehicleInfo>();
Ship *v = new Ship(); Ship *v = Ship::Create();
*ret = v; *ret = v;
v->owner = _current_company; v->owner = _current_company;
+1 -1
View File
@@ -45,7 +45,7 @@ std::tuple<CommandCost, SignID> CmdPlaceSign(DoCommandFlags flags, TileIndex til
int x = TileX(tile) * TILE_SIZE; int x = TileX(tile) * TILE_SIZE;
int y = TileY(tile) * TILE_SIZE; int y = TileY(tile) * TILE_SIZE;
Sign *si = new Sign(_game_mode == GM_EDITOR ? OWNER_DEITY : _current_company, x, y, GetSlopePixelZ(x, y), text); Sign *si = Sign::Create(_game_mode == GM_EDITOR ? OWNER_DEITY : _current_company, x, y, GetSlopePixelZ(x, y), text);
si->UpdateVirtCoord(); si->UpdateVirtCoord();
InvalidateWindowData(WC_SIGN_LIST, 0, 0); InvalidateWindowData(WC_SIGN_LIST, 0, 0);
+6 -6
View File
@@ -701,7 +701,7 @@ static CommandCost BuildStationPart(Station **st, DoCommandFlags flags, bool reu
if (!Station::CanAllocateItem()) return CommandCost(STR_ERROR_TOO_MANY_STATIONS_LOADING); if (!Station::CanAllocateItem()) return CommandCost(STR_ERROR_TOO_MANY_STATIONS_LOADING);
if (flags.Test(DoCommandFlag::Execute)) { if (flags.Test(DoCommandFlag::Execute)) {
*st = new Station(area.tile); *st = Station::Create(area.tile);
_station_kdtree.Insert((*st)->index); _station_kdtree.Insert((*st)->index);
(*st)->town = ClosestTownFromTile(area.tile, UINT_MAX); (*st)->town = ClosestTownFromTile(area.tile, UINT_MAX);
@@ -2165,7 +2165,7 @@ CommandCost CmdBuildRoadStop(DoCommandFlags flags, TileIndex tile, uint8_t width
st->cached_roadstop_anim_triggers.Set(roadstopspec->animation.triggers); st->cached_roadstop_anim_triggers.Set(roadstopspec->animation.triggers);
} }
RoadStop *road_stop = new RoadStop(cur_tile); RoadStop *road_stop = RoadStop::Create(cur_tile);
/* Insert into linked list of RoadStops. */ /* Insert into linked list of RoadStops. */
RoadStop **currstop = FindRoadStopSpot(is_truck_stop, st); RoadStop **currstop = FindRoadStopSpot(is_truck_stop, st);
*currstop = road_stop; *currstop = road_stop;
@@ -4268,7 +4268,7 @@ void IncreaseStats(Station *st, CargoType cargo, StationID next_station_id, uint
if (ge1.link_graph == LinkGraphID::Invalid()) { if (ge1.link_graph == LinkGraphID::Invalid()) {
if (ge2.link_graph == LinkGraphID::Invalid()) { if (ge2.link_graph == LinkGraphID::Invalid()) {
if (LinkGraph::CanAllocateItem()) { if (LinkGraph::CanAllocateItem()) {
lg = new LinkGraph(cargo); lg = LinkGraph::Create(cargo);
LinkGraphSchedule::instance.Queue(lg); LinkGraphSchedule::instance.Queue(lg);
ge2.link_graph = lg->index; ge2.link_graph = lg->index;
ge2.node = lg->AddNode(st2); ge2.node = lg->AddNode(st2);
@@ -4413,11 +4413,11 @@ static uint UpdateStationWaiting(Station *st, CargoType cargo, uint amount, Sour
if (amount == 0) return 0; if (amount == 0) return 0;
StationID next = ge.GetVia(st->index); StationID next = ge.GetVia(st->index);
ge.GetOrCreateData().cargo.Append(new CargoPacket(st->index, amount, source), next); ge.GetOrCreateData().cargo.Append(CargoPacket::Create(st->index, amount, source), next);
LinkGraph *lg = nullptr; LinkGraph *lg = nullptr;
if (ge.link_graph == LinkGraphID::Invalid()) { if (ge.link_graph == LinkGraphID::Invalid()) {
if (LinkGraph::CanAllocateItem()) { if (LinkGraph::CanAllocateItem()) {
lg = new LinkGraph(cargo); lg = LinkGraph::Create(cargo);
LinkGraphSchedule::instance.Queue(lg); LinkGraphSchedule::instance.Queue(lg);
ge.link_graph = lg->index; ge.link_graph = lg->index;
ge.node = lg->AddNode(st); ge.node = lg->AddNode(st);
@@ -4714,7 +4714,7 @@ void BuildOilRig(TileIndex tile)
return; return;
} }
Station *st = new Station(tile); Station *st = Station::Create(tile);
_station_kdtree.Insert(st->index); _station_kdtree.Insert(st->index);
st->town = ClosestTownFromTile(tile, UINT_MAX); st->town = ClosestTownFromTile(tile, UINT_MAX);
+2 -2
View File
@@ -228,7 +228,7 @@ std::tuple<CommandCost, StoryPageID> CmdCreateStoryPage(DoCommandFlags flags, Co
_story_page_next_sort_value = 0; _story_page_next_sort_value = 0;
} }
StoryPage *s = new StoryPage(_story_page_next_sort_value, TimerGameCalendar::date, company, text); StoryPage *s = StoryPage::Create(_story_page_next_sort_value, TimerGameCalendar::date, company, text);
InvalidateWindowClassesData(WC_STORY_BOOK, -1); InvalidateWindowClassesData(WC_STORY_BOOK, -1);
if (StoryPage::GetNumItems() == 1) InvalidateWindowData(WC_MAIN_TOOLBAR, 0); if (StoryPage::GetNumItems() == 1) InvalidateWindowData(WC_MAIN_TOOLBAR, 0);
@@ -272,7 +272,7 @@ std::tuple<CommandCost, StoryPageElementID> CmdCreateStoryPageElement(DoCommandF
_story_page_element_next_sort_value = 0; _story_page_element_next_sort_value = 0;
} }
StoryPageElement *pe = new StoryPageElement(_story_page_element_next_sort_value, type, page_id); StoryPageElement *pe = StoryPageElement::Create(_story_page_element_next_sort_value, type, page_id);
UpdateElement(*pe, tile, reference, text); UpdateElement(*pe, tile, reference, text);
InvalidateWindowClassesData(WC_STORY_BOOK, page_id); InvalidateWindowClassesData(WC_STORY_BOOK, page_id);
+1 -1
View File
@@ -172,7 +172,7 @@ static bool CheckSubsidyDistance(Source src, Source dst)
*/ */
void CreateSubsidy(CargoType cargo_type, Source src, Source dst) void CreateSubsidy(CargoType cargo_type, Source src, Source dst)
{ {
Subsidy *s = new Subsidy(cargo_type, src, dst, SUBSIDY_OFFER_MONTHS); Subsidy *s = Subsidy::Create(cargo_type, src, dst, SUBSIDY_OFFER_MONTHS);
const CargoSpec *cs = CargoSpec::Get(s->cargo_type); const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
EncodedString headline = GetEncodedString(STR_NEWS_SERVICE_SUBSIDY_OFFERED, cs->name, s->src.GetFormat(), s->src.id, s->dst.GetFormat(), s->dst.id, _settings_game.difficulty.subsidy_duration); EncodedString headline = GetEncodedString(STR_NEWS_SERVICE_SUBSIDY_OFFERED, cs->name, s->src.GetFormat(), s->src.id, s->dst.GetFormat(), s->dst.id, _settings_game.difficulty.subsidy_duration);
+2 -2
View File
@@ -2253,7 +2253,7 @@ std::tuple<CommandCost, Money, TownID> CmdFoundTown(DoCommandFlags flags, TileIn
if (random_location) { if (random_location) {
t = CreateRandomTown(20, townnameparts, size, city, layout); t = CreateRandomTown(20, townnameparts, size, city, layout);
} else { } else {
t = new Town(tile); t = Town::Create(tile);
DoCreateTown(t, tile, townnameparts, size, city, layout, true); DoCreateTown(t, tile, townnameparts, size, city, layout, true);
} }
@@ -2401,7 +2401,7 @@ static Town *CreateRandomTown(uint attempts, uint32_t townnameparts, TownSize si
} else if (TownCanBePlacedHere(tile, true).Failed()) continue; } else if (TownCanBePlacedHere(tile, true).Failed()) continue;
/* Allocate a town struct */ /* Allocate a town struct */
Town *t = new Town(tile); Town *t = Town::Create(tile);
DoCreateTown(t, tile, townnameparts, size, city, layout, false); DoCreateTown(t, tile, townnameparts, size, city, layout, false);
+3 -3
View File
@@ -641,7 +641,7 @@ static CommandCost CmdBuildRailWagon(DoCommandFlags flags, TileIndex tile, const
if (!IsCompatibleRail(rvi->railtypes, GetRailType(tile))) return CMD_ERROR; if (!IsCompatibleRail(rvi->railtypes, GetRailType(tile))) return CMD_ERROR;
if (flags.Test(DoCommandFlag::Execute)) { if (flags.Test(DoCommandFlag::Execute)) {
Train *v = new Train(); Train *v = Train::Create();
*ret = v; *ret = v;
v->spritenum = rvi->image_index; v->spritenum = rvi->image_index;
@@ -723,7 +723,7 @@ void NormalizeTrainVehInDepot(const Train *u)
static void AddRearEngineToMultiheadedTrain(Train *v) static void AddRearEngineToMultiheadedTrain(Train *v)
{ {
Train *u = new Train(); Train *u = Train::Create();
v->value >>= 1; v->value >>= 1;
u->value = v->value; u->value = v->value;
u->direction = v->direction; u->direction = v->direction;
@@ -782,7 +782,7 @@ CommandCost CmdBuildRailVehicle(DoCommandFlags flags, TileIndex tile, const Engi
int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir]; int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir]; int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
Train *v = new Train(); Train *v = Train::Create();
*ret = v; *ret = v;
v->direction = DiagDirToDir(dir); v->direction = DiagDirToDir(dir);
v->tile = tile; v->tile = tile;
+1 -1
View File
@@ -2960,7 +2960,7 @@ void Vehicle::AddToShared(Vehicle *shared_chain)
if (shared_chain->orders == nullptr) { if (shared_chain->orders == nullptr) {
assert(shared_chain->previous_shared == nullptr); assert(shared_chain->previous_shared == nullptr);
assert(shared_chain->next_shared == nullptr); assert(shared_chain->next_shared == nullptr);
this->orders = shared_chain->orders = new OrderList(shared_chain); this->orders = shared_chain->orders = OrderList::Create(shared_chain);
} }
this->next_shared = shared_chain->next_shared; this->next_shared = shared_chain->next_shared;
+11
View File
@@ -1126,6 +1126,17 @@ struct SpecializedVehicle : public Vehicle {
return IsValidID(index) ? Get(index) : nullptr; return IsValidID(index) ? Get(index) : nullptr;
} }
/**
* Creates a new T-object in the vehicle pool.
* @param args... The arguments to the constructor.
* @return The created object.
*/
template <typename... Targs>
static inline T *Create(Targs &&... args)
{
return Vehicle::Create<T>(std::forward<Targs&&>(args)...);
}
/** /**
* Converts a Vehicle to SpecializedVehicle with type checking. * Converts a Vehicle to SpecializedVehicle with type checking.
* @param v Vehicle pointer * @param v Vehicle pointer
+1 -1
View File
@@ -145,7 +145,7 @@ CommandCost CmdBuildShipDepot(DoCommandFlags flags, TileIndex tile, Axis axis)
} }
if (flags.Test(DoCommandFlag::Execute)) { if (flags.Test(DoCommandFlag::Execute)) {
Depot *depot = new Depot(tile); Depot *depot = Depot::Create(tile);
uint new_water_infra = 2 * LOCK_DEPOT_TILE_FACTOR; uint new_water_infra = 2 * LOCK_DEPOT_TILE_FACTOR;
/* Update infrastructure counts after the tile clears earlier. /* Update infrastructure counts after the tile clears earlier.
+3 -3
View File
@@ -281,7 +281,7 @@ CommandCost CmdBuildRailWaypoint(DoCommandFlags flags, TileIndex start_tile, Axi
if (flags.Test(DoCommandFlag::Execute)) { if (flags.Test(DoCommandFlag::Execute)) {
if (wp == nullptr) { if (wp == nullptr) {
wp = new Waypoint(start_tile); wp = Waypoint::Create(start_tile);
} else if (!wp->IsInUse()) { } else if (!wp->IsInUse()) {
/* Move existing (recently deleted) waypoint to the new location */ /* Move existing (recently deleted) waypoint to the new location */
wp->xy = start_tile; wp->xy = start_tile;
@@ -401,7 +401,7 @@ CommandCost CmdBuildRoadWaypoint(DoCommandFlags flags, TileIndex start_tile, Axi
if (flags.Test(DoCommandFlag::Execute)) { if (flags.Test(DoCommandFlag::Execute)) {
if (wp == nullptr) { if (wp == nullptr) {
wp = new Waypoint(start_tile); wp = Waypoint::Create(start_tile);
SetBit(wp->waypoint_flags, WPF_ROAD); SetBit(wp->waypoint_flags, WPF_ROAD);
} else if (!wp->IsInUse()) { } else if (!wp->IsInUse()) {
/* Move existing (recently deleted) waypoint to the new location */ /* Move existing (recently deleted) waypoint to the new location */
@@ -492,7 +492,7 @@ CommandCost CmdBuildBuoy(DoCommandFlags flags, TileIndex tile)
if (flags.Test(DoCommandFlag::Execute)) { if (flags.Test(DoCommandFlag::Execute)) {
if (wp == nullptr) { if (wp == nullptr) {
wp = new Waypoint(tile); wp = Waypoint::Create(tile);
} else { } else {
/* Move existing (recently deleted) buoy to the new location */ /* Move existing (recently deleted) buoy to the new location */
wp->xy = tile; wp->xy = tile;