Sign in to follow this  
xinfinite33

static std::deque inside of template class

Recommended Posts

im having a problem with a static deque inside of one of my classes. i know that you have to initialize static members of a class before you can use them but i cant figure out how to initialize a static deque inside of a template class. a little help please?

 

#include <iostream>
#include <deque>

using namespace std;



template <typename T>
class jar
{
    public:
    T * value;
    static int jars;
    static deque<jar*> jarlist;

    template<typename S>
    jar(S obj) //constructor
    {
        this->value= &obj;
        jars++;
        jarlist.push_back(this);
    }

    void destroy() //destroys a jar
    {
        {
            typename deque<jar*>::iterator iter;

            for (iter=jarlist.begin();iter!=jarlist.end();iter++)
            {
                if(*iter==this)
                {
                    delete (*iter);
                    jarlist.erase(iter);
                }
            }
            jars--;
        }
    }

};

template<typename T> int jar<T>::jars=0;
template<typename T> deque<jar*> jar<T>::jarlist; // <---------------------PROBLEM HERE---------------

int main()
{
    int integer=3;
    jar A(integer);

    cout<<*(jar::jarlist.front())->value);

    return 0;
}

 

any help would be greatly appreciated

Edited by xinfinite33

Share this post


Link to post
Share on other sites
Your constructor contains a bug, it stores a pointer to a local variable as a member. Consider passing a (const) reference, or passing the pointer explicitly.

The destroy function appears to be dangerous, as it attempts to delete objects which are not guaranteed to be allocated with new. Your example program contains this bug.

Your class should probably obey the rule of three, or you should implement a destructor and mark the class as non-copyable.

The "jars" static counter is probably unnecessary, as the deque knowns how many objects it contains.

Finally, such a design is usually unnecessary and the static member can be factored elsewhere, removing or exposing the state dependency. Edited by rip-off

Share this post


Link to post
Share on other sites

Yeah I know its buggy, I was mostly experimenting with templates and pointers as a way to make my own memory management system. It failed, miserably. I guess i should research things a bit more before jumping in head first wacko.png . The "rule of three" and the "non-copyable" articles were helpful, as I had no knowledge about those either. But thanks for the comments and suggestions! smile.png

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this