Const引用临时 [英] Const reference to temporary

查看:205
本文介绍了Const引用临时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读本文在Herb Sutter的博客上,我尝试了一下,遇到了困惑我的东西。我使用Visual C ++ 2005,但如果这是实现依赖的,我会很惊讶。



这是我的代码:

  #include< iostream> 

using namespace std;

struct Base {
// Base(){}
〜Base(){cout< 〜Base()<< endl; }
};

int main()
{
const Base& f = Base();
}

运行时会显示〜Base 两次 ...但如果我取消注释构造函数,它只会显示一次


$

这个IS实现依赖。 >



标准允许在将临时数据绑定到const引用时发生复制。在你的情况下,VC ++只在构造函数被隐式定义时才执行一个复制。这是意外的,但允许。



C ++ 1x 将修复此问题


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.

Here is my code:

#include <iostream>

using namespace std;

struct Base {
    //Base() {}
    ~Base() { cout << "~Base()" << endl; }
};

int main()
{
    const Base & f = Base();
}

When run, it displays "~Base()" twice... But if I un-comment the constructor, it displays it only once!

Does anyone have an explanation for this?

解决方案

This IS implementation dependent.

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 will fix this.

这篇关于Const引用临时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆