What is the difference between these usages: the new SubElement () and SubElement ()?

In the class constructor, I need to create some objects on the fly and add them to the vector. Here is my code:

ContainerClass::ContainerClass() {
   for (int i = 0; i < limit; i++)
      elements.push_back(SubElement());
}

Is it the same with the new SubElement ()? Should I still free SubElement () objects in the ContainerClass destructor?

+3
source share
4 answers

Method 1:

If you have std::vector<SubElement> elements;
then you should use elements.push_back(SubElement()).

SubElement()creates SubElementon the stack, and then a copy is added to vector.

You should not call deletefor individual items vector. They will be destroyed and freed when it vectorgoes beyond.

Method 2:

If you have std::vector<SubElement*> elements;
then you should use elements.push_back(new SubElement()).

new SubElement() SubElement , vector.

delete , vector , . delete .

+6

SubElement(): , SubElement(): .

: , .

+1

- .

SubElement() () , .

new SubElement() . , .

+1

. - , , , , , .

++ - - , .

new . , . , .

( & ), , , , .

, , (.. ::std::vector<SubElement *> c), , new. ( ) . "" . , .

(.. ::std::vector<SubElement> c), c.push_back(SubElement()), . , . , , , .

There is a way to get a container to take control of pointers, but only indirectly. You can have copies of objects that you take over in the container. For this, ordinary class people are used ::std::tr1::shared_ptr<T>. Your container declaration would look like this: ::std::vector< ::std::tr1::shared_ptr<SubElement> > c. Then you can: c.push_back(new SubElement());and the container will remove the SubElement objects when this is done.

You have to read shared_ptrand really understand what it does before using it, though.

+1
source

Source: https://habr.com/ru/post/1739612/


All Articles