Returning a reference to a local variable in C++

This code snippet: int& func1() { int i; i = 1; return i; } will not work because you’re returning an alias (a reference) to an object with a lifetime limited to the scope of the function call. That means once func1() returns, int i dies, making the reference returned from the function worthless because … Read more

Detect when multiple enum items map to same value

There are a couple ways to check this compile time, but they might not always work for you. Start by inserting a “marker” enum value right before MsgFoo2A. typedef enum { MsgFoo1A = BASE1_VAL, MsgFoo1B, MsgFoo1C, MsgFoo1D, MsgFoo1E, MARKER_1_DONT_USE, /* Don’t use this value, but leave it here. */ MsgFoo2A = BASE2_VAL, MsgFoo2B } FOO; … Read more

Understanding return value optimization and returning temporaries – C++

In two first cases RVO optimization will take place. RVO is old feature and most compilers supports it. The last case is so called NRVO (Named RVO). That’s relatively new feature of C++. Standard allows, but doesn’t require implementation of NRVO (as well as RVO), but some compilers supports it. You could read more about … Read more

Is it possible to determine if a type is a scoped enumeration type?

I think testing if it is an enum and not implicitly convertible to the underlying type should do the trick. template <typename T, bool B = std::is_enum<T>::value> struct is_scoped_enum : std::false_type {}; template <typename T> struct is_scoped_enum<T, true> : std::integral_constant<bool, !std::is_convertible<T, typename std::underlying_type<T>::type>::value> {};