我正在更深入地研究 C++,并努力解决对用文字初始化的 const 的引用。例如
const int &r {100};
它确实有效,但我想知道编译器对这种定义做了什么。是否在内存中创建了一个真实的对象,其值为 100?还是在编译期间,代码中每次出现的 r
都简单地替换为 100?这是我的猜测,因为初始化值在运行时既不能更改也不能引用,所以为什么要将它保存在内存中?
最佳答案
这里:
const int &r {100};
正在创建一个临时的 int
,稍后绑定(bind)到 r
。对 const 的引用将延长与其绑定(bind)的临时对象的生命周期。
这在以下情况下更有用:
void foo (const std::string& s) {}
foo("test"); // here temporary std::string is created and later on bound to `s`
关于C++ 对 const 的引用与文字初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40432638/