Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

c++ - instruct std::list.push_back() to make use of the heap allocated memory address

As far as I know std::list stores it's elements internally in a doubly linked list format which means heap memory is allocated. Suppose if I already have a variable that is heap allocated using new, can I instruct std ::list push_back() function to make use of this memory in it's internal doubly linked list instead of freshly allocating new memory and then copy the data into that new memory. This is a sample code:

#include <iostream>
#include <list>

struct St {
    int a;
    int b;
};

int main()
{
    std::list<St> St_list;
    St *st = new St;
    st->a = 1;
    st->b = 2;

    St_list.push_back(*st); // can i instruct St_list to use the memory address of st
    
    std::cout << st << std::endl;
    std::cout << &St_list.back() << std::endl;
    
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The simplest answer is NO, the memory cannot be re-used.

To explain a little - the internal node class of std::list does not keep the "pointer" to value - but value itself. This node is defined more or less like this:

template <class T>
struct List_Node {
   T value; 
   List_Node* prev;
   List_Node* next;
}; 

So there is no possibility to "re-use" allocated memory.

But - nodes can be transferred between std::list<T> objects with splice, thus we can avoid reallocation.

std::list<St> st{{1,2}};

std::list<St> St_list;
St_list.splice(St_list.end(), st);
// now st is empty, St{1,2} is in St_list - no "reallocation" happened


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...