Alex Rivera | Logout

Will a good C++ compiler optimize a reference away?

Asked 2012-01-26T04:40:45.803
18

I want to write a template function that does something with a std::stack<T> and an instance of T, e.g.:

template<class StackType> inline
bool some_func( StackType const &s, typename StackType::value_type const &v ) {
  // ...
}

The reason I pass v by reference is of course to optimize for the case where StackType::value_type is a struct or class and not copy an entire object by value.

However, if StackType::value_type is a "simple" type like int, then it's of course better simply to pass it by value.

The question is: for a type such as int that would become int const& as a formal argument in the above function, will the compiler optimize away the reference and simply pass it by value?

Edit
Report

1 Answer

8

Whenever the compiler is able to inline, the resulting cross-procedural optimization will eliminate the expense of finding and passing an address.

For non-inline-able function calls, the reference probably will be implemented as a pointer, not pass-by-value.

answered 2012-01-26T05:27:58.067

Your Answer