0

Is declaring a static pointer to in an object in one .cc file, then returning that pointer with a function to a second static pointer in another .cc file safe or bad practice? I have two static pointers in file_a.cc and file_b.cc but use a function to make the pointer in file_b.cc point to the same object declared in file_a.cc. It feels like I'm doing something very bad. Am I? If I call foo() and then print_object() it will print 1, so the pointers are pointing to the same object.

/** file_a.h */
#ifndef FILE_A_H
#define FILE_A_H

struct Object {
    int value = 0;
}

Object* get_object();

void print_object();

#endif


/** file_a.cc */
#include "file_a.h"

static Object* object = new Object();

Object* get_object() {
    return object;
}

void print_object() {
    std::cout << object->value << std::endl;
}


/** file_b.h */
#ifndef FILE_B_H
#define FILE_B_H

#include "file_a.h"

void foo();

#endif


/** file_b.cc */
#include "file_b.h"

static Object* object = get_object();

void foo() {
    object->value += 1;
}
Exudes
  • 103
  • 1
  • 9
  • This looks like a slightly modified version of a singleton pattern to me (not sure why you aren't using the actual singleton pattern though). It will also have the same pitfalls/potential issues as the singleton (see [this question](http://stackoverflow.com/questions/1008019/c-singleton-design-pattern) for some discussions and links to more details). – UnholySheep Jan 04 '17 at 07:26
  • Yeah, I guess it is pretty much a singleton. I didn't think of it that way because I didn't set out to follow the pattern and was just trying things myself. – Exudes Jan 04 '17 at 07:32
  • as long as you dont rely on *order* of initializationof objects in different files you should be good – Oleg Bogdanov Jan 04 '17 at 07:33

2 Answers2

1

There is nothing really bad here. There are two different static pointers in the different compilation units, but both will point to the same object.

Simply it is not the common pattern because the object is created outside of its accessor function. This code is more usual:

Object* get_object() {
    static Object* object = new Object();
    return object;
}

It offers a slightly nicer encapsulation because the object can only be accessed through get_object and the standard guarantees that the object will be created on first call to the accessor function - provided it is only initialized by one single thread...

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • Shouldn't that be `static Object*obj; if (!obj) obj = new Object(); return obj;` because you probably want to build the `obj` only once? – Basile Starynkevitch Jan 04 '17 at 07:52
  • @BasileStarynkevitch: AFAIK, `static Object* object = new Object();` is a static initialization and will be executed only once. Am I wrong somewhere? – Serge Ballesta Jan 04 '17 at 08:38
0

Declaring 2 static variables of the same name in 2 source files results with 2 different instances.

barak manos
  • 29,648
  • 10
  • 62
  • 114