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 将解决这个问题.
这篇关于对临时的常量引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对临时的常量引用
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
