简体   繁体   中英

member variable as pointer to template type c++

Suppose I want to make a member variable of a class a pointer to the type that will be given when the class is called. How would I go about doing this? This is what I have so far.

#include <cstdio>

template <typename T>
class myClass {
    T* ptr;

    public:
        myClass(int size);
};  

template <typename T>
myClass<T>::myClass(int size)
{   
    *ptr = new T(size);
}

int main(int argc, char* argv[])
{   
    myClass<int> instance(5);
    return 0;
}   

When I dereference the pointer in the constructor I get the following error: error: invalid conversion from 'int*' to 'int'

This leads me to believe that the so called pointer variable in the class isn't being made a pointer. How can I make it a pointer to whatever type the user passes when the class is instantiated?

*ptr = new T(size);

The type of the expression *ptr is T , not T* .

Write this:

ptr = new T(size);

but then I guess, you don't meant that either. You probably meant this:

ptr = new T[size];

Know the difference between (size) and [size] .

But then if you meant [size] , then you should rather prefer std::vector<T> over T*

Or if you really meant (size) , then use T instead of T* . Or std::unique_ptr<T> if you really need pointer.

Should be ptr = new T[size] . new T[size] has type int* .

Using code like this:

template <typename T>
myClass<T>::myClass(int size)
: ptr(new T[size])
{
}

template <typename T>
myClass<T>::~myClass()
{
   delete [] ptr;
}
  1. You should give a value to your member "ptr", not "*ptr"
  2. According to Scott Meyers' "Effective C++", using initial instead of assign.
  3. Clear out in your destructor.

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