xcode - Using *new in c++ -
this question has answer here:
- delete & new in c++ 8 answers
i writing simple c++ program in xcode has 1 class message. in main want declare new message , add list messages. xcode suggesting use:
messages.push_front(*new message(messageid));
can explain *new does. dynamically allocating memory message object or creating instance of message on stack? have checked in xcode , there no memory leaks if use , not delete instance assume allocating on stack.
you allocating message
dynamically on heap , dereference pass reference.
one of overloads of push_back
push_back(const t& value)
, value first allocated on heap dereferenced , reference passed function.
now useless, directly allocate message(messageid)
, pass method. in addition generating leak since there no delete
associated new
, , can't release since don't bind returned pointer anywhere.
in addition directly passing message(messageid)
, possibly using emplace_back
instead push_back
save copy construction of object inside collection.
Comments
Post a Comment