So the first question is: if I can convert the stack object (obj2) to a heap object so that it doesn't get freed after create () completes?
This line:
_obj2 = &obj2;
Change to:
_obj2 = new Class(obj2);
I need a direct answer, not the arrogant "you're doing it wrong," as many have done.
This is the direct answer you can get. Obviously, you are new to C ++, so I’m sure it will work as planned, because you probably made a couple of mistakes in defining the class "Class" (by the way, a terrible name).
It would also be useful to convert back to a stack object.
class obj3(*_obj2);
The second question: a concrete example of heap objects, the “wrong” one, was to create a new vector <string> * using the new operator. If dynamically allocating STL objects is wrong, then what is the right way?
Why are you dynamically highlighting a vector. Just create it locally.
std::vector<std::string> funct() { std::vector<std::string> vecString;
Using new / delete uses C ++, for example C. What you need to read is smart pointers. These are those that control the life of an object and automatically delete the object when they go out of scope.
std::auto_ptr<Class> x(new Class);
Here x is a smart pointer (like auto_ptr), when it goes out of scope, the object will be deleted. But you can return the auto_ptr of the calling function and it will be safely transferred from the function. This is actually much more complicated than you, and you need a book.
Obviously, if you create them as stack objects, this fails because they are freed immediately,
Its de'allocated when it goes beyond.
but they told me (again, a very high-ranking member) that their dynamic allocation could ruin the bunch.
If you do it wrong. This, given your knowledge, is very likely. But it’s hard to check, since you did not specify a class definition.
So what is the right way to do this?
- Find out why you should use stack objects.
- Find out what smart pointers are.
- Learn how to use smart pointers to manage lifespans.
- Explore the different types of smart pointers.
- See what separation of problems is (you do not follow this basic principle).