1
4

3 回答 3

3
*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.

于 2013-09-12T18:15:01.777 回答
0

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

于 2013-09-12T18:15:08.073 回答
0

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.
于 2013-09-12T18:37:27.343 回答