3

I know it sound absurd to use weak_ptrs with unique_ptrs, but bear with me please.

I have a set of widgets and animations that act on them. The widgets have a clear owner, who creates and destroys them. All the widgets are created, destroyed, animated in one thread, so one widget can't be destroyed while the animation code is running. As you can see, the widgets are are somehow shared with the animations, but the animation should stop if the widgets gets deleted.

The current approach is to use std::unique_ptr for the owners of the widgets and expose them as raw pointers to the animations. This makes very difficult finding/debugging dangling pointers. One proposal was to change to std::shared_ptr inside the owner class and expose std::weak_ptrs to the animations, but this will add some unwanted/unneeded overhead in the system.

Is it possible (a good idea?) to create some sort of weak_ptr on top of std::unique_ptr that just flags that the pointer was deleted? If yes, can you please suggest me some implementations with minimal overhead for single threaded usage.

EDIT:

One more clarification - the widgets are used in one thread, but the application has multiple threads. Also lots of animations run in parallel and each animation is updated 60 times/second. The overhead from std::shared_ptr/std::weak_ptr comes from the (atomic) counter used inside std::shared_ptr, that actually is not needed in this particular case.

EDIT:

I'm not asking if I can use std::weak_ptr with std::unique_ptr, I know this is not possible. I'm asking if it is a good idea/possible to build something with similar behavior as std::weak_ptr that can be paired with std::unique_ptr

4
  • I guess you could use a unique pointer with a custom deleter that keeps track of not-quite-weak-pointers. I can't see how that would have less overhead than shared_ptr though. I'd just use shared_ptr, since that does exactly what you want. May 21, 2015 at 9:08
  • but instead you are adding overhead by crafting your own unique weak ptr solution, is that good?
    – AndersK
    May 21, 2015 at 9:08
  • 'The overhead [...] comes from the (atomic) counter [...], that actually is not needed in this particular case.' Yes it is, you need some (atomic) value to see if the pointer is valid or not, an atomic boolean (flag) won't make much difference vs an atomic counter.
    – KillianDS
    May 21, 2015 at 9:16
  • @KillianDS I don't need it to be atomic. The widgets are used only in one thread. May 21, 2015 at 9:19

2 Answers 2

2

No, you can't use std::weak_ptr with std::unique_ptr. You make it a std::shared_ptr and expose a std::weak_ptr, just like you said.

As far as the overhead of reference counting is concerned, I highly doubt that will be the bottleneck of your application, so profile and worry about that only when it becomes (probably never) so.

1
  • 1
    I'm not suggesting to use std::weak_ptr because this can't be used. I'm suggesting on building something that behaves like std::weak_ptr, but in the context of std::unique_ptr May 21, 2015 at 9:15
0

Sure, it's a reasonable idea. It provides control over the lifetime of the object while giving the subordinate threads the opportunity of detecting its disappearance.

Of course the lock() method of your weak objects will need to return something that does not itself allow re-sharing.

You can do this by encapsulating existing shared_ptr and weak_ptr objects.

A simple example:

#include <iostream>
#include <memory>

// some type we're going to use for testing
struct Foo {
    ~Foo() {
        std::cout << "Foo destroyed" << std::endl;
    }

    void use() const {
        std::cout << "using Foo" << std::endl;
    }

};

// forward declaration
template<class T> struct weak_object_ptr;

// a pointer that keeps the object alive but is not itself copyable
template<class T>
struct keep_alive_ptr
{
    // make it moveable
    keep_alive_ptr(keep_alive_ptr&&) = default;
    keep_alive_ptr& operator=(keep_alive_ptr&&) = default;

    // provide accessors
    T& operator*() const {
        return *_ptr;
    }

    T* operator->() const {
        return _ptr.get();
    }

private:
    // private constructor - the only way to make one of these is to lock a weak_object_ptr
    keep_alive_ptr(std::shared_ptr<T> ptr)
    : _ptr { std::move(ptr) }
    {}

    // non-copyable
    keep_alive_ptr(const keep_alive_ptr&) = delete;
    keep_alive_ptr& operator=(const keep_alive_ptr&) = delete;

    friend weak_object_ptr<T>;

    std::shared_ptr<T> _ptr;
};

// a weak reference to our shared object with single point of ownership
template<class T>
struct weak_object_ptr
{
    weak_object_ptr(std::weak_ptr<T> w)
    : _weak { std::move(w) }
    {}

    keep_alive_ptr<T> lock() const {
        return keep_alive_ptr<T> { _weak.lock() };
    }
private:
    std::weak_ptr<T> _weak;
};

// a shared object store and lifetime controller
template<class T>
struct object_controller
{

    // helpful universal constructor
    template<class...Args>
    object_controller(Args&&...args)
    : _controller { std::make_shared<T>(std::forward<Args>(args)...) }
    {}

    weak_object_ptr<T> get_weak() const {
        return weak_object_ptr<T> { _controller };
    }

    void reset() {
        _controller.reset();
    }

private:
    std::shared_ptr<T> _controller;
};


// test

using namespace std;

int main(){
    auto foo_controller = object_controller<Foo> {};

    auto weak1 = foo_controller.get_weak();
    auto weak2 = foo_controller.get_weak();

    {
        auto strong1 = weak1.lock();
        strong1->use();
        cout << "trying to destroy Foo\n";
        foo_controller.reset();

        auto strong2 = weak2.lock();
        strong2->use();
        cout << "strong2 going out of scope\n";
    }

    return 0;
}

expected output (note that the destruction of Foo takes place as early as it is legally allowed):

using Foo
trying to destroy Foo
using Foo
strong2 going out of scope
Foo destroyed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.