Declare variables in unnamed namespace - c++

In my current job, I am seeing variables declared in the unnamed namespace in the cpp file and used only by that class as if they are member variables.
I see it as an interesting way of keeping only interface information in .h and implmentation in .cpp and is less work than the usual pimpl idiom.
I see people using pimpl all the time but never this approach, is there any problem with it?

Variables declared in the unnamed namespace of a .cpp file are file scoped; this means that there is only one instance per execution of the program.
You can see this for yourself by creating two instances of your object and observing that they interfere with each other's variables in the unnamed namespace.

Show some example code please. AFAIK, you cannot declare member variables in the unnamed namespace (unless the class itself is declared in the unnamed namespace).
The unnamed namespace was introduced to replace the common practice of declaring variables as static that are used in just one compilation unit.

Related

Is initializing variables in a namespace similar to initializing them as a class member?

In other words: is it fair to say that a namespace has member variables and functions just like a class does?
Not really. A namespace is used to limit the scope of variables, functions and classes. Meaning that by putting them into a namespace, you can have the same named function appear in your code and distinguish them through the use of a namespace.
A class is meant to represent a self-contained set of data (the variables) with a set of operations (the functions) to be performed on that data.
While you can have classes that only have static members and only publicly accessible variables, you start to lose the advantages (and the point) of classes.
No.
The terms member, member variables, member functions and methods are commonly used for class (struct) variables and functions only.
Functions in a namespace are just functions in the scope of the namespace, like variables are simply variables in the scope of the namespace.
Besides the differences between namespaces and classes regarding access and other stuff, the most import difference here is that you can create multiple objects of a class which then each hold their data in their member variables, and the methods == member functions work on this data.

Different Between Static Mutext and Not Static Mutex

I have a code in .cpp
namespapce A
{
namespace
{
static CMutex initMutex;
}
void init()
{
//code here
}
void uninit()
{
//code here
}
}
What is the different if I remove the static in the mutex and if there is a static? And what is the use of the static?
Thanks!
If mutex is static and if it would have been in the header and that header included in 2 cpp files(2 translational units), the lock applied by the code in first file will not be seen by the second file which is dangerous. This is because the 2 units has separate static of the mutex. In that case a global mutex is preferable.
If this is C++ then use RAII mechanism to manage mutex lock and unlock. THis is c++, where is the class? Encapsulate things into a class.
RAII example (basic one, things can be encapsulated into class):
http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization
You are Kind of mixing up C and C++. The keyword static in C has the intention to narrow the scope of a variable down to the translation unit. You could define it globally in the translation unit, but it was not visible to other translation-units.
Bjarne Stroustrup recommends to use anonymous namespaces in C++ instead of using static like in C.
From this post it says
The C++ Standard reads in section 7.3.1.1 Unnamed namespaces, paragraph 2:
The use of the static keyword is deprecated when declaring objects
in a namespace scope, the unnamed-namespace provides a superior alternative.
Static only applies to names of objects, functions, and anonymous unions, not to type declarations.
static merely does two things:
makes a variable to exist for the entire life of a program (but this is global level, so anything here exist for the whole program life!)
makes a variable visible only in the translation unit it is declared (but this apply to whatever is in an anonymous namespace).
So, in fact, in this particular context, static does nothing.

Multiple classes in one .cpp file

I was wondering if it is considered bad practice to have multiple classes in one .cpp file. I have a background in Objective-C, where this is rarely done.
It makes for less readable code because you usually expect a class's definition to be in the header with the same name and the implementation in an implementation file with the same name.
There are cases in practice where a class is relatively small and closely-related small classes can be grouped together, but it's on a case-by-case basis.
As the other answer points out, it makes for less readable code.
It is important to also consider the scope of a nested class:
A nested class is declared within the scope of another class. The name
of a nested class is local to its enclosing class. Unless you use
explicit pointers, references, or object names, declarations in a
nested class can only use visible constructs, including type names,
static members, and enumerators from the enclosing class and global
variables.
Source

C++ namespace and static variables

I have a requirement where a (const) variable should be available throughout an entire cpp which consists of several classes. I have decided to use a namespace to solve the problem, but unsure about the following:
Do I need to define this variable as static?
Is it true that I can avoid making the variable static only if I go with an unnamed namespace?
You don't need to define the variable as static, or in an anonymous namespace. However, if you're not using this object outside of the file it's defined in, it's a good idea, to reduce namespace pollution and speed up links (by reducing how many symbols need to be considered by the linker).
If you declare a variable in an anonymous namespace, it will be effectively static. There's no need to actually make it static as well (although you can if you like). The advantage of anonymous namespaces is you can also define types (classes, structs, enums, typedefs) as well as static variables and functions.

Where to declare/define class scope constants in C++?

I'm curious about the benefits/detriments of different constant declaration and definition options in C++. For the longest time, I've just been declaring them at the top of the header file before the class definition:
//.h
const int MyConst = 10;
const string MyStrConst = "String";
class MyClass {
...
};
While this pollutes the global namespace (which I know is a bad thing, but have never found a laundry list of reasons why it is bad), the constants will still be scoped to individual translation units, so files that don't include this header won't have access to these constants. But you can get name collisions if other classes define a constant of the same name, which is arguably not a bad thing as it may be a good indication of an area that could be refactored.
Recently, I decided that it would be better to declare class specific constants inside of the class definition itself:
//.h
class MyClass {
public:
static const int MyConst = 10;
...
private:
static const string MyStrConst;
...
};
//.cpp
const string MyClass::MyStrConst = "String";
The visibility of the constant would be adjusted depending on whether the constant is used only internally to the class or is needed for other objects that use the class. This is what I'm thinking is the best option right now, mainly because you can keep internal class constants private to the class and any other classes using the public constants would have a more detailed reference to the source of the constant (e.g. MyClass::MyConst). It also won't pollute the global namespace. Though it does have the detriment of requiring non-integral initialization in the cpp file.
I've also considered moving the constants into their own header file and wrapping them in a namespace in case some other class needs the constants, but not the whole class definition.
Just looking for opinions and possibly other options I hadn't considered yet.
Your claim that declaring a non-integral constant as a static class member "have the detriment of requiring non-integral initialization in the cpp file" is not exactly solid, so to say. It does require a definition in cpp file, but it is not a "detriment", it is a matter of your intent. Namespace-level const object in C++ has internal linkage by default, meaning that in your original variant the declaration
const string MyStrConst = "String";
is equivalent to
static const string MyStrConst = "String";
i.e. it will define an independent MyStrConst object in every translation unit into which this header file is included. Are you aware of this? Was this your intent or not?
In any case, if you don't specifically need a separate object in every translation unit, the declaration of MyStrConst constant in your original example is not a good practice. Normally, you'd only put a non-defining declaration in the header file
extern const string MyStrConst;
and provide a definition in the cpp file
const string MyStrConst = "String";
thus making sure that the entire program uses the same constant object. In other words, when it comes to non-integral constants, a normal practice is to define them in cpp file. So, regardless of how you declare it (in the class or out) you will normally always have to deal with the "detriment" of having to define it in cpp file. Of course, as I said above, with namespace constants you can get away with what you have in your first variant, but that would be just an example of "lazy coding".
Anyway, I don't think there is a reason to over-complicate the issue: if the constant has an obvious "attachment" to the class, it should be declared as a class member.
P.S. Access specifiers (public, protected, private) don't control visibility of the name. They only control its accessibility. The name remains visible in any case.
Pollution of the global namespace is bad because someone (e.g. the writer of a library you use) might want to use the name MyConst for another purpose. This can lead to severe problems (libraries that can't be used together etc.)
Your second solution is clearly the best if the constants are linked to a single class. If that isn't so easy (think of physical or math constants without ties to a class in your program), the namespace solution is better than that. BTW: if you must be compatible to older C++ compilers, remember some of them can't use integral initialization in a header file - you must initialize in the C++ file or use the old enum trick in this case.
I think there are no better options for constants - at least can't think of one at the moment...
Polluting the global namespace should be self-evidently bad. If I include a header file, I don't want to encounter or debug name collisions with constants declared in that header. These types of errors are really frustrating and sometimes hard to diagnose. For example, I once had to link against a project that had this defined in a header:
#define read _read
If your constants are namespace pollution, this is namespace nuclear waste. The manifestation of this was a a series of very odd compiler errors complaining about missing the _read function, but only when linking against that library. We eventually renamed the read functions to something else, which isn't difficult but should be unnecessary.
Your second solution is very reasonable as it puts the variable into scope. There's no reason that this has to be associated with a class, and if I need to share constants among classes I'll declare constants in their own namespace and header file. This isn't great for compile-time, but sometimes it's necessary.
I've also seen people put constants into their own class, which can be implemented as a singleton. This to me seems work without reward, the language provides you some facilities for declaring constants.
You can declare them as globals in the c++ file, as long as they are not referenced in the header. Then they are private to that class and won't pollute the global namespace.
Personally I use your second approach; I've used it for years, and it works well for me.
From a visibility point I would tend to make the private constants file level statics as nobody outside the implementation file needs to know they exist; this helps prevent chain reaction recompiles if you need to change their names or add new ones as their name scope is the same as their usage scope...
If only one class is going to use these constants, declare them as static const inside the class body. If a bunch of related classes are going to use the constants, declare them either inside a class/struct that only holds the constants and utility methods or inside a dedicated namespace. For example,
namespace MyAppAudioConstants
{
//declare constants here
}
If they are constants used by the whole application (or substantial chunks of it), declare them inside a namespace in a header that is (either implicitly or explicitly) included everywhere.
namespace MyAppGlobalConstants
{
//declare constants here
}
don't pollute global namespace, pollute local.
namespace Space
{
const int Pint;
class Class {};
};
But practically...
class Class
{
static int Bar() {return 357;}
};