C
C
CodeInside2017-07-07 16:54:17
C++ / C#
CodeInside, 2017-07-07 16:54:17

How to create a global object for all project elements?

I want to create a global vector in the project. It is needed so that all forms / classes of the project have access to the same data. The problem is visible on the screenshot:
1a68970843a34ade8acc697a73912440.png
The screenshot shows part of the code (the global variable declaration itself) of the header.h file, which I include in the files where I want to use this vector.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
B
BeardedBeaver, 2017-07-07
@BeardedBeaver

The declaration of the tasks vector must be present in the corresponding cpp file (technically, in any other translation unit) besides extern in the h file in the screenshot. But generally speaking, there is a "singleton" pattern, it is much more feng shui for this situation.

A
Alexander Titov, 2017-07-07
@alex-t

Well , extern tells the compiler that somewhere (in some cpp module) this object is without extern.

A
Ariox41, 2017-07-07
@Ariox41

In general, you should read about singletons in C ++, but if you are lazy, the safest option is the Myers singleton:

#include <string>

// Синглтон Майерса. Переменная str будет создана один раз при первом вызове getPrefix, начиная с c++11 это ещё и потокобезопастно.
const std::string& getPrefix(){ 
    static std::string str  {"pref::"}; // Инициализация должна быть в конструкторе. 
    return str;
}

// Его использование.
std::string addPrefix(const std::string& str){
    return getPrefix() + str; 
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question