C++ Memory::owner_less



Instead of value-based type ordering, this function gives us owner-based mixed type ordering for both std::weak ptr and std::shared ptr. These two smart pointers only match equivalently when both of them share ownership due to the order in which they have been placed. Or if both of them are empty despite the fact that the values we acquired from the getter methods of raw pointers were different.

These compare weak pointers with shared pointers on the basis of their owner-based. The address of the control block is ordered by "owner_less". In this case, if two shared or weak pointers have the same ownership, they are treated as equivalent.

Syntax

Following is the syntax for C++ Memory::owner_less −

struct owner_less;
struct owner_less<shared_ptr<T>>;
struct owner_less<weak_ptr<T>>;

Parameters

  • Ptr − Its a managed pointer.
  • T − It indicate the type of object pointed by the managed pointer type.

Example 1

Let's look into the following example, where we are going to use the owner_less and getting the output.

#include <iostream>
#include <memory>
#include <set>
struct X {};
int main(){
   X* Y = new X();
   std::shared_ptr<X> A(Y);
   std::shared_ptr<X> B(Y);
   std::set<std::shared_ptr<X>> set1;
   set1.insert(A);
   std::cout << set1.size() << std::endl;
   set1.insert(B);
   std::cout << set1.size() << std::endl;
   std::set<std::shared_ptr<X>, std::owner_less<std::shared_ptr<X>>> set2;
   set2.insert(A);
   std::cout << set2.size() << std::endl;
   set2.insert(B);
   std::cout << set2.size() << std::endl;
}

Output

Let us compile and run the above program, this will produce the following result −

1
1
1
2
free(): double free detected in tcache 2
Aborted (core dumped)

Example 2

Following is the another example, where we are going to use the owner_less and retriveing the output.

#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);
   std::set < std::shared_ptr<int> > value_based;
   std::set < std::shared_ptr<int>, std::owner_less<std::shared_ptr<int>> > owner_based;
   value_based.insert (a);
   value_based.insert (b);
   owner_based.insert (a);
   owner_based.insert (b);
   std::cout << "value_based.size() is " << value_based.size() << '\n';
   std::cout << "owner_based.size() is " << owner_based.size() << '\n';
   delete p;
   return 0;
}

Output

On running the above code, it will display the output as shown below −

value_based.size() is 2
owner_based.size() is 1
Advertisements