c++ - What problems are solved by holding a Temporary using `const T &`? -
like, if write code looks following:
const int & const_value = 10; what advantage gaining on code instead this:
int value = 10; or
const int const_value = 10; even more complicated example, like
const enterprise::complicated_class_which_takes_time_to_construct & obj = factory.create_instance(); thanks copy elision, both of following code snippets shouldn't faster or less memory consuming.
enterprise::complicated_class_which_takes_time_to_construct obj = factory.create_instance(); or
const enterprise::complicated_class_which_takes_time_to_construct obj = factory.create_instance(); is there i'm missing explains use of construct, or hidden benefit i'm not accounting for?
edit:
the answer provided @nwp supplied example of factory method looks following:
using cc = enterprise::complicated_class_which_takes_time_to_construct; struct factory{ const cc &create_instance(){ static const cc instance; return instance; } } factory; while example of why you'd need exact const reference construct in general, doesn't answer why needed dealing temporaries, or why particular construct better seating temporary in proper stack-allocated object, compiler should still able copy-elide in normal situations.
imagine factory "clever" , like
using cc = enterprise::complicated_class_which_takes_time_to_construct; struct factory{ const cc &create_instance(){ static const cc instance; return instance; } } factory; and further assume cc not copyable const & version works while other 2 don't. common classes implement cache , keep local map of objects , reference object inside map.
edit:
it possible coding guideline take return values functions const &, because works universally values , references.
cc foo(); cc &foo(); const cc &foo(); if use const cc &var = foo(); work without unnecessary copy in cases. temporary, don't, code right thing, freeing change implementation , not having care how function use returns return-value. there still issue of having const in there, not superior notation in cases, viable design choice.