c++ - what to delete after assignment? -


if have:

template<> char *tobytes<uint64_t>(uint64_t src) {   char *data = new char[8];   //...stuff   return data; }  template<> void write<uint64_t>(char *dst, uint64_t src) {   char *srcbytes = tobytes(src);   (int = 0; < 8; ++i) {     *(dst++) = *(srcbytes++); //am leaking here?   } } 

that gets called like:

char *keyptr = new char[27]; //...stuff write(keyptr, 1234ull); //...write 27 

if delete[] keyptr; have deleted srcbytes? think question is, on line asking if i'm leaking, doing copy , result deleting keyptr leaves srcbytes still deleted?

still learning c++ , it's not clear me when copy constructor called vs assignment operator.

edit 1:

fixed delete per @steephen's answer

edit 2

add tobytes per @whozcraig's comment

you have memory leak. no, delete []-ing keyptrhas nothing srcbytes, independent allocation. 2 addressed buffers unrelated (except content due copy-code).

apart obvious (using std::vector<> , letting raii take on memory management of this), minimal change code plug leak loop this:

template<> void write<uint64_t>(char *dst, uint64_t src)  {     char *srcbytes = tobytes(src);     std::copy(srcbytes, srcbytes+8, dst);     delete [] srcbytes; } 

or using smart pointer:

template<> void write<uint64_t>(char *dst, uint64_t src)  {     std::unique_ptr<char[]> srcbytes(tobytes(src));     std::copy(srcbytes.get(), srcbytes.get()+8, dst); } 

both use std::copy stock algorithm both accomplishes seem want, while retaining original result of tobytes proper cleanup. choose (or perhaps entirely different still) leave you.

best of luck.


Comments