简体   繁体   中英

Using smart pointers as global variables

Let's say I have a program in which I must use a global variable (of some class type).

I would like to be able to use smart pointers so I won't have to worry about deleting it.

in some file Common.hpp file I have the declaration:

extern unique_ptr<CommandBuffer> globalCommandBuffer;

and in my main.cpp:

#include "Common.hpp"

int main(int argc, char* argv[]) {   
   globalCommandBuffer(new CommandBuffer());
}

this creates many compilation errors. so obviously I'm doing it wrong.

my questions are:

  • is it a good design choice to use smart pointers for global variables?
  • if so, what is the correct way of doing so?
  • which smart pointer is preferable?

You want either:

globalCommandBuffer.reset(new CommandBuffer());

Or:

globalCommandBuffer = std::make_unique<CommandBuffer>();

Global variables are very rarely a good idea.

If you want a global (you probably don't, but just in case you do), just create a global. The whole point of a smart pointer is to manage ownership and lifetime. In the case of a global, those are generally quite trivial--you want them to exist before anything else happens, and continue existing until everything else quits happening.

Unless you need something different from that, just create your object as a global object, not a smart pointer to a dynamically allocated object.

Problem is not with global variable which is some smart_ptr but problem is the fact that you are defining it once in header file - and again in main.cpp. Double definitions would definitely be problematic.

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