Hi Preston,

If you change `initField2()` to `getField2()`, you'll get the behavior you
want.

This is a somewhat unfortunate quirk in the nature of default values and
Cap'n Proto memory allocation. Imagine you had a very deep default value,
with a tree of nested structs. When you call the getter for that field the
first time, the implementation needs to make a copy of the whole default
value into the message proper so that you can modify it. However, it may be
that you're going to modify it to something that isn't nested. In that
case, not only has a bunch of time been wasted copying the tree and
allocating objects, but because of the arena-style memory allocation, the
objects you remove still end up taking space in the message.

Hence, I introduced "init" with a different policy: "init" always allocates
exactly one object, initialized to the *type*'s default value --which
always corresponds to zeros on the wire due to the XOR defaults trick.
Hence "init" is always the fastest possible thing, but then it's up to you
to set the fields.

In all honesty, I don't think I've ever set a default value on a
struct-typed field, so I'm not sure if it was worth having them (and hence
this confusion) in the first place. Oh well.

This is actually mentioned in the docs, but admittedly it's easy to miss...

https://capnproto.org/cxx.html#structs

-Kenton

On Sun, May 14, 2017 at 10:24 PM, Preston Elder <[email protected]> wrote:

> So according to the spec (https://capnproto.org/language.html#structs)
> the following schema should be valid:
>
> struct FieldWithFlags(Type) {
>     value @0 : Type;
>     flag1 @1 : Bool = false;
>     flag2 @2 : Bool = false;
> }
>
>
> struct MyRecord {
>    field1 @0 : FieldWithFlags(Text);
>    field2 @1 : FieldWithFlags(Text) = (flag1 = true);
> }
>
>
> However when I use this, using the C++ compiled code, when I do:
>
> auto field2 = myRecord.initField2();
> printf("%d, %d\n", field2.getFlag1(), field2.getFlag2());
>
>
> Will always print 0 0.  In other words, it ignored the default of true for
> flag1 I set in MyRecord.
>
> I get the same result even if I DON'T default the values of flag1 and
> flag2 in FieldWithFlags.
>
> I'm using CapnProto 0.5.3.
>
> Is there something I'm missing?  Is this a bug?  It should be defaulting
> the flag1 for field2 to true.
>
> Preston
>
> --
> You received this message because you are subscribed to the Google Groups
> "Cap'n Proto" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> Visit this group at https://groups.google.com/group/capnproto.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Cap'n Proto" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
Visit this group at https://groups.google.com/group/capnproto.

Reply via email to