Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Recommended to use smart pointer here?  (Read 2799 times)

0 Members and 1 Guest are viewing this topic.

stubbie

  • Newbie
  • *
  • Posts: 5
    • View Profile
Recommended to use smart pointer here?
« on: July 13, 2024, 01:37:03 am »
I am currently working on an isometric terrain generation engine and was wondering if it would be best to use smart pointers for storing chunk objects. Currently my chunks are stored like so and are loaded and removed in the following functions. Within my chunks map if I changed the chunk to std::unique_ptr<Chunk> would this be a good use case of smart pointers? I don't have much experience using them so I am struggling to determine if this is a good idea or not.

   std::map<std::pair<int,int>, Chunk> chunks;

void chunkManager::loadChunk(int chunkX, int chunkY){  
  sf::Vector2i blockCoords(chunkX * Chunks::size, chunkY * Chunks::size); //converted from chunk space to blocks in game space

  //chunk doesnt exist in map
  if(chunks.find({chunkX, chunkY}) == chunks.end()){
    auto chunk = Chunk();
    chunk.setBlocks(blockCoords, perlin);
    chunks[{chunkX, chunkY}] = chunk;
  }
  window.draw(chunks[{chunkX, chunkY}]);
}

void chunkManager::unloadChunk(){
  for(auto it = chunks.begin(); it != chunks.end();){
    if(std::abs(chunkPosition.x - it->first.first) > Manage::renderDistance ||
       std::abs(chunkPosition.y - it->first.second) > Manage::renderDistance){
      it = chunks.erase(it);
    }else{
      it++;
    }
  }
}
« Last Edit: July 19, 2024, 02:51:49 pm by eXpl0it3r »

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11034
    • View Profile
    • development blog
    • Email
Re: Recommended to use smart pointer here?
« Reply #1 on: July 19, 2024, 02:59:41 pm »
Smart pointers mostly come into play when you have to decide on an ownership model and you have multiple actors involved.
"Who" (i.e. what class) will own the object?
If you have multiple classes that should own the object, you have a shared ownership and thus a shared_ptr might be the way to go - there are often better designs than to use shared_ptr.
If you just have a single owner, then unique_ptr might be the way to go.

Containers can also take on the role of being owners, as such in your example, you won't benefit from using an uinque_ptr, as your std::map is already the owner of all the chunks.
What's important here, is that you either always access the map directly or use a reference/iterator to the stored chunk, as to prevent any unnecessary copies and breaking the ownership of the map.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/