const auto& 和 as_const 的区别?

The difference between const auto& vs as_const?

基本上,我正在尝试学习 C++ 17,我发现 as_const

我们使用的时候有什么区别:

MyType t;
auto& p = as_const(t);

而不是:

MyType t;
const auto& p = t;

这里有什么优势吗?

在你的情况下它们是一样的。

std::as_const 通常用于 select 来自一组重载(成员)函数的 const 版本。以下是来自 cppreference.

的示例
struct cow_string { /* ... */ }; // a copy-on-write string
cow_string str = /* ... */;
 
// for(auto x : str) { /* ... */ } // may cause deep copy
 
for(auto x : std::as_const(str)) { /* ... */ }

即使你使用for(const auto &x : str),也可能会发生深拷贝

在分配给参考的简单情况下,我怀疑任何一个选项都比另一个选项有任何 objective 好处。就个人而言,我更喜欢看到 const 附加到变量,但这完全是主观的。

as_const() 有一个重要的好处:它可以用来强制 constness 而无需变量声明。例如,当调用一个方法时,参数的 constness 很重要:

#include <iostream>
#include <utility>

void example(int const & i) {
  ::std::cout << "const int" << ::std::endl;
}

void example(int & i) {
  ::std::cout << "int" << ::std::endl;
}

int main() {
  int i = 5;

  example(i);                    // Prints "int"
  example(::std::as_const(i));   // Prints "const int"
}