0

I am writing a simple c++ program in Xcode which has one class Message. In my main I want to declare a new Message and add this to a list messages. Xcode is suggesting I use:

messages.push_front(*new Message(messageID));

Can anyone explain what the *new does. Am I dynamically allocating memory for the Message object or is it creating a instance of Message on the stack? I have checked in Xcode and there are no memory leaks if use this and do not delete the instance so I assume it is allocating on the stack.

renzo_cast
  • 81
  • 4
  • 1
    _"I have checked in Xcode and there are no memory leaks if use this and do not delete the instance so I assume it is allocating on the stack."_ How did you check this? Your assumption is completely wrong. – πάντα ῥεῖ Apr 26 '15 at 00:28
  • clearly I have a lot more to learn. I was using Xcode's leaks instrument which I thought wasn't showing any issues. But thanks for the feedback. – renzo_cast Apr 27 '15 at 08:08
  • What type is `messages`? Is it a `std::deque`? Your code looks like a leak. I wonder if XCode's suggestion is just seeing that you are calling `push_front`, which I suspect takes a `const Message&`, and seeing that you are calling it with a `Message` pointer and so suggests you need to dereference it, without warning you that that's a leak. You probably want `messages.push_front(Message(messageID));`. – Ben Nov 22 '19 at 17:25

1 Answers1

0

You are allocating a Message dynamically on the heap and then dereference it to pass it by reference.

One of the overloads of push_back is push_back(const T& value), so the value is first allocated on heap then dereferenced and its reference passed to the function.

Now this is useless, as you could directly allocate it with Message(messageID) and pass it to the method. In addition you are generating a leak since there is no delete associated with new, and you can't release it since you don't bind the returned pointer anywhere.

In addition directly passing a Message(messageID) and possibly using emplace_back instead that push_back could save from a copy construction of the object inside the collection.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • Thank you for the clear explanation. I also noticed I could use Message(messageID) but was just wondering what *new does as I couldn't find any information on this. Extra thanks for the advice on emplace_back. I haven't heard of this and will look into it. – renzo_cast Apr 27 '15 at 08:12
  • Here you can find why and how `emplace_back` could be better: http://stackoverflow.com/questions/23717151/why-emplace-back-is-faster-than-push-back – Jack Apr 27 '15 at 09:35