Const reference to temporary(对临时的常量引用)
问题描述
阅读后这篇文章在 Herb Sutter 的博客上,我进行了一些实验,但遇到了一些令我感到困惑的事情.我使用的是 Visual C++ 2005,但如果这取决于实现,我会感到惊讶.
After reading this article on Herb Sutter's blog, I experimented a bit and ran into something that puzzles me. I am using Visual C++ 2005, but I would be surprised if this was implementation dependent.
这是我的代码:
#include <iostream>
using namespace std;
struct Base {
//Base() {}
~Base() { cout << "~Base()" << endl; }
};
int main()
{
const Base & f = Base();
}
运行时,它显示~Base()
"两次...但是如果我取消注释构造函数,它只显示一次!
When run, it displays "~Base()
" twice... But if I un-comment the constructor, it displays it only once!
有人对此有解释吗?
推荐答案
这取决于实现.
该标准允许在将临时引用绑定到常量引用时进行复制.在您的情况下,VC++ 仅在隐式定义构造函数时执行复制.这是出乎意料的,但也是允许的.
The standard allows a copy to occur when binding a temporary to a const reference. In your case, VC++ performs a copy only when the constructor is implicitly defined. This is unexpected, but permitted.
C++1x 将解决这个问题.
这篇关于对临时的常量引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对临时的常量引用


基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01