1. type is a variable of type T. I haven't ever tried to pass a 'type' like 'int' to a function.
2. Moreover, with what type specification 'T' are you calling the template class?
3. target is a pointer to type T but you are making it point to a variable of type 'type'.
EDIT: Your function prototype is contradictory. The variable type cannot be of type T if it is supposed to be an int or a float itself. IMO you should remove this parameter. Combining keskiverto's points,
1 2 3 4 5 6 7 8
template <class T>
void fge::fge_New(T * &target, int amount) // target is reference to pointer.
{
target = new T [amount + 1]; // target is pointing to data of type T.
if(!target)
fge_BailOut("could not allocate that much ram");
target = NULL;
}
'target' is a local variable within fge_New. It is initialized with a copy of the value hold by the pointer parameter that the function is called with. Call to fge_New does not modify 'obj' of main().
dynamic memory and pointers are still hard for me i was trying to make examples to get a better understanding i tried to fix it as much as i can but still seems i have problems
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#ifdef __cplusplus
#include <cstdlib>
#else
#include <stdlib.h>
#endif
#include "FGE/fge.h"
int main ( int argc, char** argv )
{
int * obj;
fge::fge_New(obj, 14);
return 0;
}
1 2
template <class T>
staticvoid fge_New(T * target, int amount);
1 2 3 4 5 6 7 8
template <class T>
void fge::fge_New(T * target, int amount)
{
target = new (std::nothrow)T * ((amount + 1) * sizeof(T));
if(!target)
fge_BailOut("could not allocate that much ram");
target = NULL;
}
you cannot implement a template function like other function. template functions must be entirely visible to the compiler when instantiate (called). In other words: move the function to the header file.
This is the correct way to write it:
1 2 3 4 5 6 7 8
template <class T>
void fge::fge_New(T * target, int amount)
{
target = new (std::nothrow)T[amount + 1];
if(!target)
fge_BailOut("could not allocate that much ram");
target = NULL;
}
all you do is wasting memory though
obj in main is not modified. why do you set target to null after allocating?