简体   繁体   中英

Error deleting pointers in a vector

I´m running into a problem with this piece of code: First I create a class like this:

template <typename T1, typename T2> class MyClass
{
private:

    std::vector<T2> m_values;

    static const bool HAS_POINTER = std::is_pointer<T2>::value;
};

T2 could be, depending on the needs, either a type or a pointer. My problem is when i try to release the pointers:

template<typename T1, typename T2> void MyClass<T1, T2>::Clear()
{
     if (HAS_POINTER)
     {
         for (int i = 0; i < m_values.size(); ++i)
             delete m_values[i];
     }
}

Here the compiler complains showing error C2541: Cannot delete objects that are not pointers I know the compiler is right, but the problem is T2, in some cases, IS a pointer. How do I deal with this? Thank you in advance.

You can partially specialise templates for pointers. Here is a very simple example:

#include <vector>
#include <iostream>

template <typename T1, typename T2> class MyClass
{
public:
    std::vector<T2> m_values;

    void Clear()
    {
        std::cout << "no pointers\n";
    }
};

template <typename T1, typename T2> class MyClass<T1, T2*>
{
public:
    std::vector<T2*> m_values;

    void Clear()
    {
        std::cout << "pointers\n";

        for (int i = 0; i < m_values.size(); ++i)
            delete m_values[i];

    }
};

int main()
{
    MyClass<int, int> example;
    MyClass<int, int*> example2;
    example.Clear();
    example2.Clear();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM