I am making a VC++ 2008 windows project, and I want to have an object that I instantiate exist for all intense, and purposes globally. this object shall be a timer to monitor how long the program has been running, and needs to be accessible by other objects for the purpose of log file generation. I know that I can mark native, and sudo-native (string) members as extern to make them reachable, but how do I get an object to exist globally to other objects.
Do I put the object definition before the class of the object that needs to know of its existence (insuring to load the class first), or must I put a method in my main that allows access to the object?
Just create a class with the methods you need, then declare an instance of the class global
include the header of the class in all your modules where you want to use it plus have
an extern declaration telling the modules that the definition is elsewhere. Maybe you
have some common header that all include.
extern MyClass yourInstance;
The global definition should be where the main() is
MyClass yourInstance;
or if you prefer allocate it on the heap by using a pointer, then allocate at start of main
and delete at end and just have the pointer as global.
that said, it is normally not good to have global declarations instead you should declare
the MyClass in the main() and then pass a pointer to it to all functions/classes that
you use. that is how i would do it. Then you don't need the extern statement and just
include the header MyClass.h
one problem with global instances is that you have little or no control of when they are
created/destroyed.
What you describe is often done using a singleton.
Here's an example on how to write one: Singleton: How should it be used
Here's another one:
Can any one provide me a sample of Singleton in c++?
Also note: What is so bad about singletons?
Related
I already read a lot of posts and articles all over the net, but I couldn't find a definite answer about this.
I have some functions with similar purposes that I want to have out of the global scope. Some of them need to be public, others should be private (because they are only helper functions for the "public" ones).
Additionally, I don't have only functions, but also variables. They are only needed by the "private" helper functions and should be private, too.
Now there are the three ways:
making a class with everything being static (contra: potential "Cannot call member function without object" - not everything needs to be static)
making a singleton class (contra: I WILL need the object)
making a namespace (no private keyword - why should I put it in a namespace at all, then?)
What would be the way to take for me? Possible way of combining some of these ways?
I thought of something like:
making a singleton, the static functions use the helper function of the singleton object (is this possible? I'm still within the class, but accessing an object of it's type)
constructor called at programm start, initializes everything (-> making sure the statics can access the functions from the singleton object)
access the public functions only through MyClass::PublicStaticFunction()
Thanks.
As noted, using global variables is generally bad engineering practice, unless absolutely needed of course (mapping hardware for example, but that doesn't happen THAT often).
Stashing everything in a class is something you would do in a Java-like language, but in C++ you don't have to, and in fact using namespaces here is a superior alternative, if only:
because people won't suddenly build instances of your objects: to what end ?
because no introspection information (RTTI) is generated for namespaces
Here is a typical implementation:
// foo.h
#ifndef MYPROJECT_FOO_H_INCLUDED
#define MYPROJECT_FOO_H_INCLUDED
namespace myproject {
void foo();
void foomore();
}
#endif // MYPROJECT_FOO_H_INCLUDED
// foo.cpp
#include "myproject/foo.h"
namespace myproject {
namespace {
typedef XXXX MyHelperType;
void bar(MyHelperType& helper);
} // anonymous
void foo() {
MyHelperType helper = /**/;
bar(helper);
}
void foomore() {
MyHelperType helper = /**/;
bar(helper);
bar(helper);
}
} // myproject
The anonymous namespace neatly tucked in a source file is an enhanced private section: not only the client cannot use what's inside, but he does not even see it at all (since it's in the source file) and thus do not depend on it (which has definite ABI and compile-time advantages!)
Don't make it a singleton
For public helper functions that don't directly depend on these variables, make them non-member functions. There's nothing gained by putting them in a class.
For the rest, put it in a class as normal non-static members. If you need a single globally accessible instance of the class, then create one (but don't make it a singleton, just a global).
Otherwise, instantiate it when needed.
The classic C way of doing this, which seems to be what you want, is to put the public function declarations in a header file, and all the implementation in source file, making the variables and non-public functions static. Otherwise just implement it as a class - I think you are making a bit of a mountain out of a molehill here.
What about using a keyword static at global scope (making stuff local to the file) as a privacy substitute?
From your description it looks like you have methods and data that interact with each other here, in other words it sounds to me like you actually want a non-singleton class to maintain the state and offer operations upon that state. Expose your public functions as the interface and keep everything else private.
Then you can create instance(s) as needed, you don't have to worry about init order or threading issues (if you have one per thread), and only clients that need access will have an object to operate upon. If you really need just one of these for the entire program you could get away say a global pointer that's set in main or possibly an instance method, but those come with their own sets of problems.
Remember that the singleton instance of a singleton class is a valid instance, so it is perfectly able to be the recipient of nonstatic member functions. If you expose your singleton factory as a static function then have all of your public functionality as public nonstatic member functions and your private functionality as private nonstatic member functions, anyone that can get at the class can access the public functionality by simply invoking the singleton factory function.
You don't describe whether all of the functionality you're trying to wrap up is as related as to justify being in the same class, but if it is, this approach might work.
If you take a "C-like" approach and just use top-level functions, you can make them private by declaring them in the .cpp file rather than the publicly-included .h file. You should also make them static (or use an anonymous namespace) if you take that approach.
I am a student studying MFC.
I want to declare ChildView region variables.
Where do I have to declare variables? header file? or cpp file?
I think both work well. But I want to know general style.
Please let me know which are desirable.
// ChildView.h : interface of the CChildView class
//
#pragma once
// CChildView window
class CChildView : public CWnd
{
// Construction
public:
CChildView();
...
...
// User variables
public:
CFile* pImgFile = NULL;
ULONGLONG imgLength, frameLength;
unsigned char RRR[288][352];
unsigned char GGG[288][352];
unsigned char BBB[288][352];
unsigned char YYY[288][352];
unsigned char UUU[144][176];
unsigned char VVV[144][176];
};
or
// ChildView.cpp : implementation of the CChildView class
//
#include "stdafx.h"
#include "Doyup_YUV_HW7-8.h"
#include "ChildView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CChildView
CChildView::CChildView()
{
CFile* pImgFile = NULL;
ULONGLONG imgLength, frameLength;
unsigned char RRR[288][352];
unsigned char GGG[288][352];
unsigned char BBB[288][352];
unsigned char YYY[288][352];
unsigned char UUU[144][176];
unsigned char VVV[144][176];
}
In addition, I also wondered where define statements are located.
after (3)#pragma once in header file?
or after (9)#endif in cpp file?
You should prefer second way - declare variables in .cpp file in
CChildView::CChildView()
only in case you will need your variables only in constructor and won't need them in other functions.
But I think you will need these variables in other functions, too. In this case you should declare them in .h file. Please note them now you declare them as public variables, this is bad idea. You would better declare them as private variables (read about private and public variables and encapsulation). By default it is better to declare all your variables as private.
As for defines, it is better to add them to .cpp file, then they will be visible in your cpp file only. If you define something in h file, it will be defined everywhere when you include your h file and may cause conflicts.
You have little choice, because the place where you declare them greatly affects the behavior. In particular, the lifetime of variables is strongly dependent on the place where they're defined.
If you define the variable inside the class definition (which is almost always in the .h file), then it's a member variable. The lifetime of the member is tied to the lifetime of the containing object. If you have 3 objects, they each have a unique lifetime, and thus you have 3 copies of each member variables with corresponding lifetimes.
If you define a variable inside a member function (which is usually in the .cpp file), then the lifetime matches the function call. If you have 3 objects, one thread, and that one thread calls the member function, you get one variable for the duration of that call.
You can also define a variable in the .cpp file outside a member function. This is a global variable, not associated with any object or class. For this reason, globals are often considered bad style.
This is not an MFC issue. This is a good question regarding what makes a good structured design and a good object oriented design.
Variable lifetime, variable scope (global, object, class, function, block, ...), and variable accessibility (including, but not limited to, public vs. protected vs. private member variables in a class) requires a good understanding of not just the basic semantics, but what makes a good design "good".
A general rule is that you want the lifetime of most variables to be as short as possible but as long as needed. So a for-loop index can usually be declared within the for-loop within a function, and NOT in the class (you only need the index within the loop, not outside the loop, and not within other methods in the class). But you would want the "modified" flag of your CDocument MFC object to be a member of the CDocument class so that other methods of CDocument can look at/set/clear it, and then provide a public accessor GetModified() so that other users of the CDocument object (like its corresponding CView object) can determine if the CDocument has been "modified" (say to put an * at the end of the CView's title bar text to show that it has been modified).
Where do I have to declare variables? header file? or cpp file?
here we have to specify that Declaration and Implementation are not tied respectively to header file and cpp file.
It's a good thing to have them separated in header file and cpp file but not restrictively necesary.
variable scope
in your example the variables declared in the "header file" are declared inside the class, so they are members of that class, and you can use them from objects of that class, the variables declared in the cpp file are declared inside the constructur so they will be available ONLY in that method and cannot be used anywhere else
where do I use the defines?
that also is about scope, the define in the header file can be used in other files that include it, but it will only be defined when the compiler actually gets to that point, so if you have another file that is compiled before, it will not contain that define. You might want to look at preprocessor definitions too. You might want to set your defines in the "stdafx.h" file. In your case it doesn't seem that you actually need that define because anyway you can use the _DEBUG already declared automaticaly.
So far, I've been using classes the following way:
GameEngine.h declares the class as follows
class GameEngine {
public:
// Declaration of constructor and public methods
private:
InputManager inputManager;
int a, b, c;
// Declaration of private methods
};
My GameEngine.cpp files then just implement the methods
#include "____.h"
GameEngine::GameEngine() {
}
void GameEngine::run() {
// stuff
}
However, I've recently read that variable declarations are not supposed to be in the header file. In the above example, that would be an inputManager and a, b, c.
Now, I've been searching for where to put the variable declarations, the closest answer I found was this: Variable declaration in a header file
However, I'm not sure if the use of extern would make sense here; I just declare private variables that will only be used in an instance of the class itself. Are my variable declarations in the header files fine? Or should I put them elsewhere? If I should put them in the cpp file, do they go directly under the #include?
Don't confuse a type's members with variables. A class/struct definition is merely describing what constitutes a type, without actually declaring the existence of any variables, anything to be constructed on memory, anything addressable.
In the traditional sense, modern class design practices recommend you pretend they are "black boxes": stuff goes in, they can perform certain tasks, maybe output some other info. We do this with class methods all the time, briefly describing their signature on the .h/.hpp/.hxx file and hiding the implementation details in the .cpp/.cc/.cxx file.
While the same philosophy can be applied to members, the current state of C++, how translation units are compiled individually make this way harder to implement. There's certainly nothing "out of the box" that helps you here. The basic, fundamental problem is that for almost anything to use your class, it kind of needs to know the size in bytes, and this is something constrained by the member fields and the order of declaration. Even if they're private and nothing outside the scope of the type should be able to manipulate them, they still need to briefly know what they are.
If you actually want to hide this information to outsiders, certain idioms such as PImpl and inlined PImpl can help. But I'd recommend you don't go this way unless you're actually:
Writing a library with a semi-stable ABI, even if you make tons of changes.
Need to hide non-portable, platform-specific code.
Need to reduce pre-processor times due to an abundance of includes.
Need to reduce compile times directly impacted by this exposure of information.
What the guideline is actually talking about is to never declare global variables in headers. Any translation unit that takes advantage of your header, even if indirectly, will end up declaring its own global variable as per header instructions. Everything will compile just fine when examined individually, but the linker will complain that you have more than one definition for the same thing (which is a big no-no in C++)
If you need to reserve memory / construct something and bind it to a variable's name, always try to make that happen in the source file(s).
Class member variables must be declared in the class definition, which is usually in a header file. This should be done without any extern keywords, completely normally, like you have been doing so far.
Only variables that are not class members and that need to be declared in a header file should be declared extern.
As a general rule:
Variables that are to be used with many functions in the same class go in the class declaration.
Temporary variables for individual functions go in the functions themselves.
It seems that InputManager inputManager; belongs in the class header.
int a, b, c; is harder to know from here. What are they used for? They look like temporary variables that would be better off in the function(s) they're used in, but I can't say for sure without proper context.
extern has no use here.
I already read a lot of posts and articles all over the net, but I couldn't find a definite answer about this.
I have some functions with similar purposes that I want to have out of the global scope. Some of them need to be public, others should be private (because they are only helper functions for the "public" ones).
Additionally, I don't have only functions, but also variables. They are only needed by the "private" helper functions and should be private, too.
Now there are the three ways:
making a class with everything being static (contra: potential "Cannot call member function without object" - not everything needs to be static)
making a singleton class (contra: I WILL need the object)
making a namespace (no private keyword - why should I put it in a namespace at all, then?)
What would be the way to take for me? Possible way of combining some of these ways?
I thought of something like:
making a singleton, the static functions use the helper function of the singleton object (is this possible? I'm still within the class, but accessing an object of it's type)
constructor called at programm start, initializes everything (-> making sure the statics can access the functions from the singleton object)
access the public functions only through MyClass::PublicStaticFunction()
Thanks.
As noted, using global variables is generally bad engineering practice, unless absolutely needed of course (mapping hardware for example, but that doesn't happen THAT often).
Stashing everything in a class is something you would do in a Java-like language, but in C++ you don't have to, and in fact using namespaces here is a superior alternative, if only:
because people won't suddenly build instances of your objects: to what end ?
because no introspection information (RTTI) is generated for namespaces
Here is a typical implementation:
// foo.h
#ifndef MYPROJECT_FOO_H_INCLUDED
#define MYPROJECT_FOO_H_INCLUDED
namespace myproject {
void foo();
void foomore();
}
#endif // MYPROJECT_FOO_H_INCLUDED
// foo.cpp
#include "myproject/foo.h"
namespace myproject {
namespace {
typedef XXXX MyHelperType;
void bar(MyHelperType& helper);
} // anonymous
void foo() {
MyHelperType helper = /**/;
bar(helper);
}
void foomore() {
MyHelperType helper = /**/;
bar(helper);
bar(helper);
}
} // myproject
The anonymous namespace neatly tucked in a source file is an enhanced private section: not only the client cannot use what's inside, but he does not even see it at all (since it's in the source file) and thus do not depend on it (which has definite ABI and compile-time advantages!)
Don't make it a singleton
For public helper functions that don't directly depend on these variables, make them non-member functions. There's nothing gained by putting them in a class.
For the rest, put it in a class as normal non-static members. If you need a single globally accessible instance of the class, then create one (but don't make it a singleton, just a global).
Otherwise, instantiate it when needed.
The classic C way of doing this, which seems to be what you want, is to put the public function declarations in a header file, and all the implementation in source file, making the variables and non-public functions static. Otherwise just implement it as a class - I think you are making a bit of a mountain out of a molehill here.
What about using a keyword static at global scope (making stuff local to the file) as a privacy substitute?
From your description it looks like you have methods and data that interact with each other here, in other words it sounds to me like you actually want a non-singleton class to maintain the state and offer operations upon that state. Expose your public functions as the interface and keep everything else private.
Then you can create instance(s) as needed, you don't have to worry about init order or threading issues (if you have one per thread), and only clients that need access will have an object to operate upon. If you really need just one of these for the entire program you could get away say a global pointer that's set in main or possibly an instance method, but those come with their own sets of problems.
Remember that the singleton instance of a singleton class is a valid instance, so it is perfectly able to be the recipient of nonstatic member functions. If you expose your singleton factory as a static function then have all of your public functionality as public nonstatic member functions and your private functionality as private nonstatic member functions, anyone that can get at the class can access the public functionality by simply invoking the singleton factory function.
You don't describe whether all of the functionality you're trying to wrap up is as related as to justify being in the same class, but if it is, this approach might work.
If you take a "C-like" approach and just use top-level functions, you can make them private by declaring them in the .cpp file rather than the publicly-included .h file. You should also make them static (or use an anonymous namespace) if you take that approach.
In C++, say you want to declare a global variable to be used by many. How do you do it?
I commonly use declare and define in cpp file, and then use extern in other cpp file (and not headers).
I don't like this approach, and I am considering something along these lines:
In a header file:
some_file.h
Class MYGlobalClass
{
};
MyGlobalClass& MyGlobalClassInstance()
{
static MYGlobalClass instance;
return instance;
}
Edit
Consider in the following contexts:
can be used in multi-threaded applications
namespace pollution
may NOT necessery be a singleton, as many instances of this might be created
What are your thoughts, suggestions, new ideas?
The best advice is probably "try to avoid globals". People don't need global variables as often as they think. Usually it turns out that "passing everything as arguments to constructors" isn't quite as much work as people think when they hear the suggestion. It also tends to lead to cleaner code with fewer, and more explicit, dependencies.
I'm not aware of any "correct" way to declare globals in C++. The way you do it now works fine, but the order of initialization is unspecified, so if there are any dependencies between your globals, you're in trouble.
A function returning a static instance more or less solves that problem, but isn't thread safe.
And a singleton is just a terrible idea. It doesn't solve your problem, but adds additional constraints to your code, which weren't actually necessary, and will most likely come back and bite you later.
Declare as extern in one header file included by "many" and define it in one *.cpp file
Declare it in one header file (using extern), and define it in one .cpp (or whatever other extension) file. You may use a function and return a reference to a static variable like you showed to circumvent problems with construction order relative to other such namespace scope variables in other .cpp files. But remember that won't protect you from destruction order problems - which is in the exact reverse order from construction (these things are called "static initialization order fiasco". If you use a function like yours and put it into headers, make it inline to make the redefinition of the function valid when it is included into multiple .cpp files (logically, the function is still only apparent once, because the static in it will only exist once, not separately for each file it is included into). Alternatively just declare it in a header but define it in one .cpp file (but then, remove the inline from it!).
inline A& getA() { static A a; return a; }
The potential problems with destruction order can be circumvented by using new:
inline A& getA() { static A *a = new A; return *a; }
The destructor of it, however, will never be called then. If you need thread safety, you should add a mutex that protects against multiple accesses. boost.thread probably has something for that.
Your idea of a static inside the accessor function is significantly different from a global variable. The difference is when it is constructed, and is most likely to be a major problem with multiple threads. What if two threads call MyGlobalClassInstance at the same time? Depending on the environment, but I suspect this is typical of most C++ compilers, you will potentially get two calls to the constructor of MyGlobalClass running at the same time, addressing the same area of memory.
If you're single-threaded, it's less likely to be a problem.
If you declare the instance as a normal static member or as a normal global variable in the source file, you'll probably have an easier time, because the constructor will be called before main executes, before you have a chance to start other threads.
declare and define in cpp file
Keep the extern-ed declaration in a header. Define it only once in an implementation file.
You are close. Use a namespace instead for global variables.
namespace myns {
int foo = 0;
}
Now, if it is a class object, you are looking at the Singletion pattern. In fact, your sample code reflects a Singleton design. However, if you are going to define the function in the header, make it inline -- ODR violation otherwise.
It it's truly a global variable that could theoretically be accessed externally by any module, you should put the extern declaration in the header file:
// MyClass.h
class MyClass { ... };
extern MyClass myGlobalInstance;
// MyClass.cpp
MyClass myGlobalInstance;
If it's just a global object that should really only be accessed by a single module, limit its scope by either making it a private (or protected) static class variable, a static function variable (if it's only needed by one function), or in an anonymous namespace:
Option 1:
// MyClass.h
class MyClass
{
private: // or protected, if you want it accessible by subclasses
static MyClass myGlobalInstance;
};
Option 2:
// MyClass.cpp
void someFunction()
{
// it's global, but only accessible inside this function
static MyClass myGlobalInstance;
...
}
Option 3:
// MyClass.cpp
namespace
{
MyClass myGlobalInstance;
}
// it's now only accessible in this file
extern MyGlobalClass MyGlobalClassInstance;
Edit: Not static >.<
Why not use good old singleton pattern?