分配通过引用传递给成员变量的值(在C ++中) [英] Assigning value passed by reference to a member variable (in C++)

查看:92
本文介绍了分配通过引用传递给成员变量的值(在C ++中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C ++中围绕范围。请考虑以下内容:

I am trying to wrap my head about scope in C++. Please consider the following:

class C
{
    int i_;
public:
    C() { i_ = 0;}
    C(int i) { i_ = i; }
    C(const C &c) {
        i_ = c.i_;
        cout << "C is being copied: " << i_ << endl;
    }
    int getI() { return i_; }
    ~C() {cout << "dstr: " << i_ << endl;}
};

class D
{
    C c_;
public:
    void setC(C &c) { c_ = c; }
    int getC_I() { return c_.getI(); }
};

void Test(D &d)
{
    C c(1);
    d.setC(c);
    //here c is going out of scope, surely it will be destroyed now?
}

int main()
{
    D d;
    Test(d); //this sets value of c_ to the local variable in Test. 
             //Surely this will be invalid when Test returns?
    int ii = d.getC_I();
    cout << ii << endl;
}

运行此程序输出:

dstr:1

1

dstr:1

dstr: 1
1
dstr: 1

显然,第一个析构函数调用发生在Test,

Apparently, the first destructor call occurs in Test, and the other when program terminates and d is destroyed.

所以我的问题是:C在哪里复制?我的推理有错吗?一般来说,我试图问:安全的是有一个成员函数,它引用一个对象,然后将其存储在成员变量中。

So my question is: Where was c copied? Is there fault with my reasoning? And general point I am trying to ask: is it safe to have a member function that takes a reference to an object and then stores it in a member variable?

推荐答案

您的代码很好,因为它现在是现在。 D :: c _ 的类型为 C ,而不是 C& 。您的 SetC 引用一个C,并将该引用所引用的值分配给 C :: c _ 所以你有一个完全独立的 C 对象具有相同的值。由于您在中自动存储时间创建了 d ,它和 c _ 这是它的一部分,直到退出 main 为止。

Your code is fine as it stands right now. D::c_ is of type C rather than C &. Your SetC takes a reference to a C, and assigns the value referred to by that reference to C::c_, so what you have is an entirely separate C object that has the same value. Since you created d with automatic storage duration in main, it and c_ which is part of it remain valid until you exit from main.

这篇关于分配通过引用传递给成员变量的值(在C ++中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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