开发者

Appropriate use of global const variables in C++?

开发者 https://www.devze.com 2023-04-06 07:01 出处:网络
I am working on a program for my CS class. It is a simulation of a del开发者_C百科ivery company\'s activities at an airport.

I am working on a program for my CS class. It is a simulation of a del开发者_C百科ivery company's activities at an airport.

This is a very simple, small program consisting of a few header and source files and a main.cpp source file that orchestrates the simulation.

There are certain given constant values, such as the frequency of shipment arrival, the load capacity of planes, the amount of time it takes a worker to process certain items, etc. (all are integer values). It is necessary for me to access these variables throughout several functions in main.cpp

It seemed reasonable to declare these above the main() function as const ints, effectively making them global, e.g.

const int kTotalTime = 2000;

const int kPlaneCapacity = 25;

int main(){//...program code}

I am aware that global variables are to be avoided in most situations, as there are no restrictions on where they can be called and/or modified, which can lead to accidentally breaking parts of the program which in turn may be difficult to debug, as well as causing compatibility issues for future code, etc. However since these are read-only values of a primitive data type, which are used throughout the program, it seemed like a reasonable solution. Also, it makes an explicit statement about the purpose of the variables to anyone reading the code as well as to the compiler.

Questions: Is my logic flawed? How so? When are global variables (const or not) reasonable to use? If this is a bad solution, then how would you suggest declaring constant read-only values such as these?

Thank you very much for your time!


Regarding the size and purpose of your program (as I understand it from your description) it probably doesn't matter, but since it has an educational context, I'd suggest to "do it right".

In such a situation I would go for a Config struct (or class, if you want to make it a bit smarter, see below) which carries the configuration values and can be tossed around your program. It has the advantage that you can easily change it if you have to, say, fetch your options from a file or from the command line.

As for the class versus struct thingy (note that I am making a logical distinction here, not a technical). Either you just put all values as members in your struct and pass around const refs of it, or you make it a full fledged class with accessors that hide where the data is coming from (and how it is generated). Programming is always decision making and this is your decision to make. If you think you will have to allow more configuration possibilities in the future (like mentioned above) you may want to go for class abstraction.

Yet another option is to scatter your data across your program, which is actually a lot smarter than it sounds. If every class knows only its configuration options (and hides them) you can actually make use of the OOP language, you're using. Example:

// footype.h
class FooType {
  private:
    static const int fooOption;
};
// bartype.h
class BarType {
  private:
    static const float barOption;
};

The question is, how to initialise this. One way could be to create a config.cpp that looks like this:

#include "footype.h"
#include "bartype.h"

const int FooType::fooOption = 42;
const float BarType::barOption = 7.4;

So you have information hiding, and you still have all the config options together at one place (config.cpp).

Edit:

If you have config option that is required by many (more than one) different modules, you can go for a bit of sophistication (with indirection) like so:

// footype.h
class FooType {
  private:
    static const int& fooOption;
    static const bool& dumpLevel;
};
// bartype.h
class BarType {
  private:
    static const float& barOption;
    static const bool& dumpLevel;
};

config.cpp:

#include "footype.h"
#include "bartype.h"

static const int opt_foo = 42;
static const float opt_bar = 7.4;
static const bool opt_dumpLevel = false;

const int& FooType::fooOption = opt_foo;
const bool& FooType::dumpLevel = opt_dumpLevel;
const float& BarType::barOption = opt_bar;
const bool& BarType::dumpLevel = opt_dumpLevel;

You can even make the options non-const if you want (but I don't see the point in a configuration option that is mutable).


I think it's best to put your constants as static inside the class.

I assume you have the class Plane, just do this:

Plane.h

class Plane{
   static const int kPlaneCapacity;
   //....
}

Plane.cpp

const int Plane::kPlaneCapacity = 25;

Also, take good care of what you understand by constant. Pi is a constant. 10 is a constant. I do see how you would think a plane capacity is constant, but think about this: What if your teacher says that for your next assignment, your plane capacity should be 30, and not 25.


When are global variables (const or not) reasonable to use?

If your program is a multithreaded program then you should be giving a serious thought about using globals for they would need proper synchronization to avoid race conditions. Usually proper synchronization is not a very trivial task and requires some serious undrestanding and thought.

Here is an excerpt from a nice article:

Non-locality -- Source code is easiest to understand when the scope of its individual elements are limited. Global variables can be read or modified by any part of the program, making it difficult to remember or reason about every possible use. No Access Control or Constraint Checking -- A global variable can be get or set by any part of the program, and any rules regarding its use can be easily broken or forgotten.

Implicit coupling -- A program with many global variables often has tight couplings between some of those variables, and couplings between variables and functions. Grouping coupled items into cohesive units usually leads to better programs.

Memory allocation issues -- Some environments have memory allocation schemes that make allocation of globals tricky. This is especially true in languages where "constructors" have side-effects other than allocation (because, in that case, you can express unsafe situations where two globals mutually depend on one another). Also, when dynamically linking modules, it can be unclear whether different libraries have their own instances of globals or whether the globals are shared.

Testing and Confinement - source that utilizes globals is somewhat more difficult to test because one cannot readily set up a 'clean' environment between runs. More generally, source that utilizes global services of any sort that aren't explicitly provided to that source is difficult to test for the same reason.

Given all the above, As long as you understand the pitfalls and understand that the way you are using the globals does insulate your program against those pitfalls, then you can go ahead and very well use globals.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号