2

my question is similar into this one, but I hadn't found info that I need. I have my class constructor.

CustomTreeViewItem::CustomTreeViewItem(CustomTreeView* list) 
    : m_childs(), m_expanded(false), m_list(list), m_components(), m_depth(1), 
    m_rect(), m_root(this)
{}

I use this pointer in constructor but do not call any methods from that so I do not invoke undefined behavior. So everything is fine, but I got warning, now I'm writing some lib (little framework) so I have to write error-free code. So I have changed my code into this:

CustomTreeViewItem::CustomTreeViewItem(CustomTreeView* list) 
    : m_childs(), m_expanded(false), m_list(list), m_components(), m_depth(1), 
    m_rect(), m_root(NULL)
{
    m_root = this;
}

Now I do not get any warning, however in this way I lose performance (very slightly, but anyway it is loss). I want to ask if there isn't any way to keep the highest performance and prevent this warning.

Community
  • 1
  • 1
ST3
  • 8,826
  • 3
  • 68
  • 92
  • Are you sure that you lose performance with optimization enabled? Doesn't seem to make a difference for the assembly generated by g++ here. Also, you could use `#pragma` to disable warnings if you know exactly what you're doing. – nikolas Sep 23 '13 at 13:51
  • @nijansen this will be used for new projects and for old (very old) so compilers variates. – ST3 Sep 23 '13 at 13:54

2 Answers2

5

If the pointer is only stored for later use, the Standard guarantees this is perfectly safe.

You likely will need to use a pragma to disable the warning. And warning control is non-portable (other compilers will likely just ignore your pragma and continue to warn).

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
1

First thing is that the compiler should not complain about that, the next thing is that the alternative version of the code, where the m_root is set to NULL (should be nullptr) and later to this will most probably not have a performance impact at all. Any optimizing compiler should be able to merge both writes into a single write with this. Take a look at the assembly. Even if that triggered an extra write, the variable is hot, so it is just an L1 write and the cost would not be noticeable.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
  • Fully agree with that; and from what I've tested so far compilers agree with that as well if you compile with optimization enabled. – nikolas Sep 23 '13 at 14:10