为什么持有引用的班级是可复制的? [英] Why is the class holding a reference copyable?

查看:56
本文介绍了为什么持有引用的班级是可复制的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个持有引用的类,我希望下面的代码失败,但可以编译:

Having a class holding a reference I would expect the following code to fail miserable, but it compiles:

#include <iostream>

struct ReferenceHolder
{
    std::string& str;

    ReferenceHolder(std::string& str)
    :   str(str)
    {}
};

// Why does this compile?
ReferenceHolder f() {
    std::string str = "Hello";
    return ReferenceHolder(str);
}

int main() {
    ReferenceHolder h  = f();
    std::cout << "Should be garbage: " << h.str << '\n';
    return  0;
}

编译器:g ++ 4.7.2(带有-std = c ++ 11)

Compiler: g++ 4.7.2 (with -std=c++11)

编辑:即使使用-fno-elide-constructors,它也可以很容易地编译

Edit: Even with -fno-elide-constructors it compiles happily

推荐答案

像您的示例一样,对副本进行类初始化没有问题:只需简单地初始化新引用即可引用与旧对象相同的对象。当然,当函数返回离开引用悬空时,您会得到不确定的行为。

There's no problem with copy-initialising your class, as your example does: the new reference is simply initialised to refer to the same object as the old one. Of course, you then get undefined behaviour when the function return leaves the reference dangling.

该引用可防止默认初始化和复制赋值;因此以下小改动由于这些原因将失败:

The reference prevents default-initialisation and copy-assignment; so the following small change will fail for those reasons:

ReferenceHolder h;  // ERROR: can't default-initialise the reference
h = f();            // ERROR: can't reassign the reference.

这篇关于为什么持有引用的班级是可复制的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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