Jump to content

  • Log In with Google      Sign In   
  • Create Account


#Actualsednihp

Posted 17 January 2013 - 09:40 AM

When I want to put something on the screen I do something like this...


std::shared_ptr button1(new GUIButton(g_width/2-125,g_height/2-125,0,250,100,"(L)oad Default Scenario",updatestate));
button1->SetShortCut(ALLEGRO_KEY_L);
button1->SetZOrder(1);
UIelements.push_back(button1);

Now I may do that 2000 times on a single screen for all the various elements on the map (which worked fine as "raw" pointers)

In my main game loop I have this...
Instead of using new, use std::make_shared<T> instead, i.e.

std::shared_ptr button1 = std::make_shared<GUIButton>(g_width/2-125, g_height/2-125, 0, 250, 100, "(L)oad Default Scenario", updatestate);
Make_shared is exception safe and uses the same call to allocate the memory for the reference counting block and the resource itself, reducing construction overhead (and hey, if you're doing something 2000 times you want to do it the most efficient way possible)

For more advice on how to use shared_ptr I found the MSDN article excellent (there are equivalent articles on unique_ptr, weak_ptr and general smart pointers as well)

If you didn't have to call setShortCut() and setZOrder() I would have recommended emplace_back as well,

UIElements.emplace_back(std::make_shared<GUIButton>(g_width/2-125, g_height/2-125, 0, 250, 100, "(L)oad Default Scenario", updatestate));
Which constructs the element in place in the vector

#1sednihp

Posted 17 January 2013 - 09:40 AM

When I want to put something on the screen I do something like this...
 

    std::shared_ptr button1(new GUIButton(g_width/2-125,g_height/2-125,0,250,100,"(L)oad Default Scenario",updatestate));
    button1->SetShortCut(ALLEGRO_KEY_L);
    button1->SetZOrder(1);
    UIelements.push_back(button1);
 
Now I may do that 2000 times on a single screen for all the various elements on the map (which worked fine as "raw" pointers)
 
In my main game loop I have this...

 

Instead of using new, use std::make_shared<T> instead, i.e.

 

 

std::shared_ptr button1 = std::make_shared<GUIButton>(g_width/2-125, g_height/2-125, 0, 250, 100, "(L)oad Default Scenario", updatestate);

 

Make_shared is exception safe and uses the same call to allocate the memory for the reference counting block and the resource itself, reducing construction overhead (and hey, if you're doing something 2000 times you want to do it the most efficient way possible)

 

For more advice on how to use shared_ptr I found the MSDN article excellent (there are equivalent articles on unique_ptr, weak_ptr and general smart pointers as well)

 

If you didn't have to call setShortCut() and setZOrder() I would have recommended emplace_back as well,

 

 

UIElements.emplace_back(std::make_shared<GUIButton>(g_width/2-125, g_height/2-125, 0, 250, 100, "(L)oad Default Scenario", updatestate));

 

Which constructs the element in place in the vector


PARTNERS