当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Template & memory-allocation

问题描述:

#include <iostream>

template<class T> T CreateArray(T a, int n)

{

a = new T [n]; // mistake: double* = double**

return a;

}

int main()

{

double* a;

int n = 5;

a = CreateArray(a,n);

return 0;

}

can I allocate memory using a template and new? And what my mistake?

网友答案:

Your code has some wrong things. First, you can do something like what you're trying to do, but you should write something like this:

template<class T> T* CreateArray(int n)
{
    T* a = new T [n];
    return a;
}

int main()
{
    double* a;
    int n = 5;
    a = CreateArray<double>(n);
    return 0;
}

Note that you don't have to pass the a array (it will be copied inside CreateArray, and its changes won't be visible inside main). Note also that you define the template to returning a pointer T*, that is what main() a is expecting.

网友答案:

So others have explained why your code doesn’t work and how it can be improved.

Now I’ll show how you can still get the following code to compile – and to work properly:

 double* a = CreateArray(5);
 int* b = CreateArray(7);

The problem, as already mentioned, is that C++ does not infer template arguments from return types alone.

You can circumvent this limitation by making the above function return a simple proxy object. The proxy object has a single operation: an (implicit) conversion to T*. This is where the actual allocation happens.

The CreateArray function is therefore very simple (and not a template):

CreateArrayProxy CreateArray(std::size_t num_elements) {
    return CreateArrayProxy(num_elements);
}

As for the proxy:

struct CreateArrayProxy {
    std::size_t num_elements;

    CreateArrayProxy(std::size_t num_elements) : num_elements(num_elements) { }

    template <typename T>
    operator T*() const {
        return new T[num_elements];
    }
};

Easy as π.

Now, should you use this code? No, probably not. It offers no real advantage over direct allocation. But it’s a useful idiom to know.

网友答案:

You want to accept a pointer to the type you want to allocate:

template<class T> T* CreateArray(T* a, int n)
{
    a = new T [n];
    return a;
}

This should do the trick.

网友答案:

I prefer to keep empty pointers value NULL.

#include <iostream>

template<class T> bool CreateArray(T * &a, int n)
{
    if ( a != 0 )
      return false;
    a = new T [n];
    return true;
}

int main()
{
    double* a = 0;
    int n = 5;
    CreateArray(a,n);
    return 0;
}

vector could be a good solution, too. I think it is better one, because you won't make memory leak(s).

#include <vector>

int main()
{
    std::vector<double> a;
    int n = 5;
    a.resize(n);
    return 0;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: