Sign in to follow this  
hyyou

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

Recommended Posts

hyyou    223

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
Hodgman    51338
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
hyyou    223
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
hyyou    223
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  

  • Similar Content

    • By the incredible smoker
      Hi, i have a question about accessing the sound buffer for win32.
      How do i do that ?
       
      I like to fill it with bytes, so i can generate realtime digital audio.
       
      thanks in advance
    • By Ivanotus
      Hi, I'm the director of "Project Sentinels".
      Our game will be a 2D top-down view Action-RPG, made with Game Maker, with influences from Zelda, Dark Souls, Monster Hunter and The Witcher.
      We're actively looking for hobbyist 2D artists (ideally two) that will be tasked with the creation of the sprites and mapping for our game. The style of the art isn't fixed yet and can be talked about.
      The game, as of right now, is nothing but a good bunch of documentation and ideas waiting to be put into practice. The main story and characters, the world background and lore and game mechanics (combat, dialogues and others) are already written down.
      Synopsis:
      For the moment, there's no money involved. We're all students that use some of our free time to work on a videogame. We'll try to crowdfund our game in the future, and the money that will be potentially earned will be equally shared.
      If you're interested, send me a PM or add me in Discord (Ivanotus#0984) and there I'll answer any question you may have.

    • By Modymek
      hi all
      I want to enable and disable shader in MPCH Media player Classic
      the MPCH have shader option using HLSL shaders
      I want the shader to read each file extension before it plays the file
      so if the video file name is video.GR.Mp4 it will play it in Grayscale shader 
      if it is not and standard file name Video.Mp4 without GR. unique extension so it plays standard without shader or end the shader
      here is the shader I have for grayscale
      // $MinimumShaderProfile: ps_2_0
      sampler s0 : register(s0);
      float4 main(float2 tex : TEXCOORD0) : COLOR {
          float c0 = dot(tex2D(s0, tex), float4(0.299, 0.587, 0.114, 0));
          return c0;
      }
       
      I want to add if or block stantement or bloean to detect file name before it call the shader in order to go to the procedure or disable it or goto end direct without it
       
      any thoughts or help
    • By noodleBowl
      I've gotten to part in my DirectX 11 project where I need to pass the MVP matrices to my vertex shader. And I'm a little lost when it comes to the use of the constant buffer with the vertex shader
      I understand I need to set up the constant buffer just like any other buffer:
      1. Create a buffer description with the D3D11_BIND_CONSTANT_BUFFER flag 2. Map my matrix data into the constant buffer 3. Use VSSetConstantBuffers to actually use the buffer But I get lost at the VertexShader part, how does my vertex shader know to use this constant buffer when we get to the shader side of things
      In the example I'm following I see they have this as their vertex shader, but I don't understand how the shader knows to use the MatrixBuffer cbuffer. They just use the members directly. What if there was multiple cbuffer declarations like the Microsoft documentation says you could have?
      //Inside vertex shader cbuffer MatrixBuffer { matrix worldMatrix; matrix viewMatrix; matrix projectionMatrix; }; struct VertexInputType { float4 position : POSITION; float4 color : COLOR; }; struct PixelInputType { float4 position : SV_POSITION; float4 color : COLOR; }; PixelInputType ColorVertexShader(VertexInputType input) { PixelInputType output; // Change the position vector to be 4 units for proper matrix calculations. input.position.w = 1.0f; // Calculate the position of the vertex against the world, view, and projection matrices. output.position = mul(input.position, worldMatrix); output.position = mul(output.position, viewMatrix); output.position = mul(output.position, projectionMatrix); // Store the input color for the pixel shader to use. output.color = input.color; return output; }  
    • By ilovegames
      Beat Spirit is a fun game in the Side-Scroller genre with elements of RPG. You'll have to fight the undead in different locations and under varying conditions. The playroom is generated, so you will always have to wait for something new and different. Earn gold and discover new things! The game is quite hardcore and unusual. Try something new
      Download https://falcoware.com/BeaterSpirit.php



  • Popular Now