Sign in to follow this  
hyyou

Tool for object Lifetime = unique_ptr; Tool for Memory Lifetime = ?

Recommended Posts

As I know, tools for managing object lifetime are :- 

  • std::unique_ptr
  • std::move
  • move constructor
  • move assignment
  • delete copy constructor
  • delete copy assigment

With those tools, it is very obvious to determine owner of any certain object - the owner is the one who stores std::unique_ptr as a field.

However, it is obscure which class actually controls memory allocation.

There are only few tools to help :-

  • the second template parameter of std::unique_ptr
  • the second template parameter of std::vector and other datastructure

None of them indicate which instance of allocator is the ownership of such address.

In a scope of class, it is alarming that underlying memory of a std::unique_ptr (that a class owns) can be deallocated any times. (e.g. from pop operation of scope allocators).

std::unique_ptr<SomeThing> a=scopeAllocator->makeUnique<SomeThing>();
scopeAllocator->pop();
//memory of "a" is invalid!

Are there any tools/techniques to help/prevent it, or at least make thing more obvious for coder?

 

 

 

Share this post


Link to post
Share on other sites
These tools are designed to work best when the object lifetime and allocation lifetime match exactly.

If the object was allocated from a scope allocator, then the scope allocator itself IS the owner. It's not a good idea to use a unique_ptr as well...

Share this post


Link to post
Share on other sites
These tools are designed to work best when the object lifetime and allocation lifetime match exactly.

Thank a lot Hodgman!  It sounds very nice.  

How to make an allocator own the objects?   

  • Should I cache them by void* and cache the correct deleter (function pointer) for each one?   
  • If I understand correctly, any one-frame allocator should also return weak pointer. (?)

i.e. are there any good practice to follow?    

What if the return result is a bit obscure?

template<class T>class CustomVector{
     T* t;//
};
class AISystem{
    public: static CustomVector<NPC_ID> reportAllNearNPC(){
        //use "scopeAllocator" to allocate "CustomVector::t"
    }
};
CustomVector<NPC_ID> a=aiSystem->reportAllNearNPC();
scopeAllocator->pop();
//"a.t" become dangling pointer

Your comment is very valuable - it is better than the chapter "allocator" in every C++ books I have read, thank!

I desire to know more.  If it is not too much to ask, may you recommend name of some good books :D please?

Edited by hyyou

Share this post


Link to post
Share on other sites
When you allocate objects (not PODs) from a scope allocator, then the scope allocator is supposed to call destructors (and release memory). That's the entire reason for using it over a simpler linear allocator. Does it even make sense to wrap objects in unique_ptr then? You'd call destructors twice, and in the strictest sense you are telling lies because now two owners own the object although you say only one does (and only one should). That's really bad.

On the other hand, the calling of destructors and (conceptual) release of memory usually happens at the end of a scope, not when you manually call a pop() function (why would I even want to pop the allocator at an inopportune time?). End of scope may of course mean "end of frame" or "end of level", and it may "manually" call a pop function. But that point in time is exactly well-defined, it's not happening randomly when the objects are still being accessed afterwards. Which means it basically does the same thing unique_ptr would do as well, at the same time, only for a whole bunch of objects.

Share this post


Link to post
Share on other sites
the strictest sense you are telling lies

It is totally reasonable and also enlightens me, thank!   

What if the result value has some pointer inside?

For example, it is a data-structure that may or may not the owner of the underlying data,  should I create 2 classes like this? :-   

//old version
template<class T>class CustomArray{ //type of return result
    unique_pointer<void*> database; //underlying data
};

//new version
template<class T>class WeakArray{
    T* database;
};
template<class T>class StrongArray{
    unique_pointer_toArray<Bullet*> database;//just example
};
//inside a function of some system
WeakArray<Bullet> arr;
arr.t = scopeAllocator->makeWeakArray<Bullet>(5);//similar as new Bullet[5];
return arr;
Edited by hyyou

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Forum Statistics

    • Total Topics
      628281
    • Total Posts
      2981796
  • Similar Content

    • By ForgedInteractive


      Who We Are
      We are Forged Interactive, a small team of like-minded game developers with the sole purpose of making games we love! We're a team of artists, animators, programmers, level designers, writers, composers, producers, and other creative minds. We want to make games that you, the modern gamer want to play! We hope to build a community that enjoys our games as much as we love creating them. With your feedback and support we will be able to achieve that.

      About the Game
      GAME NAME is a fun, action-packed army builder with unique characters, challenges and engaging levels. Set forth on an adventure to protect friends, family and countrymen from new adversaries. Once defeated your enemies turn coat and join you in your adventures. Players can enjoy a range of troops and abilities based on their gameplay style which become more important as maps introduce more challenging terrain, enemies and bosses. Strong orc knights, dangerous shamans, and even a dragon are out on the prowl. Knowing when to fight and when to run, and how to manage your army is essential. Your actions alone decide the fate of this world.

      Previous Work by Team
      Although we are working towards our first game as a team, our team members themselves have past experience in the industry.
      This includes members who have worked on titles including:
      Final Fantasy Kingsglaive, FIFA, Xcom 2 and Civilization.

      Who are we looking for? 3D Modellers Concept Artists Marketing Specialists Level Designer

      What do we expect? Reference work or portfolio. Examples what have you already done and what projects you have worked on academic or otherwise. The ability to commit to the project on a regular basis. If you are going on a two-week trip, we don't mind, but it would be good if you could commit 10+ hours to the project each week. Willingness to work with a royalty based compensation model, you will be paid when the game launches. Openness to learning new tools and techniques
      What can we offer? Continuous support and availability from our side. You have the ability to give design input, and creative say in the development of the game. Shown in credits on websites, in-game and more. Insight and contacts from within the Industry.
      Contact
      If you are interested in knowing more or joining. Please email or PM us on Skype. Myself or Colin will reply to you within 48 hours.

      E-mail: Recruitment@ForgedInteractive.com
      Skype: ForgedInteractive

      Regards,
      David and Colin

      Follow us on:

      Facebook: https://www.facebook.com/ForgedInteractive/
      Twitter: @ForgedInteract
      Youtube: https://www.youtube.com/channel/UCpK..._as=subscriber
      Reddit: https://www.reddit.com/user/Forged_Interactive/
    • By Rannion
      Hi,
      I'm trying to fill a win64 Console with ASCII char.
      At the moment I have 2 solutions: one using std::cout for each line, let's say 30 lines at once using std::endl at the end of each one.
      The second solution is using FillConsoleOutputCharacter. This method seems a lot more robust and with less flickering. But I'm guessing, internally it's using a different table than the one used by std::cout. I'm trying to fill the console with the unsigned char 0xB0 which is a sort of grey square when I use std::cout but when using FillConsoleOutputCharacter it is outputted as the UTF8 char '°'.
      I tried using SetConsoleOutputCP before but could not find a proper way to force it to only use the non-extended ASCII code page...
      Has anyone a hint on this one?
      Cheers!
    • By jhay_u
      so i have this 2D point and click game wherein you play as teenage boy being forced to deal illegal drugs in exchange for your kidnapped sister. 
      the game is currently in production and the game somehow has very few challenges to it according to testers.
      now, im kinda looking for suggestions regarding some puzzles that i could integrate onto the game. the game's theme is somehow dark, serious and true to life. something that happens in real life perhaps.
      some of the mechanics i have is item interaction and dialogue system where responses would vary and affect certain outcomes.
      comments and suggestions would be very much appreciated. thanks!
    • By IMakeBadGames
      https://www.kongregate.com/accounts/IMakeBadGames
      Click "Cube Rain" below. Please tell me what all of you think of it  
    • By INTwindwolf
      THE PROJECT

      INT is a 3D Sci-fi RPG with a strong emphasis on story, role playing, and innovative RPG features such as randomized companions. The focus is on the journey through a war-torn world with fast-paced combat against hordes of enemies. The player must accomplish quests like a traditional RPG, complete objectives, and meet lively crew members who will aid in the player's survival. Throughout the game you can side and complete missions through criminal cartels, and the two major combatants, the UCE and ACP, of the Interstellar Civil War.
      Please note that all of our current positions are remote work. You will not be required to travel.
      Talent Needed
       
      Unity Engine Programmer
      Website Administrator
      Community Manager
      3D Animator
       
      Revenue-Share
      This is the perfect opportunity to get into the game development industry. Being an Indie team we do not have the creative restrictions often imposed by publishers or other third parties. We are extremely conscientious of our work and continuously uphold a high level of quality throughout our project.
      We are unable to offer wages or per-item payments at this time. However revenue-sharing from crowd-funding is offered to team members who contribute 15-20 hours per week to company projects, as well as maintain constant communication and adhere to deadlines. Currently the crowd-funding campaign is scheduled for the year 2018. Your understanding is dearly appreciated.
       
      Thank you for your time! We look forward to hearing from you!
       
      John Shen
      HR Lead
      Starboard Games LLC
  • Popular Now