
On Thu, Dec 13, 2012 at 8:13 AM, Fernando Pelliccioni <fpelliccioni@gmail.com> wrote:
Hi all,
The motivation is to avoid code like the following...
//---------------------------------------------------------------------------- // Usage //----------------------------------------------------------------------------
#include <iostream> #include <string>
struct A { void do_something( std::string s ) const { std::cout << "A::do_something with " << s << " and " << i_ << "\n"; }
int i_ = 99; };
struct Safe { void set_ref( A& a ) { a_ref_ = ref(a); }
void use_ref( std::string s ) const { a_ref_.use( [&s] ( A& a ) { a.do_something(s); }); }
safe_ref<A> a_ref_; };
void usage1() { A a;
Safe safe; safe.use_ref( "hello" ); //null reference, do nothing safe.set_ref(a); safe.use_ref( "hello world!" ); //safe reference, Ok! }
void usage2() { safe_ref<int> si; si.use( [] (int& i ) { std::cout << i << std::endl; });
int temp = 15;
safe_ref<int> si2(temp); si2.use( [] (int& i ) { std::cout << i << std::endl; });
si = ref(temp); si.use( [] (int& i ) { std::cout << i << std::endl; }); } //----------------------------------------------------------------------------
It is similar to optional<T>, but in this case the idea is to not allow access to internal data if the pointer is null, only allowing a safe usage
There is interest to add something like this to Boost? Any comments or remarks?
I don't see how this is better than optional<T&>, sorry. Your Safe wrapper could have been written around optional with the same success, and using lambdas or other function objects to work with references seem overcomplicated to me. Why not this: optional<int&> si(temp) if (si) std::cout << *si << std::endl; Looks simpler and it is clearly apparent that the output statement is executed conditionally on si presence.