From 2fcd4e189aa3a5a06bfca8f2ca3a9c5bc2dee62d Mon Sep 17 00:00:00 2001 From: Rubidium Date: Sat, 3 Jan 2026 11:45:18 +0100 Subject: [PATCH] Codechange: replace 'new PoolItem(...' with 'PoolItem::Create(...' --- src/aircraft_cmd.cpp | 6 ++-- src/articulated_vehicles.cpp | 6 ++-- src/autoreplace.cpp | 2 +- src/base_station_base.h | 11 +++++++ src/cargopacket.cpp | 2 +- src/company_cmd.cpp | 2 +- src/core/pool_type.hpp | 25 +++++++++------ src/disaster_vehicle.cpp | 28 ++++++++--------- src/economy.cpp | 2 +- src/effectvehicle.cpp | 2 +- src/goal.cpp | 2 +- src/group_cmd.cpp | 2 +- src/industry_cmd.cpp | 2 +- src/league_cmd.cpp | 4 +-- src/linkgraph/linkgraphschedule.cpp | 2 +- src/network/network.cpp | 4 +-- src/network/network_admin.cpp | 2 +- src/network/network_client.cpp | 2 +- src/network/network_server.cpp | 2 +- src/newgrf.cpp | 2 +- src/newgrf/newgrf_act2.cpp | 14 ++++----- src/newgrf_airport.cpp | 2 +- src/newgrf_industries.cpp | 2 +- src/newgrf_spritegroup.h | 48 ++++++++++++++++++++--------- src/newgrf_town.cpp | 2 +- src/object_cmd.cpp | 2 +- src/order_backup.cpp | 4 +-- src/order_backup.h | 5 +-- src/order_cmd.cpp | 4 +-- src/rail_cmd.cpp | 2 +- src/road_cmd.cpp | 2 +- src/roadveh_cmd.cpp | 2 +- src/saveload/afterload.cpp | 6 ++-- src/saveload/industry_sl.cpp | 2 +- src/saveload/oldloader_sl.cpp | 4 +-- src/saveload/station_sl.cpp | 4 +-- src/saveload/vehicle_sl.cpp | 6 ++-- src/saveload/waypoint_sl.cpp | 2 +- src/ship_cmd.cpp | 2 +- src/signs_cmd.cpp | 2 +- src/station_cmd.cpp | 12 ++++---- src/story.cpp | 4 +-- src/subsidy.cpp | 2 +- src/town_cmd.cpp | 4 +-- src/train_cmd.cpp | 6 ++-- src/vehicle.cpp | 2 +- src/vehicle_base.h | 11 +++++++ src/water_cmd.cpp | 2 +- src/waypoint_cmd.cpp | 6 ++-- 49 files changed, 162 insertions(+), 114 deletions(-) diff --git a/src/aircraft_cmd.cpp b/src/aircraft_cmd.cpp index 7ca1faf8da..87abaddb44 100644 --- a/src/aircraft_cmd.cpp +++ b/src/aircraft_cmd.cpp @@ -275,8 +275,8 @@ CommandCost CmdBuildAircraft(DoCommandFlags flags, TileIndex tile, const Engine tile = st->airport.GetHangarTile(st->airport.GetHangarNum(tile)); if (flags.Test(DoCommandFlag::Execute)) { - Aircraft *v = new Aircraft(); // aircraft - Aircraft *u = new Aircraft(); // shadow + Aircraft *v = Aircraft::Create(); // aircraft + Aircraft *u = Aircraft::Create(); // shadow *ret = v; v->direction = DIR_SE; @@ -366,7 +366,7 @@ CommandCost CmdBuildAircraft(DoCommandFlags flags, TileIndex tile, const Engine /* Aircraft with 3 vehicles (chopper)? */ if (v->subtype == AIR_HELICOPTER) { - Aircraft *w = new Aircraft(); + Aircraft *w = Aircraft::Create(); w->engine_type = e->index; w->direction = DIR_N; w->owner = _current_company; diff --git a/src/articulated_vehicles.cpp b/src/articulated_vehicles.cpp index 64bc1a333f..08fd04c46a 100644 --- a/src/articulated_vehicles.cpp +++ b/src/articulated_vehicles.cpp @@ -82,7 +82,7 @@ uint CountArticulatedParts(EngineID engine_type, bool purchase_window) std::unique_ptr v; if (!purchase_window) { - v = std::make_unique(); + v = std::unique_ptr(Vehicle::Create()); v->engine_type = engine_type; v->owner = _current_company; } @@ -357,7 +357,7 @@ void AddArticulatedParts(Vehicle *first) case VEH_TRAIN: { Train *front = Train::From(first); - Train *t = new Train(); + Train *t = Train::Create(); v->SetNext(t); v = t; @@ -381,7 +381,7 @@ void AddArticulatedParts(Vehicle *first) case VEH_ROAD: { RoadVehicle *front = RoadVehicle::From(first); - RoadVehicle *rv = new RoadVehicle(); + RoadVehicle *rv = RoadVehicle::Create(); v->SetNext(rv); v = rv; diff --git a/src/autoreplace.cpp b/src/autoreplace.cpp index e4ad64815f..eefee2a9ff 100644 --- a/src/autoreplace.cpp +++ b/src/autoreplace.cpp @@ -109,7 +109,7 @@ CommandCost AddEngineReplacement(EngineRenewList *erl, EngineID old_engine, Engi if (flags.Test(DoCommandFlag::Execute)) { /* 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(); diff --git a/src/base_station_base.h b/src/base_station_base.h index 75bdfb5471..9873a73b7b 100644 --- a/src/base_station_base.h +++ b/src/base_station_base.h @@ -269,6 +269,17 @@ struct SpecializedStation : public BaseStation { 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 + static inline T *Create(Targs &&... args) + { + return BaseStation::Create(std::forward(args)...); + } + /** * Converts a BaseStation to SpecializedStation with type checking. * @param st BaseStation pointer diff --git a/src/cargopacket.cpp b/src/cargopacket.cpp index 2fbd3f2f29..f2bf4253cf 100644 --- a/src/cargopacket.cpp +++ b/src/cargopacket.cpp @@ -96,7 +96,7 @@ CargoPacket *CargoPacket::Split(uint new_size) if (!CargoPacket::CanAllocateItem()) return nullptr; 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->count -= new_size; return cp_new; diff --git a/src/company_cmd.cpp b/src/company_cmd.cpp index a049e30548..9ef6006762 100644 --- a/src/company_cmd.cpp +++ b/src/company_cmd.cpp @@ -605,7 +605,7 @@ Company *DoStartupNewCompany(bool is_ai, CompanyID company = CompanyID::Invalid( Company *c; if (company == CompanyID::Invalid()) { - c = new Company(STR_SV_UNNAMED, is_ai); + c = Company::Create(STR_SV_UNNAMED, is_ai); } else { if (Company::IsValidID(company)) return nullptr; c = new (company) Company(STR_SV_UNNAMED, is_ai); diff --git a/src/core/pool_type.hpp b/src/core/pool_type.hpp index dd76abc3a5..545a258eef 100644 --- a/src/core/pool_type.hpp +++ b/src/core/pool_type.hpp @@ -288,16 +288,8 @@ public: /** Type of the pool this item is going to be part of */ typedef struct Pool Pool; - /** - * Allocates space for new Titem - * @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); - } + /** Do not use new PoolItem, but rather PoolItem::Create. */ + inline void *operator new(size_t) = delete; /** * 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 + requires std::is_base_of_v + static inline T *Create(Targs &&... args) + { + void *data = Tpool->GetNew(sizeof(T)); + return ::new (data) T(std::forward(args)...); + } + /** Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function() */ /** diff --git a/src/disaster_vehicle.cpp b/src/disaster_vehicle.cpp index b592d3ebfe..6bbb453860 100644 --- a/src/disaster_vehicle.cpp +++ b/src/disaster_vehicle.cpp @@ -569,8 +569,8 @@ static bool DisasterTick_Big_Ufo(DisasterVehicle *v) delete v; return false; } - DisasterVehicle *u = new DisasterVehicle(-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 *u = DisasterVehicle::Create(-6 * (int)TILE_SIZE, v->y_pos, DIR_SW, ST_BIG_UFO_DESTROYER, v->index); + DisasterVehicle *w = DisasterVehicle::Create(-6 * (int)TILE_SIZE, v->y_pos, DIR_SW, ST_BIG_UFO_DESTROYER_SHADOW); u->SetNext(w); } else if (v->state == 0) { 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 */ - 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); } @@ -759,11 +759,11 @@ static void Disaster_Small_Ufo_Init() if (!Vehicle::CanAllocateItem(2)) return; 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); /* 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); } @@ -788,8 +788,8 @@ static void Disaster_Airplane_Init() int x = (Map::SizeX() + 9) * TILE_SIZE - 1; int y = TileY(found->location.tile) * TILE_SIZE + 37; - DisasterVehicle *v = new DisasterVehicle(x, y, DIR_NE, ST_AIRPLANE); - DisasterVehicle *u = new DisasterVehicle(x, y, DIR_NE, ST_AIRPLANE_SHADOW); + DisasterVehicle *v = DisasterVehicle::Create(x, y, DIR_NE, ST_AIRPLANE); + DisasterVehicle *u = DisasterVehicle::Create(x, y, DIR_NE, ST_AIRPLANE_SHADOW); v->SetNext(u); } @@ -813,11 +813,11 @@ static void Disaster_Helicopter_Init() int x = -16 * (int)TILE_SIZE; int y = TileY(found->location.tile) * TILE_SIZE + 37; - DisasterVehicle *v = new DisasterVehicle(x, y, DIR_SW, ST_HELICOPTER); - DisasterVehicle *u = new DisasterVehicle(x, y, DIR_SW, ST_HELICOPTER_SHADOW); + DisasterVehicle *v = DisasterVehicle::Create(x, y, DIR_SW, ST_HELICOPTER); + DisasterVehicle *u = DisasterVehicle::Create(x, y, DIR_SW, ST_HELICOPTER_SHADOW); 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); } @@ -831,11 +831,11 @@ static void Disaster_Big_Ufo_Init() int x = TileX(RandomTile()) * TILE_SIZE + TILE_SIZE / 2; 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); /* 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); } @@ -859,7 +859,7 @@ static void Disaster_Submarine_Init(DisasterSubType subtype) } if (!IsWaterTile(TileVirtXY(x, y))) return; - new DisasterVehicle(x, y, dir, subtype); + DisasterVehicle::Create(x, y, dir, subtype); } /* Curious submarine #1, just floats around */ diff --git a/src/economy.cpp b/src/economy.cpp index c4f029cddd..05b4e664ce 100644 --- a/src/economy.cpp +++ b/src/economy.cpp @@ -1259,7 +1259,7 @@ void PrepareUnload(Vehicle *front_v) * limit in number of CargoPayments. Can't go wrong. */ static_assert(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE); assert(CargoPayment::CanAllocateItem()); - front_v->cargo_payment = new CargoPayment(front_v); + front_v->cargo_payment = CargoPayment::Create(front_v); std::vector next_station; front_v->GetNextStoppingStation(next_station); diff --git a/src/effectvehicle.cpp b/src/effectvehicle.cpp index 58507eb541..958cd49edf 100644 --- a/src/effectvehicle.cpp +++ b/src/effectvehicle.cpp @@ -567,7 +567,7 @@ EffectVehicle *CreateEffectVehicle(int x, int y, int z, EffectVehicleType type) { if (!Vehicle::CanAllocateItem()) return nullptr; - EffectVehicle *v = new EffectVehicle(); + EffectVehicle *v = EffectVehicle::Create(); v->subtype = type; v->x_pos = x; v->y_pos = y; diff --git a/src/goal.cpp b/src/goal.cpp index bf0d2ac083..aa9d33e3b6 100644 --- a/src/goal.cpp +++ b/src/goal.cpp @@ -85,7 +85,7 @@ std::tuple CmdCreateGoal(DoCommandFlags flags, CompanyID co if (!Goal::IsValidGoalDestination(company, type, dest)) return { CMD_ERROR, GoalID::Invalid() }; 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()) { InvalidateWindowClassesData(WC_GOALS_LIST); diff --git a/src/group_cmd.cpp b/src/group_cmd.cpp index 23576a48f0..13c35e8dbb 100644 --- a/src/group_cmd.cpp +++ b/src/group_cmd.cpp @@ -349,7 +349,7 @@ std::tuple CmdCreateGroup(DoCommandFlags flags, VehicleTyp } 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); g->number = c->freegroups.UseID(c->freegroups.NextID()); diff --git a/src/industry_cmd.cpp b/src/industry_cmd.cpp index 22bad9aad1..2400eb9a93 100644 --- a/src/industry_cmd.cpp +++ b/src/industry_cmd.cpp @@ -2043,7 +2043,7 @@ static CommandCost CreateNewIndustryHelper(TileIndex tile, IndustryType type, Do if (!Industry::CanAllocateItem()) return CommandCost(STR_ERROR_TOO_MANY_INDUSTRIES); if (flags.Test(DoCommandFlag::Execute)) { - *ip = new Industry(tile); + *ip = Industry::Create(tile); if (!custom_shape_check) CheckIfCanLevelIndustryPlatform(tile, {DoCommandFlag::NoWater, DoCommandFlag::Execute}, layout); DoCreateNewIndustry(*ip, tile, type, layout, layout_index, t, founder, random_initial_bits); } diff --git a/src/league_cmd.cpp b/src/league_cmd.cpp index 275d1dd378..aa749400a8 100644 --- a/src/league_cmd.cpp +++ b/src/league_cmd.cpp @@ -60,7 +60,7 @@ std::tuple CmdCreateLeagueTable(DoCommandFlags flags if (title.empty()) return { CMD_ERROR, LeagueTableID::Invalid() }; if (flags.Test(DoCommandFlag::Execute)) { - LeagueTable *lt = new LeagueTable(title, header, footer); + LeagueTable *lt = LeagueTable::Create(title, header, footer); return { CommandCost(), lt->index }; } @@ -89,7 +89,7 @@ std::tuple CmdCreateLeagueTableElement(DoComm if (company != CompanyID::Invalid() && !Company::IsValidID(company)) return { CMD_ERROR, LeagueTableElementID::Invalid() }; 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); return { CommandCost(), lte->index }; } diff --git a/src/linkgraph/linkgraphschedule.cpp b/src/linkgraph/linkgraphschedule.cpp index ea7195e348..30957b9bb0 100644 --- a/src/linkgraph/linkgraphschedule.cpp +++ b/src/linkgraph/linkgraphschedule.cpp @@ -43,7 +43,7 @@ void LinkGraphSchedule::SpawnNext() assert(next == LinkGraph::Get(next->index)); this->schedule.pop_front(); if (LinkGraphJob::CanAllocateItem()) { - LinkGraphJob *job = new LinkGraphJob(*next); + LinkGraphJob *job = LinkGraphJob::Create(*next); job->SpawnThread(); this->running.push_back(job); } else { diff --git a/src/network/network.cpp b/src/network/network.cpp index 6baf23301a..68f18ab6ec 100644 --- a/src/network/network.cpp +++ b/src/network/network.cpp @@ -568,7 +568,7 @@ NetworkAddress ParseConnectionString(std::string_view connection_string, uint16_ /* Register the login */ _network_clients_connected++; - ServerNetworkGameSocketHandler *cs = new ServerNetworkGameSocketHandler(s); + ServerNetworkGameSocketHandler *cs = ServerNetworkGameSocketHandler::Create(s); cs->client_address = address; // Save the IP of the client InvalidateWindowData(WC_CLIENT_LIST, 0); @@ -836,7 +836,7 @@ static void NetworkInitGameInfo() /* There should be always space for the server. */ assert(NetworkClientInfo::CanAllocateItem()); - NetworkClientInfo *ci = new NetworkClientInfo(CLIENT_ID_SERVER); + NetworkClientInfo *ci = NetworkClientInfo::Create(CLIENT_ID_SERVER); ci->client_playas = COMPANY_SPECTATOR; ci->client_name = _settings_client.network.client_name; diff --git a/src/network/network_admin.cpp b/src/network/network_admin.cpp index 99ec918ef3..045088d0a3 100644 --- a/src/network/network_admin.cpp +++ b/src/network/network_admin.cpp @@ -115,7 +115,7 @@ ServerNetworkAdminSocketHandler::~ServerNetworkAdminSocketHandler() */ /* 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 } diff --git a/src/network/network_client.cpp b/src/network/network_client.cpp index 4a683dc1f4..87cb5ce561 100644 --- a/src/network/network_client.cpp +++ b/src/network/network_client.cpp @@ -565,7 +565,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CLIENT_INFO(Pac 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 */ - ci = new NetworkClientInfo(client_id); + ci = NetworkClientInfo::Create(client_id); ci->client_playas = playas; if (client_id == _network_own_client_id) this->SetInfo(ci); diff --git a/src/network/network_server.cpp b/src/network/network_server.cpp index b3535977a2..bd60630df3 100644 --- a/src/network/network_server.cpp +++ b/src/network/network_server.cpp @@ -914,7 +914,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_IDENTIFY(Packet } assert(NetworkClientInfo::CanAllocateItem()); - NetworkClientInfo *ci = new NetworkClientInfo(this->client_id); + NetworkClientInfo *ci = NetworkClientInfo::Create(this->client_id); this->SetInfo(ci); ci->join_date = TimerGameEconomy::date; ci->client_name = std::move(client_name); diff --git a/src/newgrf.cpp b/src/newgrf.cpp index 3db85edbdb..b814ce48ec 100644 --- a/src/newgrf.cpp +++ b/src/newgrf.cpp @@ -263,7 +263,7 @@ Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16_t internal_id size_t engine_pool_size = Engine::GetPoolSize(); /* ... 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); /* Reserve the engine slot */ diff --git a/src/newgrf/newgrf_act2.cpp b/src/newgrf/newgrf_act2.cpp index abf656af59..26fe388193 100644 --- a/src/newgrf/newgrf_act2.cpp +++ b/src/newgrf/newgrf_act2.cpp @@ -286,7 +286,7 @@ static const SpriteGroup *GetCallbackResultGroup(uint16_t value) /* Result value is not present, so make it and add to cache. */ assert(CallbackResultSpriteGroup::CanAllocateItem()); - const SpriteGroup *group = new CallbackResultSpriteGroup(value); + const SpriteGroup *group = CallbackResultSpriteGroup::Create(value); it = _cached_callback_groups.emplace(it, value, group->index); return group; } @@ -330,7 +330,7 @@ static const SpriteGroup *CreateGroupFromGroupID(GrfSpecFeature feature, uint8_t assert(spriteset_start + num_sprites <= _cur_gps.spriteid); assert(ResultSpriteGroup::CanAllocateItem()); - return new ResultSpriteGroup(spriteset_start, num_sprites); + return ResultSpriteGroup::Create(spriteset_start, num_sprites); } /* Action 0x02 */ @@ -374,7 +374,7 @@ static void NewSpriteGroup(ByteReader &buf) uint8_t varsize; assert(DeterministicSpriteGroup::CanAllocateItem()); - DeterministicSpriteGroup *group = new DeterministicSpriteGroup(); + DeterministicSpriteGroup *group = DeterministicSpriteGroup::Create(); group->nfo_line = _cur_gps.nfo_line; act_group = group; 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 { assert(RandomizedSpriteGroup::CanAllocateItem()); - RandomizedSpriteGroup *group = new RandomizedSpriteGroup(); + RandomizedSpriteGroup *group = RandomizedSpriteGroup::Create(); group->nfo_line = _cur_gps.nfo_line; act_group = group; group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF; @@ -593,7 +593,7 @@ static void NewSpriteGroup(ByteReader &buf) } assert(RealSpriteGroup::CanAllocateItem()); - RealSpriteGroup *group = new RealSpriteGroup(); + RealSpriteGroup *group = RealSpriteGroup::Create(); group->nfo_line = _cur_gps.nfo_line; act_group = group; @@ -622,7 +622,7 @@ static void NewSpriteGroup(ByteReader &buf) uint8_t num_building_sprites = std::max((uint8_t)1, type); assert(TileLayoutSpriteGroup::CanAllocateItem()); - TileLayoutSpriteGroup *group = new TileLayoutSpriteGroup(); + TileLayoutSpriteGroup *group = TileLayoutSpriteGroup::Create(); group->nfo_line = _cur_gps.nfo_line; act_group = group; @@ -638,7 +638,7 @@ static void NewSpriteGroup(ByteReader &buf) } assert(IndustryProductionSpriteGroup::CanAllocateItem()); - IndustryProductionSpriteGroup *group = new IndustryProductionSpriteGroup(); + IndustryProductionSpriteGroup *group = IndustryProductionSpriteGroup::Create(); group->nfo_line = _cur_gps.nfo_line; act_group = group; group->version = type; diff --git a/src/newgrf_airport.cpp b/src/newgrf_airport.cpp index 2188793a66..89a30ea480 100644 --- a/src/newgrf_airport.cpp +++ b/src/newgrf_airport.cpp @@ -213,7 +213,7 @@ uint32_t AirportResolverObject::GetDebugID() const /* Create storage on first modification. */ uint32_t grfid = (this->ro.grffile != nullptr) ? this->ro.grffile->grfid : 0; 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); } diff --git a/src/newgrf_industries.cpp b/src/newgrf_industries.cpp index da314cc055..b3b87a0468 100644 --- a/src/newgrf_industries.cpp +++ b/src/newgrf_industries.cpp @@ -448,7 +448,7 @@ static uint32_t GetCountAndDistanceOfClosestInstance(const ResolverObject &objec /* Create storage on first modification. */ const IndustrySpec *indsp = GetIndustrySpec(this->industry->type); 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); diff --git a/src/newgrf_spritegroup.h b/src/newgrf_spritegroup.h index dc20f33d21..3cfc692e9e 100644 --- a/src/newgrf_spritegroup.h +++ b/src/newgrf_spritegroup.h @@ -59,10 +59,30 @@ public: }; +/** + * Class defining some overloaded accessors so we don't have to cast SpriteGroups that often + */ +template +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 + static inline T *Create(Targs &&... args) + { + return SpriteGroup::Create(std::forward(args)...); + } +}; + + /* 'Real' sprite groups contain a list of other result or callback sprite * groups. */ -struct RealSpriteGroup : SpriteGroup { - RealSpriteGroup() : SpriteGroup() {} +struct RealSpriteGroup : SpecializedSpriteGroup { + RealSpriteGroup() : SpecializedSpriteGroup() {} /* Loaded = in motion, loading = not moving * Each group contains several spritesets, for various loading stages */ @@ -156,8 +176,8 @@ struct DeterministicSpriteGroupRange { }; -struct DeterministicSpriteGroup : SpriteGroup { - DeterministicSpriteGroup() : SpriteGroup() {} +struct DeterministicSpriteGroup : SpecializedSpriteGroup { + DeterministicSpriteGroup() : SpecializedSpriteGroup() {} VarSpriteGroupScope var_scope{}; DeterministicSpriteGroupSize size{}; @@ -178,8 +198,8 @@ enum RandomizedSpriteGroupCompareMode : uint8_t { RSG_CMP_ALL, }; -struct RandomizedSpriteGroup : SpriteGroup { - RandomizedSpriteGroup() : SpriteGroup() {} +struct RandomizedSpriteGroup : SpecializedSpriteGroup { + RandomizedSpriteGroup() : SpecializedSpriteGroup() {} VarSpriteGroupScope var_scope{}; ///< Take this object: @@ -198,12 +218,12 @@ protected: /* This contains a callback result. A failed callback has a value of * CALLBACK_FAILED */ -struct CallbackResultSpriteGroup : SpriteGroup { +struct CallbackResultSpriteGroup : SpecializedSpriteGroup { /** * Creates a spritegroup representing a 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(), result(value) {} CallbackResult result = 0; @@ -214,14 +234,14 @@ protected: /* A result sprite group returns the first SpriteID and the number of * sprites in the set */ -struct ResultSpriteGroup : SpriteGroup { +struct ResultSpriteGroup : SpecializedSpriteGroup { /** * Creates a spritegroup representing a sprite number result. * @param sprite The sprite number. * @param num_sprites The number of sprites per set. * @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(), num_sprites(num_sprites), sprite(sprite) {} uint8_t num_sprites = 0; SpriteID sprite = 0; @@ -233,8 +253,8 @@ protected: /** * Action 2 sprite layout for houses, industry tiles, objects and airport tiles. */ -struct TileLayoutSpriteGroup : SpriteGroup { - TileLayoutSpriteGroup() : SpriteGroup() {} +struct TileLayoutSpriteGroup : SpecializedSpriteGroup { + TileLayoutSpriteGroup() : SpecializedSpriteGroup() {} NewGRFSpriteLayout dts{}; @@ -244,8 +264,8 @@ protected: ResolverResult Resolve(ResolverObject &) const override { return this; } }; -struct IndustryProductionSpriteGroup : SpriteGroup { - IndustryProductionSpriteGroup() : SpriteGroup() {} +struct IndustryProductionSpriteGroup : SpecializedSpriteGroup { + IndustryProductionSpriteGroup() : SpecializedSpriteGroup() {} 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 diff --git a/src/newgrf_town.cpp b/src/newgrf_town.cpp index d429204e38..5c9ac98427 100644 --- a/src/newgrf_town.cpp +++ b/src/newgrf_town.cpp @@ -156,7 +156,7 @@ static uint16_t TownHistoryHelper(const Town *t, CargoLabel label, uint period, /* Create a new storage. */ 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); t->psa_list.push_back(psa); } diff --git a/src/object_cmd.cpp b/src/object_cmd.cpp index 51331fcc27..3f390f0970 100644 --- a/src/object_cmd.cpp +++ b/src/object_cmd.cpp @@ -90,7 +90,7 @@ void BuildObject(ObjectType type, TileIndex tile, CompanyID owner, Town *town, u 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)); - 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 * get the colour from the company's livery settings. */ diff --git a/src/order_backup.cpp b/src/order_backup.cpp index abd18ef1f4..8de1cbe661 100644 --- a/src/order_backup.cpp +++ b/src/order_backup.cpp @@ -57,7 +57,7 @@ void OrderBackup::DoRestore(Vehicle *v) if (this->clone != nullptr) { Command::Do(DoCommandFlag::Execute, CO_SHARE, v->index, this->clone->index); } 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. */ InvalidateWindowClassesData(WC_STATION_LIST, 0); } @@ -89,7 +89,7 @@ void OrderBackup::DoRestore(Vehicle *v) if (ob->user == user) delete ob; } if (OrderBackup::CanAllocateItem()) { - new OrderBackup(v, user); + OrderBackup::Create(v, user); } } diff --git a/src/order_backup.h b/src/order_backup.h index a4de4eb7bd..24360719f3 100644 --- a/src/order_backup.h +++ b/src/order_backup.h @@ -45,12 +45,13 @@ private: std::vector orders; ///< The actual orders if the vehicle was not a clone. uint32_t old_order_index = 0; + void DoRestore(Vehicle *v); + + friend OrderBackupPool::PoolItem<&_order_backup_pool>; /** Creation for savegame restoration. */ OrderBackup() = default; OrderBackup(const Vehicle *v, uint32_t user); - void DoRestore(Vehicle *v); - public: ~OrderBackup(); diff --git a/src/order_cmd.cpp b/src/order_cmd.cpp index ae606468c2..8ceac01fc8 100644 --- a/src/order_cmd.cpp +++ b/src/order_cmd.cpp @@ -847,7 +847,7 @@ void InsertOrder(Vehicle *v, Order &&new_o, VehicleOrderID sel_ord) { /* Create new order and link in list */ if (v->orders == nullptr) { - v->orders = new OrderList(std::move(new_o), v); + v->orders = OrderList::Create(std::move(new_o), v); } else { v->orders->InsertOrderAt(std::move(new_o), sel_ord); } @@ -1604,7 +1604,7 @@ CommandCost CmdCloneOrder(DoCommandFlags flags, CloneOptions action, VehicleID v } 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); diff --git a/src/rail_cmd.cpp b/src/rail_cmd.cpp index 8f96fe87d6..73477414bf 100644 --- a/src/rail_cmd.cpp +++ b/src/rail_cmd.cpp @@ -1008,7 +1008,7 @@ CommandCost CmdBuildTrainDepot(DoCommandFlags flags, TileIndex tile, RailType ra if (rotate_existing_depot) { SetRailDepotExitDirection(tile, dir); } else { - Depot *d = new Depot(tile); + Depot *d = Depot::Create(tile); MakeRailDepot(tile, _current_company, d->index, dir, railtype); MakeDefaultName(d); diff --git a/src/road_cmd.cpp b/src/road_cmd.cpp index 47a096e5d6..c1cc317a4a 100644 --- a/src/road_cmd.cpp +++ b/src/road_cmd.cpp @@ -1176,7 +1176,7 @@ CommandCost CmdBuildRoadDepot(DoCommandFlags flags, TileIndex tile, RoadType rt, if (rotate_existing_depot) { SetRoadDepotExitDirection(tile, dir); } else { - Depot *dep = new Depot(tile); + Depot *dep = Depot::Create(tile); MakeRoadDepot(tile, _current_company, dep->index, dir, rt); MakeDefaultName(dep); diff --git a/src/roadveh_cmd.cpp b/src/roadveh_cmd.cpp index a6da977cb6..4325fb70a1 100644 --- a/src/roadveh_cmd.cpp +++ b/src/roadveh_cmd.cpp @@ -269,7 +269,7 @@ CommandCost CmdBuildRoadVehicle(DoCommandFlags flags, TileIndex tile, const Engi if (flags.Test(DoCommandFlag::Execute)) { const RoadVehicleInfo *rvi = &e->VehInfo(); - RoadVehicle *v = new RoadVehicle(); + RoadVehicle *v = RoadVehicle::Create(); *ret = v; v->direction = DiagDirToDir(GetRoadDepotDirection(tile)); v->owner = _current_company; diff --git a/src/saveload/afterload.cpp b/src/saveload/afterload.cpp index 371d567d10..138ff5aa86 100644 --- a/src/saveload/afterload.cpp +++ b/src/saveload/afterload.cpp @@ -961,7 +961,7 @@ bool AfterLoadGame() /* From this version on there can be multiple road stops of the * same type per station. Convert the existing stops to the new * internal data structure. */ - RoadStop *rs = new RoadStop(t); + RoadStop *rs = RoadStop::Create(t); RoadStop **head = IsTruckStop(t) ? &st->truck_stops : &st->bus_stops; @@ -2156,7 +2156,7 @@ bool AfterLoadGame() SlError(STR_ERROR_TOO_MANY_OBJECTS); } - Object *o = new Object(); + Object *o = Object::Create(); o->location.tile = (TileIndex)t; o->location.w = size; o->location.h = size; @@ -2251,7 +2251,7 @@ bool AfterLoadGame() * assert() in Pool::GetNew() happy by calling CanAllocateItem(). */ static_assert(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE); 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); } } } diff --git a/src/saveload/industry_sl.cpp b/src/saveload/industry_sl.cpp index 28ce281976..adca7f440e 100644 --- a/src/saveload/industry_sl.cpp +++ b/src/saveload/industry_sl.cpp @@ -260,7 +260,7 @@ struct INDYChunkHandler : ChunkHandler { if (IsSavegameVersionBefore(SLV_161) && !IsSavegameVersionBefore(SLV_76)) { /* Store the old persistent storage. The GRFID will be added later. */ 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)); } if (IsSavegameVersionBefore(SLV_EXTEND_INDUSTRY_CARGO_SLOTS)) { diff --git a/src/saveload/oldloader_sl.cpp b/src/saveload/oldloader_sl.cpp index dcf2851002..93728c955f 100644 --- a/src/saveload/oldloader_sl.cpp +++ b/src/saveload/oldloader_sl.cpp @@ -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::Rating, _cargo_source != 0xFF); 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()); } @@ -1383,7 +1383,7 @@ bool LoadOldVehicle(LoadgameState &ls, int num) if (_cargo_count != 0 && CargoPacket::CanAllocateItem()) { StationID source = (_cargo_source == 0xFF) ? StationID::Invalid() : StationID{_cargo_source}; 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)); } } diff --git a/src/saveload/station_sl.cpp b/src/saveload/station_sl.cpp index d79aa9dfb9..ddb99f9a47 100644 --- a/src/saveload/station_sl.cpp +++ b/src/saveload/station_sl.cpp @@ -399,7 +399,7 @@ public: if (IsSavegameVersionBefore(SLV_161) && !IsSavegameVersionBefore(SLV_145) && st->facilities.Test(StationFacility::Airport)) { /* Store the old persistent storage. The GRFID will be added later. */ 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)); } @@ -426,7 +426,7 @@ public: assert(CargoPacket::CanAllocateItem()); /* 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.status.Set(GoodsEntry::State::Rating); } diff --git a/src/saveload/vehicle_sl.cpp b/src/saveload/vehicle_sl.cpp index 63c45ca784..b315a50455 100644 --- a/src/saveload/vehicle_sl.cpp +++ b/src/saveload/vehicle_sl.cpp @@ -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)) { 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 { v->orders = mapping[v->old_orders]; /* 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. */ assert(OrderList::CanAllocateItem()); - v->orders = new OrderList(); + v->orders = OrderList::Create(); v->orders->first_shared = v; for (Vehicle *u = v; u != nullptr; u = u->next_shared) { u->orders = v->orders; @@ -1143,7 +1143,7 @@ struct VEHSChunkHandler : ChunkHandler { if (_cargo_count != 0 && IsCompanyBuildableVehicleType(v) && CargoPacket::CanAllocateItem()) { /* 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); } diff --git a/src/saveload/waypoint_sl.cpp b/src/saveload/waypoint_sl.cpp index e57d3cc387..c4dcd49130 100644 --- a/src/saveload/waypoint_sl.cpp +++ b/src/saveload/waypoint_sl.cpp @@ -115,7 +115,7 @@ void MoveWaypointsToBaseStations() 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_cn = wp.town_cn; new_wp->name = wp.name; diff --git a/src/ship_cmd.cpp b/src/ship_cmd.cpp index 7b4446de3c..b47ee9ceaf 100644 --- a/src/ship_cmd.cpp +++ b/src/ship_cmd.cpp @@ -871,7 +871,7 @@ CommandCost CmdBuildShip(DoCommandFlags flags, TileIndex tile, const Engine *e, const ShipVehicleInfo *svi = &e->VehInfo(); - Ship *v = new Ship(); + Ship *v = Ship::Create(); *ret = v; v->owner = _current_company; diff --git a/src/signs_cmd.cpp b/src/signs_cmd.cpp index f8b4fb1965..fb5e58bb13 100644 --- a/src/signs_cmd.cpp +++ b/src/signs_cmd.cpp @@ -45,7 +45,7 @@ std::tuple CmdPlaceSign(DoCommandFlags flags, TileIndex til int x = TileX(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(); InvalidateWindowData(WC_SIGN_LIST, 0, 0); diff --git a/src/station_cmd.cpp b/src/station_cmd.cpp index 351f10dfbe..b4a037bc08 100644 --- a/src/station_cmd.cpp +++ b/src/station_cmd.cpp @@ -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 (flags.Test(DoCommandFlag::Execute)) { - *st = new Station(area.tile); + *st = Station::Create(area.tile); _station_kdtree.Insert((*st)->index); (*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); } - RoadStop *road_stop = new RoadStop(cur_tile); + RoadStop *road_stop = RoadStop::Create(cur_tile); /* Insert into linked list of RoadStops. */ RoadStop **currstop = FindRoadStopSpot(is_truck_stop, st); *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 (ge2.link_graph == LinkGraphID::Invalid()) { if (LinkGraph::CanAllocateItem()) { - lg = new LinkGraph(cargo); + lg = LinkGraph::Create(cargo); LinkGraphSchedule::instance.Queue(lg); ge2.link_graph = lg->index; ge2.node = lg->AddNode(st2); @@ -4413,11 +4413,11 @@ static uint UpdateStationWaiting(Station *st, CargoType cargo, uint amount, Sour if (amount == 0) return 0; 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; if (ge.link_graph == LinkGraphID::Invalid()) { if (LinkGraph::CanAllocateItem()) { - lg = new LinkGraph(cargo); + lg = LinkGraph::Create(cargo); LinkGraphSchedule::instance.Queue(lg); ge.link_graph = lg->index; ge.node = lg->AddNode(st); @@ -4714,7 +4714,7 @@ void BuildOilRig(TileIndex tile) return; } - Station *st = new Station(tile); + Station *st = Station::Create(tile); _station_kdtree.Insert(st->index); st->town = ClosestTownFromTile(tile, UINT_MAX); diff --git a/src/story.cpp b/src/story.cpp index 286d776898..d7fb74c943 100644 --- a/src/story.cpp +++ b/src/story.cpp @@ -228,7 +228,7 @@ std::tuple CmdCreateStoryPage(DoCommandFlags flags, Co _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); if (StoryPage::GetNumItems() == 1) InvalidateWindowData(WC_MAIN_TOOLBAR, 0); @@ -272,7 +272,7 @@ std::tuple CmdCreateStoryPageElement(DoCommandF _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); InvalidateWindowClassesData(WC_STORY_BOOK, page_id); diff --git a/src/subsidy.cpp b/src/subsidy.cpp index 0ba5447c54..34f8c08917 100644 --- a/src/subsidy.cpp +++ b/src/subsidy.cpp @@ -172,7 +172,7 @@ static bool CheckSubsidyDistance(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); 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); diff --git a/src/town_cmd.cpp b/src/town_cmd.cpp index f789af8aea..6b2d12817d 100644 --- a/src/town_cmd.cpp +++ b/src/town_cmd.cpp @@ -2253,7 +2253,7 @@ std::tuple CmdFoundTown(DoCommandFlags flags, TileIn if (random_location) { t = CreateRandomTown(20, townnameparts, size, city, layout); } else { - t = new Town(tile); + t = Town::Create(tile); 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; /* Allocate a town struct */ - Town *t = new Town(tile); + Town *t = Town::Create(tile); DoCreateTown(t, tile, townnameparts, size, city, layout, false); diff --git a/src/train_cmd.cpp b/src/train_cmd.cpp index 0ef0f49fec..305e14ac79 100644 --- a/src/train_cmd.cpp +++ b/src/train_cmd.cpp @@ -641,7 +641,7 @@ static CommandCost CmdBuildRailWagon(DoCommandFlags flags, TileIndex tile, const if (!IsCompatibleRail(rvi->railtypes, GetRailType(tile))) return CMD_ERROR; if (flags.Test(DoCommandFlag::Execute)) { - Train *v = new Train(); + Train *v = Train::Create(); *ret = v; v->spritenum = rvi->image_index; @@ -723,7 +723,7 @@ void NormalizeTrainVehInDepot(const Train *u) static void AddRearEngineToMultiheadedTrain(Train *v) { - Train *u = new Train(); + Train *u = Train::Create(); v->value >>= 1; u->value = v->value; 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 y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir]; - Train *v = new Train(); + Train *v = Train::Create(); *ret = v; v->direction = DiagDirToDir(dir); v->tile = tile; diff --git a/src/vehicle.cpp b/src/vehicle.cpp index 0feef76047..7094569d93 100644 --- a/src/vehicle.cpp +++ b/src/vehicle.cpp @@ -2960,7 +2960,7 @@ void Vehicle::AddToShared(Vehicle *shared_chain) if (shared_chain->orders == nullptr) { assert(shared_chain->previous_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; diff --git a/src/vehicle_base.h b/src/vehicle_base.h index 84b82976cd..da817c5fe3 100644 --- a/src/vehicle_base.h +++ b/src/vehicle_base.h @@ -1126,6 +1126,17 @@ struct SpecializedVehicle : public Vehicle { 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 + static inline T *Create(Targs &&... args) + { + return Vehicle::Create(std::forward(args)...); + } + /** * Converts a Vehicle to SpecializedVehicle with type checking. * @param v Vehicle pointer diff --git a/src/water_cmd.cpp b/src/water_cmd.cpp index 2f9814a719..c41c953ec2 100644 --- a/src/water_cmd.cpp +++ b/src/water_cmd.cpp @@ -145,7 +145,7 @@ CommandCost CmdBuildShipDepot(DoCommandFlags flags, TileIndex tile, Axis axis) } if (flags.Test(DoCommandFlag::Execute)) { - Depot *depot = new Depot(tile); + Depot *depot = Depot::Create(tile); uint new_water_infra = 2 * LOCK_DEPOT_TILE_FACTOR; /* Update infrastructure counts after the tile clears earlier. diff --git a/src/waypoint_cmd.cpp b/src/waypoint_cmd.cpp index 3478370f2c..863ca13230 100644 --- a/src/waypoint_cmd.cpp +++ b/src/waypoint_cmd.cpp @@ -281,7 +281,7 @@ CommandCost CmdBuildRailWaypoint(DoCommandFlags flags, TileIndex start_tile, Axi if (flags.Test(DoCommandFlag::Execute)) { if (wp == nullptr) { - wp = new Waypoint(start_tile); + wp = Waypoint::Create(start_tile); } else if (!wp->IsInUse()) { /* Move existing (recently deleted) waypoint to the new location */ wp->xy = start_tile; @@ -401,7 +401,7 @@ CommandCost CmdBuildRoadWaypoint(DoCommandFlags flags, TileIndex start_tile, Axi if (flags.Test(DoCommandFlag::Execute)) { if (wp == nullptr) { - wp = new Waypoint(start_tile); + wp = Waypoint::Create(start_tile); SetBit(wp->waypoint_flags, WPF_ROAD); } else if (!wp->IsInUse()) { /* 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 (wp == nullptr) { - wp = new Waypoint(tile); + wp = Waypoint::Create(tile); } else { /* Move existing (recently deleted) buoy to the new location */ wp->xy = tile;