A bit of background for the structures bindings proposal

[This note from Bjarne provides some background for the updated structured bindings proposal posted yesterday. --Ed.]

 

In the context of the C++ Core Guidelines, we (Herb Sutter, Gabriel Dos Reis, me, and few others) were discussing sources of bugs and inefficiencies. We noticed that returning multiple values (e.g., from a tuple) was one of the two remaining sources of uninitialized variables. We noticed that there were real cases of bugs and inefficiency (from default initialization followed by assignment rather than initialization) stemming from separating variable introduction from initialization. Use of tie() is at best a partial solution that doesn’t get to the root of the problem.

The next day or so, Herb had a first draft of a proposal. We refined it, adding use cases and implications. I noted that we had a syntax in concepts for the introduction of multiple names that we could borrow. We noted that whatever we came up with had to fit into our ideas for a possible future far-more-general pattern matching design. We always try to ensure that a proposal doesn’t block an important potential evolution path. The design document for the proposal was refined and extended.

It was now obvious that the proposal completed C++’s mechanism for returning multiple values from a function: With structured binding, we can initialize a set of values, {x,y,z},  just as we  can return a set of values, {e1,e2,e3}.

In web discussions, and especially at the Kona standards meeting, many alternatives were discussed. We focused on how to deal with user-defined types with private members. The new feature mustn’t discourage encapsulation by providing a convenient notation for structs only. We also considered whether explicit declaration of types were needed and how to achieve conversions. A conversion from a char[] in a return value to a string was considered particularly desirable by several people. These two needs were both addressed by adding the ability for users to define get<N> functions for a class. Jens Maurer refined the proposed wording and in doing so found a few weaknesses in the design.

For the details and code examples, you can find the current proposal and wording papers here for the upcoming meeting in Jacksonville.

Add a Comment

Comments are closed.

Comments (1)

0 0

petke said on Feb 11, 2016 03:38 PM:

"3.2 Should this syntax support initialization from a braced-init-list?"

Yes. Generalisation of syntax was reason enough for "uniform initialization" to be accepted into the language. Special case syntax is surprising to users, and harder for them to learn and remember.



std::vector<int> a = {1, 2, 3}; //works.
auto {x,y,z} = {1, 2, 3}; //should work.

auto b = {1, 2, 3}; //works (type of b is initializer_list).
auto c = {1, "two", 3}; //should work (type of c is tuple?).