類模板
<memory>

std::owner_less

template <class Ptr> struct owner_less;template <class T> struct owner_less<shared_ptr<T>>;template <class T> struct owner_less<weak_ptr<T>>;
基於所有者的less比較操作
此類定義了函式物件,它們對 shared_ptr 和/或 weak_ptr 物件執行基於所有者的比較。

這是 less(或 operator<)的替代品,用於對這些型別進行排序,當排序需要基於它們的所擁有的指標而不是它們的儲存的指標(這是 operator< 比較的內容)時使用。

一個 shared_ptr 物件的儲存的指標(即,它 解引用到的指標)可能與其所擁有的指標(即,在物件銷燬時被刪除的指標)不同,如果該 shared_ptr 物件是一個別名(由別名構造的物件及其副本)。

由...執行的比較owner_less::operator()依賴於 shared_ptrweak_ptr 的成員函式 owner_beforeowner_less定義了一個介面,該介面模仿了 binary_function,並帶有額外的過載。其實現行為與
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
template<class P> struct owner_less;  // not defined

template<class T> struct owner_less <shared_ptr<T>>
{
  typedef bool result_type;
  typedef shared_ptr<T> first_argument_type;
  typedef shared_ptr<T> second_argument_type;
  bool operator() (const shared_ptr<T>& x, const shared_ptr<T>& y) const {return x.owner_before(y);}
  bool operator() (const shared_ptr<T>& x, const weak_ptr<T>& y) const {return x.owner_before(y);}
  bool operator() (const weak_ptr<T>& x, const shared_ptr<T>& y) const {return x.owner_before(y);}
};

template<class T> struct owner_less <weak_ptr<T>>
{
  typedef bool result_type;
  typedef weak_ptr<T> first_argument_type;
  typedef weak_ptr<T> second_argument_type;
  bool operator() (const weak_ptr<T>& x, const weak_ptr<T>& y) const {return x.owner_before(y);}
  bool operator() (const shared_ptr<T>& x, const weak_ptr<T>& y) const {return x.owner_before(y);}
  bool operator() (const weak_ptr<T>& x, const shared_ptr<T>& y) const {return x.owner_before(y);}
};


模板引數

Ptr
被管理的指標的型別,根據所擁有的資源進行排序,並作為成員類型別名first_argument_typesecond_argument_type.
T
被管理的指標型別所指向的物件的型別。

成員型別

以下別名是owner_less.

成員型別定義說明
result_typebool操作的結果
first_argument_typePtr第一個引數的型別
second_argument_typePtr第二個引數的型別

成員函式

operator()
返回值true如果第一個引數在基於其所擁有的指標的嚴格弱序中被認為在第二個引數之前。
該函式使用 shared_ptr::owner_before 和/或 weak_ptr::owner_before 來確定此順序。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// owner_less example
#include <iostream>
#include <memory>
#include <set>

int main ()
{
  int * p = new int (10);

  std::shared_ptr<int> a (new int (20));
  std::shared_ptr<int> b (a,p);  // alias constructor: co-owns a, points to p

  // standard set container: cannot contain duplicates.
  std::set < std::shared_ptr<int> > value_based;  // uses std::less
  std::set < std::shared_ptr<int>, std::owner_less<std::shared_ptr<int>> > owner_based;

  value_based.insert (a);
  value_based.insert (b);  // ok, different value

  owner_based.insert (a);
  owner_based.insert (b);  // overwrites (same owned pointer)

  std::cout << "value_based.size() is " << value_based.size() << '\n';
  std::cout << "owner_based.size() is " << owner_based.size() << '\n';

  delete p;
  return 0;
}

輸出
value_based.size() is 2
owner_based.size() is 1


另見