I have created the following class (in a header file):
#ifndef HASPTR_H
#define HASPTR_H
#include <iostream>
#include <string>
class HasPtr
{
public:
HasPtr(const std::string &);
HasPtr(const HasPtr &);
HasPtr & operator=(const HasPtr &);
friend bool operator<(const HasPtr &, const HasPtr &);
friend void swap(HasPtr &, HasPtr &);
~HasPtr();
private:
int m_x;
std::string *m_strPtr;
};
inline bool operator<(const HasPtr &lhs, const HasPtr &rhs)
{
return (*lhs.m_strPtr < *rhs.m_strPtr);
}
inline void swap(HasPtr &lhs, HasPtr &rhs)
{
using std::swap;
swap(lhs.m_x, rhs.m_x);
swap(lhs.m_strPtr, rhs.m_strPtr);
std::cout << "Swap executed\n";
}
#endif // !HASPTR_H
Although I have provided a custom swap function for HasPtr
objects, std::swap
is called by the stl sorting algorithm instead of the above swap
function, after running the following code:
#include "stdafx.h"
#include <algorithm>
#include "HasPtr.h"
#include <vector>
int main()
{
HasPtr hp1("zzzzzzzzzzzzzz"), hp2("aaaaaaa"), hp3("cccccccccc");
std::vector<HasPtr> hpVec{ hp1, hp3, hp2 };
std::sort(hpVec.begin(), hpVec.end());
return 0;
}
What is wrong? Thanks in advance