VS 2015 c++ compile issue -
i have code snipped i've been using while create dynamic arrays, , stopped working.
this meant create dynamic array without use of vector in c++ console applications. older programs have worked fine in past no longer compile while included though.
int main() { int n = 5; allocatearray newarray(n); int *myarray = newarray.create(); delete[] myarray; return 0; } class allocatearray { private: int *newarray; int size; public: allocatearray(int); int* create() { return (newarray = new int[size]); } ~allocatearray() { delete newarray; } }; allocatearray::allocatearray(int n) { size = n; }
with in header
int* allocatearray(int n);
this error log, can find whats happening?
severity code description error c2065 'allocatearray': undeclared identifier error c2146 syntax error: missing ';' before identifier 'newarray' error c3861 'newarray': identifier not found error c2065 'newarray': undeclared identifier error c2228 left of '.create' must have class/struct/union
move declaration of allocatearray
before main()
.
as user @joachimpileborg explains:
c++ needs symbols use declared (and defined) before used.
class allocatearray { private: int *newarray; int size; public: allocatearray(int); int* create() { return (newarray = new int[size]); } ~allocatearray() { delete[] newarray; // changed 'delete[]' 'delete' } }; int main() { int n = 5; allocatearray newarray(n); int *myarray = newarray.create(); //delete[] myarray; // error: delete called allocatearray's destructor. return 0; } allocatearray::allocatearray(int n) { size = n; }
warning
you deleting same pointer p twice. once in allocatearray
's destructor , once in main()
. p returned create()
function myarray
in main()
. delete it, @ end of main()
, allocatearray
's destructor called , tries delete p again.
notes
you should check out raii idiom if plan on allocating arrays yourself. however, should consider using std::vector<t>
instead, manages memory (and provides useful range of functionalities).
Comments
Post a Comment