Re: Replace Gtk::manage() with std::unique_ptr<>?
- From: Jonathan Wakely <gtkmm kayari org>
- To: Ian Martin <martin_id vodafone co nz>
- Cc: gtkmm-list gnome org
- Subject: Re: Replace Gtk::manage() with std::unique_ptr<>?
- Date: Mon, 8 Feb 2016 12:24:42 +0000
On 08/02/16 10:18 +1300, Ian Martin wrote:
As you've said, using unique_pointer mandates a design with only one
access point to the controlled object,
That's not true.
std::unique_ptr mandates one *owner* of the object, but that doesn't
prevent you accessing it through any number of non-owning pointers.
The only caveat is that you must ensure that the object is still valid
for as long as you use the non-owning pointers, i.e. there is still an
owner keeping it alive. Otherwise your non-owning pointers become
dangling and accessing the expired object is undefined behaviour.
If you cannot guarantee that the owning pointer outlives the
non-owning pointers then unique_ptr is not the right solution. Instead
you can use std::shared_ptr as the owner (even if you only have a
single owner) because that allows you to use std::weak_ptr as the
non-owning observer. The benefit of std::weak_ptr is that you can (in
fact, must) check whether there is still a shared_ptr that owns the
object before you access it, so you can never access an expired object
through a weak_ptr, instead you get an empty shared_ptr or an
exception. That means there can be no dangling pointers that have
undefined behaviour when dereferenced.
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]