Confusing difference in raw versus shared_ptr behavior w/ static initializers
Hi everybody,
I am struggling to understand the different behavior exhibited in the
raw versus shared_ptr behavior of the static initializers in the
following small test program. Can anybody explain this to me, or is
it perhaps a compiler bug?
I am trying to get good at RAII and cannot figure this puzzle out.
Any helpful info will be much appreciated. Code pasted below. Best
regards,
Rudi
// Compiled with g++ 4.5.2 using command:
//
// g++ main.cc -o noshared -std=c++0x
// or
// g++ main.cc -o yesshared -std=c++0x -DUSED_SHARED=1
//
// How come the first case produces two lines of output and the second
only 1?
//
// % ./noshared
// cmdstring
// hello
// %
// % ./yesshared
// hello
// %
#include <string>
#include <vector>
#include <iostream>
#include <memory>
class Anac {
std::vector<std::string> m_strings;
Anac(void);
public:
static Anac& getInstance(void);
void printStrings(void);
void addString(std::string val);
};
class Cmd {
public:
Cmd(void);
};
static Cmd c;
Cmd::Cmd(void)
{
Anac::getInstance().addString("cmdstring");
}
using namespace std;
#if USED_SHARED
static std::shared_ptr<Anac> singleton;
#else
static Anac *singleton;
#endif
Anac::Anac(void) : m_strings() {
}
void Anac::addString(std::string val) {
m_strings.push_back(val);
}
void Anac::printStrings(void) {
for (auto i = m_strings.begin(); i != m_strings.end(); ++i) {
cout << (*i) << '\n';
}
}
Anac& Anac::getInstance(void) {
if (!singleton) {
#if USED_SHARED
singleton = std::shared_ptr<Anac>(new Anac());
#else
singleton = new Anac();
#endif
}
return *singleton;
}
using namespace std;
int main(int argc, char **argv)
{
Anac::getInstance().addString("hello");
Anac::getInstance().printStrings();
return 0;
}