There is a HasPtr class:
class HasPtr
{
friend void swap(HasPtr&, HasPtr&);
public:
HasPtr(const std::string& s = std::string())
: ps(new std::string(s)), i(0), use(new std::size_t(1)) {}
HasPtr(const HasPtr& hp) : ps(hp.ps), i(hp.i), use(hp.use) { ++*use; }
HasPtr& operator=(HasPtr hp)
{
swap(*this, hp);
return *this;
}
~HasPtr()
{
if (--*use == 0)
{
delete ps;
delete use;
}
}
bool operator<(const HasPtr& rhs)
{
return *ps < *rhs.ps;
}
private:
unsigned i;
std::size_t* use; // counter
std::string* ps;
};
inline void swap(HasPtr& lhs, HasPtr& rhs)
{
using std::swap;
swap(lhs.ps, rhs.ps);
swap(lhs.i, rhs.i);
}
The main function also initializes the vector and then sorts and displays the result:
int main()
{
HasPtr a("A"), b("B"), c("C"), d("D"), e("E");
std::vector<HasPtr> vec{d, a, c, e, b};
std::sort(vec.begin(), vec.end());
for (auto letter : vec)
{
std::cout << *letter.ps << " " << letter.get_use() << " " << std::endl;;
}
return 0;
}
Question: Why does it turn out that every object in the vector has a counter of 3 and how can this be fixed?
>Solution :
Inserting into a vector will create a second copy, increasing the use-count to 2.
Then you have the loop for (auto letter : vec) which iterates using values. I.e. it creates copies of the object inside the vector, increasing the count to 3 while inside the loop.
If you iterate using references instead, as in for (auto const& letter : vec), then the use-count should be left at 2.