c++stylestemporaries

When should I use temporary variables?


Specifically, I'm wondering which of these I should write:

{
    shared_ptr<GuiContextMenu> subMenu = items[j].subMenu.lock();
    if (subMenu)
        subMenu->setVisible(false);
}

or:

{
    if (items[j].subMenu.lock())
        items[j].subMenu.lock()->setVisible(false);
}

I am not required to follow any style guidelines. After optimization, I don't think either choice makes a difference in performance. What is generally the preferred style and why?

EDIT: the type of items[j].subMenu is boost::weak_ptr. lock() creates a shared_ptr out of it. There is actually an ambiguous difference in the two versions above, regarding how long the temporary shared_ptr lasts, so I wrapped my two examples in { braces } to resolve the ambiguity there.


Solution

  • An alternative method:

    if(shared_ptr<GuiContextMenu> subMenu = items[j].subMenu.lock()) {
        subMenu->setVisible(false);
    }
    //subMenu is no longer in scope
    

    I'm assuming subMenu is a weak_ptr, in which case your second method creates two temporaries, which might or might not be an issue. And your first method adds a variable to a wider scope than it needs to. Personally, I try to avoid assignments within if statements, but this is one of the few cases where I feel its more useful than the alternatives.