bebbo/binutils-gdb

C++ singleton class doesn't work on 68k using g++

tdolphin-org opened this issue · 3 comments

This problem is related to one of known singletons patterns, when constructor is private, and there is only static method instance which has static variable with type of this class, the object is created only once and returned from method.
Here is example code below (few files):

Main.cpp

#include "ClassSinleton.hpp"
#include "SomeClass.hpp"

int main(int argc, char **argv)
{
    ClassSinleton::instance().setName("Amiga");
    ClassSinleton::instance().toString();

    SomeClass object;
    object.Test();

    ClassSinleton::instance().toString();
}

ClassSinleton.hpp

#pragma once

#include <iostream>
#include <string>

class ClassSinleton {
  std::string mName;

  ClassSinleton(){};
  ClassSinleton(ClassSinleton const &) = delete;
  void operator=(ClassSinleton const &) = delete;

public:
  static ClassSinleton &instance() {
    static ClassSinleton inst;
    std::cout << "@@@@@@ " << __PRETTY_FUNCTION__ << &inst << std::endl;
    return inst;
  };

  void setName(const std::string &name);
  void toString();
};

ClassSinleton.cpp

#include "ClassSinleton.hpp"

void ClassSinleton::setName(const std::string &name) { mName = name; }
void ClassSinleton::toString() { std::cout << mName << std::endl; }

SomeClass.hpp

#pragma once

class SomeClass
{
    public:
        void Test();
};

SomeClass.cpp

#include "ClassSinleton.hpp"

#include "SomeClass.hpp"

void SomeClass::Test()
{
    ClassSinleton::instance().toString();
    ClassSinleton::instance().setName("MorphOS");
}

The expected result (after compiled and run it on linux) is:

@@@@@@ static ClassSinleton& ClassSinleton::instance()0x55803f6c9160
@@@@@@ static ClassSinleton& ClassSinleton::instance()0x55803f6c9160
Amiga
@@@@@@ static ClassSinleton& ClassSinleton::instance()0x55803f6c9160
Amiga
@@@@@@ static ClassSinleton& ClassSinleton::instance()0x55803f6c9160
@@@@@@ static ClassSinleton& ClassSinleton::instance()0x55803f6c9160
MorphOS

But compiled using m68k-amigaos-g++ and run under AmigaOS result is:
g++ 68k problem

As we can see the object is created again if singleton instance() is called from other source file/class, what is wrong.
Also I have check and such problem not exists under MorphOS with the latest g++ from MOS SDK.

bebbo commented

You have to redesign your code. The amiga hunks can't support this.

bebbo commented

it yields now:

@@@@@@ static ClassSinleton& ClassSinleton::instance()0xc93ac
@@@@@@ static ClassSinleton& ClassSinleton::instance()0xc93ac
Amiga
@@@@@@ static ClassSinleton& ClassSinleton::instance()0xc93ac
Amiga
@@@@@@ static ClassSinleton& ClassSinleton::instance()0xc93ac
@@@@@@ static ClassSinleton& ClassSinleton::instance()0xc93ac
MorphOS

it yields now:

You are great!!
Thanks!