const int n = 0;
auto& n1 = const_cast<int&>(n);
auto n2 = const_cast<int&>(n);
Does the C++11 standard guarantee n2 is int&
by auto n2 = const_cast<int&>(n);
?
Must I use auto& n1 = const_cast<int&>(n);
instead of auto n2 = const_cast<int&>(n);
?
Are the two ways completely equivalent to each other as per the C++11 standard?
auto
on its own never produces a reference type.
So n2
is an int
type.
(If I had a dollar for every time I see code like for (auto s : expensive_deep_copy_container)
).
auto
uses the same rules as regular function template argument deduction, which never deduces a reference.
C++14 decltype(auto)
, on the other hand, can deduce a reference here. As well as C++11 auto&&
.
const int n = 0;
auto a = const_cast<int&>(n); // a is int
decltype(auto) b = const_cast<int&>(n); // b is int&
auto&& c = const_cast<int&>(n); // c is int&
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.