繁体   English   中英

在函数中创建的对象的范围

[英]Scope of an object created in a function

我已经在函数内部创建了一个类的对象。 创建的对象作为参数传递给另一个类。 我希望当我退出创建对象的函数时,必须销毁该对象。

同样,对此对象的任何引用都必须无效,但是我发现退出函数后引用的对象仍然有效。 试图了解对象的范围。 截断的代码如下。

class TextWidget
{
    public:
        TextWidget()
        {
            cout <<  "Constructor TextWidget" << endl;
        }

        TextWidget(int id)
        {
            _ID = id;
            cout <<  "Constructor TextWidget" << endl;
        }

        ~TextWidget()
        {
            cout <<  "Destructor TextWidget" << endl;
        }

        void printWidgetInstance()
        {
            cout << this << endl;
        }
        int _ID;
};

class AnotherWidget
{
    public:
        AnotherWidget()
        {
            cout << "Constructor AnotherWidget" << endl;
        }

        ~AnotherWidget()
        {
            cout << "Destructor AnotherWidget" << endl;
        }

        TextWidget* getTextWidget()
        {
            return _textWidget;
        }

        void setTextWidget(TextWidget* t)
        {
            _textWidget = t;
        }

        int getTextID() { return _textWidget->_ID; }

    private:
        TextWidget* _textWidget;
};


ButtonWidget b;
AnotherWidget a;

void fun()
{
    TextWidget t(7);
    b.setTextWidget(&t);
    a.setTextWidget(&t);
    a.getTextWidget()->printWidgetInstance();
    b.getTextWidget()->printWidgetInstance();
}

int main()
{
    fun();
    cout << "TextWidget in AnotherWidget is ";
    a.getTextWidget()->printWidgetInstance();
    cout << "Text ID in a is " << a.getTextID() << endl;
    getchar();
    return 0;
}

OUTPUT

Constructor AnotherWidget
Constructor TextWidget
Before deleting TextWidget in class ButtonWidget 0x73fdf0
Before deleting TextWidget in class AnotherWidget 0x73fdf0
0x73fdf0
0x73fdf0
Destructor TextWidget
TextWidget in AnotherWidget is 0x73fdf0
Text ID in a is 7

使用自动存储持续时间声明的变量(不使用new变量)具有其范围的生命周期。 在范围之外访问变量将导致未定义的行为。

您需要了解什么是类,对象,指针和引用。 类是内存中的代码,此代码处理成员变量。 一个类不占用任何数据存储器。 创建对象时,您将实例化该类。 此步骤将为该类的一个对象实例的本地数据保留一些数据存储器。 要访问该实例,您需要获得对该对象的引用(this)。 一个对象变量持有一个指向类实例数据存储器的指针。

当一个对象被销毁时,占用的内存块将被列为空闲但不会清除。 因此,如果您仍然引用该内存块,则可以访问它。 只要系统不将此存储块用于其他目的,您仍然会在其中找到您的位和字节。

您可以声明一些变量:

long      long_array[10];
myclass   myobject;

这些变量按顺序存储在一个存储块中。 现在,当您通过该数组访问long_array后面的内存时:

long_array [10] = 12345; //有效范围是从long_array [0]到long_array [9]

比您将覆盖对象myobject的数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM