Using a function to create an object in a queue

I am having some issues wrapping my brain around how use a function to create an object in a queue. Below is my current relevant code. I am creating a pointer for the object as the object will be one of several children based on user input.


In main:
1
2
std::queue<MyObject> MyQueue;
p1Queue.push(MyFunction(1));


Creation function:
1
2
3
4
5
6
7
8
9
MyObject MyFunction(int num)  {

   MyObject* ObjPtr = 0;

   ObjPtr = new MyObject;

   return ObjPtr;
}


I understand that this code is wrong because I am attempting to return a pointer as an object, but I am just not sure how to pass or create the object around the function in a correct manner.
Last edited on
Instead of creating a container of Objects, create a container of Object pointers.

1
2
std::queue<MyObject*> objects;
objects.push_back(new MyObject());


However, using new in any sense requires that you delete your objects as well, unless you're using smart pointers.
With smart pointers, you can simply create a container of smart object pointers, and not have to worry about clean up.

1
2
3
4
5
6
7
#include <memory>

typedef std::shared_ptr<MyObject> MyObjectPtr;
//std::shared_ptr<> is one of the smart pointers available.

std::queue<MyObjectPtr> objects;
objects.push_back(MyObjectPtr(new MyObject()));



*edit* typo
Last edited on
Thanks xismn! That was exactly what I needed. I think I was just thinking about it backwards.
Topic archived. No new replies allowed.