Re: [Vala] can a struct be stored in a map?
- From: Stefan Risberg <steffenomak gmail com>
- To: Evan Nemerson <evan coeus-group com>
- Cc: vala-list gnome org
- Subject: Re: [Vala] can a struct be stored in a map?
- Date: Sat, 30 Jun 2012 23:45:32 +0200
On Sat, Jun 30, 2012 at 02:26:29PM -0700, Evan Nemerson wrote:
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
That is true, I just think I'm thinking to much c/c++ for my own good.
But I don't know how Gee.HashMap does after it is deallocated, but
if it reacts like lists/maps usally does why no just store a pointer of
the struct in the map and let it clean up all allocated structs after it
goes out of scope?
But that would probably defeat the purpos of having a memory management
scheme in vala. But if the speed is so crucial for the program then that
would maybe be the correct way to go, by using structs and pointers. Other
then that one should just go with using classas... maybe.
Stefan
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]