[Development] Improving toInt, toLong, etc.

Olivier Goffart olivier at woboq.com
Wed Feb 5 19:04:10 CET 2014


On Wednesday 05 February 2014 09:44:39 Thiago Macieira wrote:
> Em qua 05 fev 2014, às 12:36:42, Matthew Woehlke escreveu:
> > On 2014-02-05 12:19, Thiago Macieira wrote:
> > > Em qua 05 fev 2014, às 10:37:27, Robert Knight escreveu:
> > >>> The idea was to silently return a default-constructed type.
> > >> 
> > >> I'm not keen on that. Aside from adding extra restrictions to the
> > >> types that the class can be used with as you mention,
> > >> it runs the much more severe risk of masking serious bugs.
> > > 
> > > No way around it if we exclude exceptions.
> > > 
> > > We need to return something.
> > 
> > ...or you could abort, which I assume is what operator* does?
> 
> That doesn't help.
> 
> First, Q_ASSERT() is eliminated in a debug build, so we're left with no
> abort.
> 
> Second, even if we stick a real call to qFatal() there, we don't have the
> "noreturn" annotation in all compiles -- particularly, it's not there for
> MSVC because qFatal *can* return there. That means we still must return
> something.

You will just have an undefined behaviour.  You will return the content of the 
uninitialized memory cast to the type, and it will likely cause a crash later.  
Debug build will abort,  release build will probably crash somehow too.
Same as QList::at()

// possible implementation
T &QOptional<T>::operator*() { 
   Q_ASSERT(isValid());
   return reinterpret_cast<T&>(data);
};


-- 
Olivier 

Woboq - Qt services and support - http://woboq.com - http://code.woboq.org



More information about the Development mailing list