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++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01