简体   繁体   中英

C++ strange issue. Data member getting out of scope

This code:

#include "stdafx.h"
#include <iostream>
using namespace std;
class singleTon
{
    float testVal;
public:
    singleTon()
    {
        cout << "Singleton created\n";
        testVal = 0.0;
    }
    ~singleTon()
    {
        cout << "Singleton deleted\n";
    }
    void setTest(float x)
    {
        testVal = x;
    }
    float getTest()
    {
        return testVal;
    }

};

class myClass
{
    singleTon s;

public:
    myClass()
    {
        cout << "myClass created\n";
    }
    ~myClass()
    {
        cout << "myClass deleted\n";
    }

    singleTon getSingleTon()
    {
        return s;
    }

};

int _tmain(int argc, _TCHAR* argv[])
{
    myClass m;
    m.getSingleTon().setTest(100);
    cout << "\ngetting" << m.getSingleTon().getTest();
    cout << "\nSetting:";
    m.getSingleTon().setTest(200);
    cout << "\ngetting" << m.getSingleTon().getTest();

    getchar();
    return 0;
}

After the first setTest() :

m.getSingleTon().setTest(100);      

The singleton class's destructor is getting called.

But, why?

My understanding was that it will still hold the singleton instance in class myClass . I know, if I use heap allocation, it may work. But what is wrong with this style? Where is the issue?

singleTon getSingleTon()
{
    return s;
}

The return type of this function is neither a reference nor a pointer, so you will return s by value , which means you're making a copy of it and returning a copy. However, if you want to modify the data members of the singleTon stored in myClass , you'll want to return by reference instead (returning by pointer is also possible, but usually discouraged if its not necessary). You code would have to change to look something like this:

singleTon& getSingleTon()
{
    return s;
}

调用getSinglton()时,实际上是在myClass中获得单例的副本。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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