I have a class template that keeps track of all instances of a specific instance of the class template with a list of pointers. In the constructor, I push_back(this)
to add the created instance to the class. If I create an instance within main
, it works fine. But if I create a global instance, the constructor causes an error. The error is from the list.push_back()
and it says that the insertion iterator is out of range of the container. I have recreated the bug with minimal code.
Header file
#ifndef HEADER_H
#define HEADER_H
#include <iostream>
#include <list>
template<typename T>
class A
{
public:
static std::list<A<T>*> l;
A( T t ) : val( t ) { l.push_back( this ); }
~A() { l.remove( this ); }
T val;
void print() { std::cout << val; }
};
template<typename T>
std::list<A<T>*> A<T>::l;
#endif
Source file
#include "Header.h"
A<int> temp( 0 );
void main()
{
temp.print();
char c;
std::cin >> c;
}
I'm guessing it has something to do with the constructor call order, but does anyone know how to fix this?