简体   繁体   English

返回指向静态对象的指针

[英]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? 是在一个.cc文件中的对象中声明一个静态指针,然后将带有函数的指针返回到另一个.cc文件中的第二个静态指针是安全还是不良做法? 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. 我在file_a.cc和file_b.cc中有两个静态指针,但使用函数使file_b.cc中的指针指向在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. 如果我先调用foo()然后再调用print_object(),它将打印1,因此指针指向同一对象。

/** 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... 它提供了更好的封装,因为只能通过get_object来访问该对象,并且该标准保证了该对象将在首次调用accessor函数时创建-前提是该对象只能由一个线程初始化。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM