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

时间:2017-03-28 22:44:36

标签: c++ scope

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

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

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;
}

输出

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

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

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

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

您可以声明一些变量:

username

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

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

您将覆盖对象myobject的数据。

相关问题