Jon Stewart on 17 May 2003 00:27:01 -0000 |
[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]
Re: [ALACPP] Chris' stupid C++ trick of the week |
> So, this is a little off the core purpose of this list, but I thought > I'd share a C++ tidbit. I'd say this is quite on-topic. > template<typename T> > T& doFoo(T& aTarget) { > //do something with aTarget > return aTarget; > } ... > The object referenced by aBar may be destroyed when you exit the doFoo() > block (and obviously before the caller gets a chance to look at it). > How? Well, the compiler actually has the option of passing arguments to > doFoo() by value. Of course this is only in the special case of a > parameter passed as a ref to a const. I didn't know compilers were allowed to do that. It seems patently broken. Someone needs to rant at Bjarne about that. > 1) Use compile time assertions to ensure that the template is not > instantiated on const types. > > 2) Make sure Bar's copy constructor is private, and better still with > pure virtual functions which will cause a linker error in the event that > you get by the privacy restriction. > > 3) Use a typelist to limit the types which my generic function can take > to a select set of non-const types. > > 4) Use a compiler that always inlines templated function calls. ;-) Well, I'd prefer specifying the function as inline. It's not guaranteed to work -- compilers always have the option of not-inlining -- but... I'd bet most of them would take you at your word, especially for a template function. Otherwise you could be lame and change the function signature to be: doFoo(T *foo) Pointers are cheesy, but they work (unlike references). Jon -- Jon Stewart stew1@xxxxxxxxxxx _______________________________________________ alacpp mailing list alacpp@xxxxxxxxxxx http://lists.ellipsis.cx/mailman/listinfo/alacpp