Re: [Vala] can a struct be stored in a map?



On Sat, 2012-06-30 at 22:55 +0200, Stefan Risberg wrote:
But if you don't need reference counting and just need data holding like in
his example wouldn't a struct be much better then a class?

Well, he didn't really go into detail about his use case, but we know
that he wants to use it with a Gee.HashMap, so he might be doing
something like this:

Entry entry = {
    id: 1,
    name: "foo",
    data: "data",
    count: 42,
    dirty: false
  };
hash_map.set (id, entry);

// somewhere else
Entry entry = hash_map.get (id);


Now first an entry struct gets created on the stack.  So far, so good.
Next a copy of that struct gets put into the hash_map, since HashMap
needs a copy and we can't just give it ours since we might do something
else with entry later.  Now, you might be thinking you could just do
hash_map.set (id, (owned) entry) to give it our copy, but our copy is on
the stack--it will be released when the function goes out of scope, so
we still need to copy it to the heap.

Then, when you want to retrieve the entry from the HashMap, another copy
gets made... HashMap still needs its copy, and we need one too.

If you were using GLib.HashTable instead of Gee.HashMap, the get method
would return an unowned reference, meaning we could avoid a copy with
unowned Entry? entry = hash_table.get (id).  However, it's easy to
forget to add "unowned", especially if you use type inferencing.


-Evan




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