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 将解决这个问题.
这篇关于对临时的常量引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对临时的常量引用
基础教程推荐
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- c++ STL设置差异 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
