Re: Best practise inheritance



On Tue, 2017-03-21 at 18:27 +0100, S. Jacobi wrote:
On Mon, 20 Mar 2017 16:01:39 +0000
Tristan Van Berkom <tristan vanberkom codethink co uk> wrote:



Use instance private data, this will not need any priv pointer and
can be done with th G_DEFINE_TYPE_WITH_PRIVATE() macro, and another
to lookup your private data inside your C file (under the hood,
this
uses negative instance offsets with power nter arithmatic, so
public
and private data are on the same allocated memory slice)


This is still a bit unclear to me, because I found no good reference
what instance private data really is, apart from a patch on the
mailing
list. So is it just GObject "magic" that puts private fields into
special memory locations and can therefore retain ABI compatibility?
Because from what I read, I define my structs the same way.

struct _MyType
{
  GtkWidget   parent;
  MyTypePriv *priv;
}
G_DEFINE_TYPE (MyType, my_type, GTK_TYPE_WIDGET)

and

struct _MyType
{
  GtkWidget   parent;
  MyTypePriv *priv;
}
G_DEFINE_TYPE_WITH_PRIVATE (MyType, my_type, GTK_TYPE_WIDGET)

would be first a struct with "normal" private data and second a
struct
with instance private data. Or am I completely on the wrong track
here?

This describes a bit of what you're after:

   https://developer.gnome.org/gobject/stable/howto-gobject-code.html

The key points here are that:

  o MyType structure does not need any 'priv' pointer, as it can be
    looked up at any time.
  o G_DEFINE_TYPE_WITH_PRIVATE() expects that a MyTypePrivate structure
    is defined above
  o G_TYPE_INSTANCE_GET_PRIVATE() can be called in your C file to
    access the allocated MyTypePrivate structure for a given instance.

    See: https://developer.gnome.org/gobject/stable/gobject-Type-Inform
ation.html#G-TYPE-INSTANCE-GET-PRIVATE:CAPS

At the end of the day, the main memory slice for an object instance
will be created with space for your MyTypePrivate structure, but the
sizeof() that structure will be computed at runtime so it does not
effect ABI.

This means:
  o No need for allocating an extra pointer to point to private data
  o Less overall memory fragmentation, because private data is
    allocated on the object instance itself.
  o I believe the lookups with G_TYPE_INSTANCE_GET_PRIVATE() are just
    as cheap as the pointer dereference (as it will be implemented
    using simple pointer arithmetic).

Cheers,
    -Tristan



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]