首先,讓我指出你的列表通常不應該包含相同的節點。如果需要列表之間的共享對象,請保存指向節點中對象的指針或引用,而不是共享節點本身。
如果您必須共享節點本身,您需要的是reference counting。
實際上,你所做的是跟蹤指針或對特定對象的引用的數量(在一個變量中),並且只有當數字變爲0時釋放內存,指示不能再達到該對象應該被釋放。
要使用STL進行引用計數,可以使用shared_ptr
,它自C++ 11以來位於STL中。
struct node
{
node(const data_t&);
data_t data;
std::shared_ptr<node> next;
};
auto head1 = std::make_shared(some_data1);
auto head2 = std::make_shared(some_data2);
head1->next = std::make_shared(some_data);
head2->next = head1->next;
//note that you do NOT copy the raw pointer, you must copy the shared_ptr itself
head1.reset(); //destroys some_data1 but not some_data
head2.reset(); //destroys some_data2 and some_data
請勿交叉鏈接您的列表。除此之外,使用'std :: shared_ptr'並讓運行時間排除它。 – WhozCraig
請分享代碼和錯誤。 – Awais
請提供最少重複性的例子。 – user31264