Date: Wed, 03 Apr 2024 18:41:53 -0500
you want the container to return a std::optional not a null reference. the nice thing about a reference is in practice nobody writes code to make them null even though it is easy and works as expected in most cases (i have done it to prove a point. No I won't share more, the conclusion is don't do that)
throwing an exception is sometimes a useful alternative, as is the std::expected variant of exceptions. Optional is likely what you want, and it is much less confusing.
throwing an exception is sometimes a useful alternative, as is the std::expected variant of exceptions. Optional is likely what you want, and it is much less confusing.
-- Henry Miller hank_at_[hidden] On Wed, Apr 3, 2024, at 17:57, Frederick Virchanza Gotham via Std-Proposals wrote: > Back in 1993, they were talking about null references: > > http://www.virjacode.com/cxxproposals/compstdcxx/article86414 > > If we were to have null references now 31 years later, here's how I'd do them: > > int &myref = *nullptr; > > Normally it's undefined behaviour to dereference a nullptr, but if you > dereference the compile-time constant expression 'nullptr', you get > the null reference. And so then if you write a function that takes a > reference, you can check if it's a null reference as follows: > > void Func(int &arg) > { > if ( arg == *nullptr ) return; > } > > You can use a static_cast to get a null reference of a specific type: > > static_cast<MyClass&>( *nullptr ); > > As Pascual said back in 1993, this would be useful for a method that > returns an element from a container: > > Y& X::operator[](size_t index){...} > > If your index is out of range, the method returns a null reference. > -- > Std-Proposals mailing list > Std-Proposals_at_[hidden] > https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
Received on 2024-04-03 23:42:14