对临时的常量引用

2022-01-05 00:00:00 reference c++ 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 将解决这个问题.

相关文章