Hello All,
I am trying to use vectors of weak_ptrs and at times I need to know if the vector contains a "pointer" that "point" to the same item. Below is a simplified example of what I am trying to do...
#include <iostream>
#include <vector>
#include <algorithm>
#include <memory>
using namespace std ;
// Return true if either they have both expired or they both "point" to the
// same object.
bool operator== (const weak_ptr<int>& lhs, const weak_ptr<int>& rhs )
{
cout << "In specialised ==" << endl;
return ( lhs.lock() == rhs.lock() ) ;
}
int main()
{
// Create some shared_ptrs from which we will create the weak_ptrs
shared_ptr<int> Sp1 {new int } ;
shared_ptr<int> Sp2 {new int } ;
shared_ptr<int> Sp3 {new int } ;
shared_ptr<int> Sp4 {new int } ;
// Create the weak_ptrs
weak_ptr<int> Wp1 {Sp1} ;
weak_ptr<int> Wp2 {Sp2} ;
weak_ptr<int> Wp3 {Sp3} ;
weak_ptr<int> Wp4 {Sp4} ;
// Put weak_ptrs into the vector
vector<weak_ptr<int>> Vwp {Wp1, Wp2, Wp3, Wp4} ;
// Verify that my operator == method is working as I expect.
if (Wp1 == Wp2) cout << "That's odd!" << endl;
else cout << "That was expected" << endl;
weak_ptr<int> Wp5{ Wp1 };
if (Wp1 == Wp5) cout << "Wp1 equals Wp5 -- good" << endl;
else cout << "Wp1 not equals Wp5 -- bad" << endl;
// The block of code that fails...
if ( find ( Vwp.begin(), Vwp.end(), Wp2 ) == Vwp.end() ) cout << "Not in list" << endl ;
else cout << "In list" << endl ;
}
Because weak_ptr does not provide an operator== method, I have provided my own. I have added code that checks that the operator== is doing what I want it to do (and certainly at a simplistic level it does). My problem is that I cannot use std::find with
the vector of weak_ptrs. I get the following compiler error:
Error C2678 binary '==': no operator found which takes a left-hand operand of type 'std::weak_ptr<int>' (or there is no acceptable conversion) Project1 C:\Program Files (x86)\Microsoft
Visual Studio 14.0\VC\include\xutility 3134
I do not understand this, since I have provided and operator== (and I know it "works" because if I comment out the "find" code the program behaves as I expect).
I can work around this by using "find_if" and a lambda -- but so far I have not been able to get any elegant code that is anywhere near as obvious as to what I am trying to do.
Can anyone tell me why my example does not work (especially as as I have provided an operator==)? If find / vector / and weak_ptr cannot be made to work together, can anyone suggest code to replace the find that does not obfuscate the intention.
Thanks in advance.
Andrew Ch