简体   繁体   中英

Return pointer to static object

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;
}

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...

在2个源文件中声明2个同名的static变量会导致2个不同的实例。

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