C++同時プログラミング実戦第6章問題
1408 ワード
C++同時プログラミング実戦第6章、コードリスト6.4キュー実現——単線程版
まず、データ構造を定義する場合headはunique_ptr,tailは2つのunique_を使用するのではなく、オリジナルポインタです.ptr、ここでは同じnullptrアドレスの2回のdeleteを避けることを意味します.スマートポインタのデフォルトdeleter(std::default_delete)はdeleteスタックの後にnullptrにポインタを置くことはありません.これは問題ありません.皆さんが見ている間に疑問があるかもしれません.
その後、queueは構造関数関数体が空であり、原生ポインタタイプのtailと組み合わせて、明らかな野ポインタ(スタックでqueueを使用する場合)
最後にtry_popでは、headが最後のノードを指す場合try_pop,tailは不正な位置を指す
template
class queue
{
private:
struct node
{
T data;
std::unique_ptr next;
node(T data_):
data(std::move(data_))
{}
};
std::unique_ptr head; // 1
node* tail; // 2
public:
queue()
{}
queue(const queue& other)=delete;
queue& operator=(const queue& other)=delete;
std::shared_ptr try_pop()
{
if(!head)
{
return std::shared_ptr();
}
std::shared_ptr const res(
std::make_shared(std::move(head->data)));
std::unique_ptr const old_head=std::move(head);
head=std::move(old_head->next); // 3
return res;
}
void push(T new_value)
{
std::unique_ptr p(new node(std::move(new_value)));
node* const new_tail=p.get();
if(tail)
{
tail->next=std::move(p); // 4
}
else
{
head=std::move(p); // 5
}
tail=new_tail; // 6
}
};
まず、データ構造を定義する場合headはunique_ptr,tailは2つのunique_を使用するのではなく、オリジナルポインタです.ptr、ここでは同じnullptrアドレスの2回のdeleteを避けることを意味します.スマートポインタのデフォルトdeleter(std::default_delete)はdeleteスタックの後にnullptrにポインタを置くことはありません.これは問題ありません.皆さんが見ている間に疑問があるかもしれません.
その後、queueは構造関数関数体が空であり、原生ポインタタイプのtailと組み合わせて、明らかな野ポインタ(スタックでqueueを使用する場合)
最後にtry_popでは、headが最後のノードを指す場合try_pop,tailは不正な位置を指す