[Home]Add Options Should Use References Rather Than Pointers - Program Options Suggestion

BOOST WIKI | RecentChanges | Preferences | Page List | Links List

Difference (from prior major revision) (no other diffs)

Changed: 1,61c1

add_options() should use references rather than pointers

Back to Suggestions - program options library

Why have pointers to parameter values, rather than references? References make more sense, in that, semantically, a pointer can have a null value, whereas in this context, there's no meaning to a null value. Reference is the right semantics, not pointer. So, we'd have:

("magic", parameter<int>("value", magic), "magic value for the program")

instead of

("magic", parameter<int>("value", &magic), "magic value for the program")

- People/Chuck Messenger

That's the matter of style. I like to pass modifiable argument by pointer, so that it's clear that they will
be modified.

- People/Vladimir Prus

I think that semantics is wrong. Pointers are not there to signify an argument might change. That's what
const is for -- if it's a non-const reference, then the argument can change. Use a const reference if it can't change.

Semantically, a pointer is an optional reference. My feeling is that, unless it makes
sense for the pointer to be null, then you should use a reference, where possible. The point is
to catch as many errors as possible at compile time. Also, the point is to advertise your
API as accurately as possible. Pointer advertises "optional value".

- People/Chuck Messenger

After some usage, I've actually found another case which might speak in favour of pointers. Code snippet (please forgive me, I'm going from memory here)

int some_data[2] = { 2, 3 };

// ...

("--option", parameter("x y", some_data), "Pair of values specifying some data");

My solution is a template function parameter that looks like this:

template<class T, int N>
parameter(const char* desc, T array[N]);

but since there's another function taking T* as parameter, it's eating my call to parameter("x y", some_data) and I have to use instead parameter<int, 2>("x y", some_data). I haven't really thought this thru. I might be horribly off-track.

- People/Marcelo Magallon

BOOST WIKI | RecentChanges | Preferences | Page List | Links List
Edit text of this page | View other revisions
Last edited September 12, 2008 1:45 pm (diff)
Disclaimer: This site not officially maintained by Boost Developers