Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22035

c++ template weird optimization

$
0
0

I wrote a singleton template class just like boost does:

template <typename _T>
class Singleton
{ 
    public :
    static _T* Instance()
    {
        static _T obj;
        return &obj;
    }

protected :
    Singleton() {}

private :
    struct ObjectCreator
    {
        ObjectCreator()
        {
            Singleton<_T>::instance();
        }
    };

    static ObjectCreator object_creator;
};

template <typename _T>
typename Singleton<_T>::ObjectCreator Singleton<_T>::object_creator;

And I wrote the main function to test it.

#include "Singleton.h"
class A : public Singleton <A>
{
    public:
        int a;
};


int main()
{
    A::Instance()->a = 2;
}

I know I mistyped Instance in ObjectCreator's constructor, the weird thing is I can compile it correctly by gcc-4.4.7, then I used clang-6.0, it hit me with the typo.

I guess gcc can do some optimization, because I did not do anything with ObjectCreator, so it ignored the error code.

I have two questions:

  1. What should I do to make gcc report me that error (without changing my code), like add some compiler flag?
  2. If anyone has a more reliable explanation for this? Some official doc would do.

Ps: I am aware that boost would add a do_nothing function in ObjectCreate and call it from Singleton<_T>:: Instance() to avoid this optimization.


Viewing all articles
Browse latest Browse all 22035

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>