Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why at the moment of sorting the object vector the counter of created objects of the class is increased by an additional 2?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading