有没有办法使用模板专门化来分隔new和new []?

Mar*_*lon 14 c++ templates specialization

我有一个自动指针类,在构造函数中我传入一个指针.我希望能够从新的[]在构造函数中分离出来的新,这样我可以正确地调用删除或析构函数删除[].这可以通过模板专业化来完成吗?我不想在构造函数中传入一个布尔值.

    template <typename T>
    class MyAutoPtr
    {
    public:
      MyAutoPtr(T* aPtr);
    };

// in use:
MyAutoPtr<int> ptr(new int);
MyAutoPtr<int> ptr2(new int[10]);
Run Code Online (Sandbox Code Playgroud)

Kon*_*lph 7

很不幸的是,不行.两者都返回相同的类型T*.考虑使用调用适当重载构造函数的构建器函数:

template <typename T>
class MyAutoPtr
{
public:
    MyAutoPtr(T* aPtr, bool array = false);
};

template <typename T>
MyAutoPtr<T> make_ptr() {
    return MyAutoPtr<T>(new T(), false);
}

template <typename T>
MyAutoPtr<T> make_ptr(size_t size) {
    return MyAutoPtr<T>(new T[size], true);
}
Run Code Online (Sandbox Code Playgroud)

现在您可以按如下方式实例化对象:

MyAutoPtr<int> ptr = make_ptr<int>();
MyAutoPtr<int> ptr2 = make_ptr<int>(10);
Run Code Online (Sandbox Code Playgroud)


vis*_*tor 3

std::unique_ptr在 C++0x 中将有一个动态数组的专门化,有点像下面所示。然而,实例化适当的实例将是用户的任务。在语言级别,没有办法区分一个指针和另一个指针。

template <class T>
class pointer
{
    T* p;
public:
    pointer(T* ptr = 0): p(ptr) {}
    ~pointer() { delete p; }
    //... rest of pointer interface
};

template <class T>
class pointer<T[]>
{
    T* p;
public:
    pointer(T* ptr = 0): p(ptr) {}
    ~pointer() { delete [] p; }
    //... rest of pointer and array interface
};

int main()
{
    pointer<int> single(new int);
    pointer<int[]> array(new int[10]);
}
Run Code Online (Sandbox Code Playgroud)

此外,在一个类中加载如此多的任务可能也不是那么好。例如,boost 有shared_ptrshared_array