Makes push_back () a "new" object earlier to add to std :: list in C ++

I am new to the C ++ standard library. I want to use std :: list. I know that if I create a list myself, instead of using stl, I have to allocate memory for a new object and then add it to the list.

list of c-style class A:

A *ptrA = new A();     
ptrA->setElement(value);
ptrA->next = null;
currentPositionMyCstyleList->next = ptrA;
ptrA->prev = currentPositionMyCstyleList;

If I use stl, do I need a "new" object? Does push_back () a "new" object before to add to std :: list in C ++?

Is the code below correct?

A aObj(value);     
listA.push_back(aObj); // Will push_back() "new" an object and copy the value of aObject to the object before add it to list

Will the aObj value be released in the code below:

funcAddToList() {
    A aObj(value);     
    listA.push_back(aObj);
}
funcDispList() {
    // display listA  // Does the value of aObj still in list?
}

What does push_back () actually do?

I am still confused after reading stl_list.h_push_back () , _ M_insert , _ M_create_node

Thank you for your time.

+4
5

POD, push_back , . a-ka , , ( push_back).

0

push_back std::list .

, , .

+2

...

. new ( ). , .

++ 11, emplace_back, //, .

emplace_back , ...

, :

list.push_back(std::move(v));

, .

+2

A std::list .

std::list<MyObj> list1;
list.push_back(MyObj()); // push an anonymous object (rvalue)
MyObj a;
list.push_back(a); // push (copy) a

std::list<MyObj*> list2;
list2.push_back(new MyObj());
MyObj* b = new MyObj();
list2.push_back(b);

list1 - MyObj, , MyObj . list2 - , , .

push_back . list2 - , , .

( rvalue) - "" : , . push_back.

+1

, push_back std::list , new ( malloc()). .


Your second snippet is correct. aObjcopied.

The third copy of the fragment aObjwill remain in the list, and it aObjwill be deleted.

+1
source

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


All Articles