0

I designed my application to run such that I call a raw pointer on a class deriving from a Singleton:

class SimulatedIndexFixingStore : public Singleton<SimulatedIndexFixingStore>
        {
            private:
                friend Singleton<SimulatedIndexFixingStore>;

                typedef std::unordered_map<std::string, std::unordered_map<int, std::map<Date, double>>> Dictionary;

                mutable Dictionary simulatedFixings_;

                SimulatedIndexFixingStore& operator=(const SimulatedIndexFixingStore& ) = delete;

                SimulatedIndexFixingStore(const SimulatedIndexFixingStore& ) = delete;

                SimulatedIndexFixingStore();
                ~SimulatedIndexFixingStore()
                {
                    std::cout << "\nCalling destructor of store...\n";
                }

            public:

                // creates raw pointers to this store and passes them around...
                static SimulatedIndexFixingStore* createPointerToStore()
                {
                    auto tmp = new SimulatedIndexFixingStore() <----- memory allocation on the heap!;
                    return tmp;
                }

        };

I then use the raw pointer generated by the static member function SimulatedIndexFixingStore* createPointerToStore() and pass them around my application.

Question:

  • I don't call delete on the pointer prior to leaving the Main() function as this would call the destructor on the static Singleton instance, so this means I have a memory leak in my app. Correct?

  • I know for a fact that the destructor ~ SimulatedIndexFixingStore() is not getting called because the message is not printed out.

  • The instrument profiler of my application doesn't seem to agree there is a memory leak. Can someone please help me understand?

Thanks, Amine

Amine
  • 134
  • 11
  • 2
    Do note that you're singleton really isn't one since every time you call `createPointerToStore` you get a new object. Use a [Meyers Singleton](https://stackoverflow.com/questions/17712001/how-is-meyers-implementation-of-a-singleton-actually-a-singleton) and all of your problems will be solved. – NathanOliver Sep 27 '19 at 13:51
  • @NathanOliver, thanks for that. I will implement a getInstance() on the derived that returns the one from the Base, as this is how I intend it to be anyway. What puzzles me more is why I can't seem to be having a memory leak, even though I dynamically allocate memory using new operator and I don't explicitly delete it... – Amine Sep 27 '19 at 14:44
  • 1
    You do technically have a memory leak. If you have a `new` without a `delete` you have a memory leak. I can't tell you why your detector is not detecting it. – NathanOliver Sep 27 '19 at 14:48

0 Answers0