What does std::owner_less do?

2474 views c++
8

I've read that std::owner_less performs "owner-based rather than value-based" ordering, that two smart pointers are equivalent if they "point to subobjects of the same object" - what does that exactly mean?

As a test case, I have written the following code:

struct T {};

int main() {
    T* t = new T();

    std::shared_ptr<T> a(t);
    std::shared_ptr<T> b(t);

    std::set<std::shared_ptr<T>> set1;
    set1.insert(a);
    std::cout << set1.size() << std::endl;
    set1.insert(b);
    std::cout << set1.size() << std::endl;

    std::set<std::shared_ptr<T>, std::owner_less<std::shared_ptr<T>>> set2;
    set2.insert(a);
    std::cout << set2.size() << std::endl;
    set2.insert(b);
    std::cout << set2.size() << std::endl;
}

And the output is 1 1 1 2. It seems to me that if std::owner_less performs "owner-based" comparison, shouldn't it consider a and b to be the same, while the default comparator treats them as different? The result of my code seems to be saying just the opposite though.

answered question

1 Answer

8

std::shared_ptr<T> a(t);
std::shared_ptr<T> b(t);

This is undefined behavior when the shared_ptrs are destroyed.

posted this

Have an answer?

JD

Please login first before posting an answer.

Related

Ads

Categories