dimanche 1 décembre 2019

singleton class based on static object reference initializing class members to default c++11

I know there are many questions in this area, however the following example does not work and it requires explanation or simple solution (i know i can use namespaces and similar solutions, however i would like to understand what is wrong here.

It isn't similar to previous asked questions since

struct point
{ 
    float x;
    float y;
    point(): x(0.0), y(0.0) {}
class A
{
public:
    static A& getRef();
    float getF();
    void setP(point P);
    point getP();
    void setF(float F);
private:
    A();
    ~A();
    float m_myFloat;
    point m_P;
};

// implementation

A& A::getRef()
{
    static A m_A;
    return m_A;
}


float A::getF()
{
    return m_myFloat;
}

void A::setF(float F)
{
    m_myFloat = F;
}

void A::setP (point P)
{
    m_P.x = P.x;
    m_P.y = P.y;
}

point getP()
{
    point P;
    P.x = m_P.x;
    P.y = m_P.y;
    return P;    
}
A::A()
{
    m_myFloat = 12.01;
    m_P.x = 13;
    m_P.y = 14;
}
A::~A()
{

}
// cal from main
point p;
p.x = 19;
p.y = 20; 
float F = 19.54;
A::getRef().setF(F);
A::getRef().setP(p);
p = A::getRef().getP()
std::cout << A::getRef().getF() << std::endl;
std::cout << p.x << " ," << p.y << std::endl;

while the member is updated correctly, the struct point is initialized whenever we call getRef() Why is that? I would like to emphasize that it is C++ 11 (!!!)

Many thanks

Aucun commentaire:

Enregistrer un commentaire