Private namespace in source files - c++

I have a doubt regarding private methods & functions.
Let's say I have some utility methods that needn't be inside a class. But those same methods need to call other ones that I don't want to expose to the user. For example:
Suspect.h
namespace Suspect {
/**
* \brief This should do this and that and more funny things.
*/
void VerbalKint(void); // This is for you to use
}
Suspect.cpp
namespace Suspect {
namespace Surprise {
/**
* \brief The user doesn't need to be aware of this, as long
* the public available VerbalKint does what it should do.
*/
void KeyserSoze(void) {
// Whatever
}
} // end Surprise
void VerbalKint(void) {
Surprise::KeyserSoze();
}
}
So, this layout works. When including the Suspect.h, only VerbalKint is visible.
This can be as well achieved using a class and marking VerbalKint as static:
class Suspect {
public:
// Whatever
static void VerbalKint(void);
private:
static void KeyserSoze(void);
};
I would like to know if there's any difference between the two approaches. Is one better (faster, easier to maintain) than the other?
What are your thoughts?

If the functions are 'free', you should use an anonymous namespace in the *.cpp:
namespace Suspect {
namespace Surprise {
namespace {
void KeyserSoze(void) {
// Whatever
}
} // end anon
} // end Surprise
} // end Suspect
or even:
namespace {
void KeyserSoze(void) {
// Whatever
}
} // end anon
This keeps it away from clients so they cannot access, depend on, or collide with your exports when linking. It also keeps unnecessary declarations from them, reducing their compile times and potentially link times or binary sizes if definitions are visible. Finally, it makes it private so they cannot depend on it and you do not need to maintain it for their use. You can still pass these to the outside world, if you choose (function pointer in KeyserSoze()'s case).
At other times, it is preferable to declare a private member function in your class then define it in the *.cpp (where possible). Typically, you would opt for this approach when you need a closer relationship with the class (e.g. when you need access to some members). You said this was not the case in the question, but I'm just reiterating when private members should be used.

The best approach is to define all helper functions in an unnamed namespace in Suspect.cpp, instead of in the Suspect::Surprise namespace.
In your case, this would be:
namespace{
void KeyserSoze(){ ... };
}
You can simply call KeyserSoze without any namespace specifiers from within Suspect.cpp.
You can find more information about that here: Unnamed/anonymous namespaces vs. static functions
Another alternative is to declare KeyserSoze to be static, but this is not advised by the standard. 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

Actually, even though the function is not visible to the eye when you do not declare it in any header; it still is available to the user should they write the declaration.
In C++, the mechanism to hide symbols declared at file level is:
static for (global) variables and functions
namespace { ... } (anonymous namespaces) for anything you wish (more general, more verbose)
For example:
// Suspect.cpp
namespace Suspect {
static void KeyserSore() {}
void VerbalKing() { KeyserSore(); }
}

The main difference between putting something in a class or a namespace is that you can't add extra static functions to a class in another header file.
This:
a.h
namespace Fred {
void Somefunc();
}
b.h
namespace Fred {
void Anotherfunc();
}
work, although neither a nor b know what each other has done to their namespaces. This could conceivably cause problems, such as this:
c.h
namespace Fred {
void Thirdfunc();
}
d.h
namespace Fred {
bool Thirdfunc();
}
which is all fine and dandy until you get to run the program...
This is, whilst not impossible, a lot less likely with classes.
In your example, with only one source file, you might also want to consider using the anonymous namespace as that restricts declarations to file scope, so people outside your file can't access them (or clash with them) by accident.

Related

Why aren't internally included namespaces private?

Or in other words, why allow this to compile?:
#include <iostream>
namespace N{
using namespace std;
string bar() { return "bar";}
void foo() { cout<<"foo\n"<<bar()<<endl; }
}
int main(){
N::foo();
N::cout<<">why allow this??\n"; //Can't ::N:: keep `::std::` to itself?
}
Why not have each namespace resolve its inner include directives internally and only "export" what's actually in that namespace?
Making it work like that would eliminate the need to use fully qualified names inside namespace blocks in most places and I can't think of the drawbacks.
Does this behavior have any purpose besides making things possibly easier on implementers?
Edit:
Turns out it behaves at least somewhat sensible in that there's no contention between a current namespace (B) and an included (using directive'd) namespace (C)—the current namespace (B) always wins. However if the current namespace (B) is included elsewhere (A) then suddenly, the suddenly, B and C start competeting, which must be weird for the user of B who never even knew about C:
#include <iostream>
namespace C {
void method() { std::cout<<"C\n"; }
void cmethod() { std::cout<<"cmethod\n"; }
}
namespace B { using namespace C;
void method() { std::cout<<"B\n"; } }
///^^Library
///>User code
namespace A {
using namespace B;
void aMethod() {
//method(); Error:
//conflict between B::method and C::method even though A doesn't even know about C
B::method(); //Why do I need to write this when I just included B?
cmethod(); //This simply leaks from C because of the u-directive
}
}
int main() { A::aMethod(); }
As far as I can tell, this feature has been explicitly introduced by N0635, proposed by Bjarne Stroustrup himself. The first reason mentioned in that proposal why this feature should be introduced is because he has been "repeatedly asked to make this work:"
namespace A {
int f();
}
using namespace A;
void g()
{
::f(); // call A::f
}
and this
namespace A {
int f();
}
namespace B {
using namespace A;
}
void g()
{
B::f(); // call A::f
}
Under the current rules, this doesn’t work because B::f means "look
for an f declared in B" and f isn’t declared in B.
There are additional reasons mentioned in that paper, though:
One could argue that this interpretation is closer to the way B::f
always worked for a base class B. A benefit would be a
simplification of the library headers because
namespace std {
int printf(const char* ... );
// ...
}
using namespace std;
int main()
{
::printf("Hello pedantic world\n");
}
would now work. It this relaxation is accepted, I would expect the
standard .h headers to be changed to use using-directives (as
originally intended) rather than using-declarations. This would save
hundreds of lines of declarations.
Also, if someone takes
static void f(char);
void f(int);
void g()
{
::f(’a’); // calls f(char)
}
and naively translates it to
namespace { void f(char); }
void f(int);
void g()
{
::f(’a’); // current rules: class f(int)
// relaxed rules: calls f(char)
}
then there would be a change of meaning under the current rules, but
not under my suggested new rules. Some people have worried about the
change of meaning implied by the current rules.
People have responded to this proposal with remarks like "obvius,"
"that was what I always meant," and "I thought that was what it did."
I consider that an indicator that the relaxation will not lead to
added teaching problems, but might reduce such problems.
In fact, namespaces didn't exist in the original version of The C++ Programming Language (1986). They were introduced later, with the aim to manage logical grouping of elements. The ability to compose new namespaces out of other existing namespaces was part of desired features (see section 8.2.8 of the current version of Stroustrup's book).
The standard being as it is, the real question would be: is using the std namespace inside your own one is a good practice in view of Herb Sutter's recommendations ? This would probably be safer:
// === For exposure in a header ====
namespace N{
std::string bar(); // std:: because not sure std is used in the surrounding context
void foo();
}
// === For use in the implemenation ===
using namespace std; // for the implementation
namespace N {
string bar() { return "bar";}
void foo() { cout<<"foo\n"<<bar()<<endl; }
}
The current namespace logic has also advantages. You could for example manage different versions of an library, still allowing for use of legacy parts during a transition period, through explicit scope resoultion.
namespace my_super_lib {
namespace my_super_lib_v1 { // legacy API
void super_f() { std::cout<<"1"; }
void super_old() {} // obsolete,
}
namespace my_super_lib_v2 { // new API
void super_f(int a) { std::cout<<"2"; }
}
using namespace my_super_lib_v2; // use now the new API
using my_super_lib_v1::super_old; // but still allow some legacy
};
Stroutrup's FAQ shows similar examples with in addition a clear case for inline namespaces.
Well, if you don't want that to happen, don't do using namespace std or similar inside the namespace N...
It is actually quite useful sometimes to be able to "export" something from one namespace into another. Imagine that I've got this clever set of functions to do flubbetiflap functionality. To this goal, I'm borrowing a set of functions in the kerflunk namespace, which provides some really useful type declarations I want to use in my functionality. So I can do:
namespace flubbetiflap
{
using namespace kerflunk;
... all the good code what I wrote to do flubbetiflap goes here ...
};
Now, the users of my flubbetiflap won't actually need to know that I'm using kerflunk for my implementation.
Sure, there could be all sorts of atlernative solutions that one COULD come up with for doing this. But I can certainly see how it can be useful.
Obviously, nobody outside of the C++ committee would actually know much about the discussion that went on to determine how this should work...

Static member initialization using CRTP in separate library

After digging the web, I found some reference to a powerful pattern which exploits CRTP to allow instantiation at run-time of static members:
C++: Compiling unused classes
Initialization class for other classes - C++
And so on.
The proposed approach works well, unless such class hierarchy is placed into an external library.
Doing so, run-time initialization no more works, unless I manually #include somewhere the header file of derived classes. However, this defeats my main purpose - having the change to add new commands to my application without the need of changing other source files.
Some code, hoping it helps:
class CAction
{
protected:
// some non relevant stuff
public:
// some other public API
CAction(void) {}
virtual ~CAction(void) {}
virtual std::wstring Name() const = 0;
};
template <class TAction>
class CCRTPAction : public CAction
{
public:
static bool m_bForceRegistration;
CCRTPAction(void) { m_bForceRegistration; }
~CCRTPAction(void) { }
static bool init() {
CActionManager::Instance()->Add(std::shared_ptr<CAction>(new TAction));
return true;
}
};
template<class TAction> bool CCRTPAction<TAction>::m_bForceRegistration = CCRTPAction<TAction>::init();
Implementations being done this way:
class CDummyAction : public CCRTPAction<CDummyAction>
{
public:
CDummyAction() { }
~CDummyAction() { }
std::wstring Name() const { return L"Dummy"; }
};
Finally, here is the container class API:
class CActionManager
{
private:
CActionManager(void);
~CActionManager(void);
std::vector<std::shared_ptr<CAction>> m_vActions;
static CActionManager* instance;
public:
void Add(std::shared_ptr<CAction>& Action);
const std::vector<std::shared_ptr<CAction>>& AvailableActions() const;
static CActionManager* Instance() {
if (nullptr == instance) {
instance = new CActionManager();
}
return instance;
}
};
Everything works fine in a single project solution. However, if I place the above code in a separate .lib, the magic somehow breaks and the implementation classes (DummyAction and so on) are no longer instantiated.
I see that #include "DummyAction.h" somewhere, either in my library or in the main project makes things work, but
For our project, it is mandatory that adding Actions does not require changes in other files.
I don't really understand what's happening behind the scene, and this makes me uncomfortable. I really hate depending on solutions I don't fully master, since a bug could get out anywhere, anytime, possibly one day before shipping our software to the customer :)
Even stranger, putting the #include directive but not defining constructor/destructor in the header file still breaks the magic.
Thanks all for attention. I really hope someone is able to shed some light...
I can describe the cause of the problem; unfortunately I can't offer a solution.
The problem is that initialisation of a variable with static storage duration may be deferred until any time before the first use of something defined in the same translation unit. If your program never uses anything in the same translation unit as CCRTPAction<CDummyAction>::m_bForceRegistration, then that variable may never be initialised.
As you found, including the header in the translation unit that defines main will force it to be initialised at some point before the start of main; but of course that solution won't meet your first requirement. My usual solution to the problems of initialising static data across multiple translation units is to avoid static data altogether (and the Singleton anti-pattern doubly so, although that's the least of your problems here).
As explained in Mike's answer, the compiler determines that the static member CCRTPAction<CDummyAction>::m_bForceRegistration is never used, and therefore does not need to be initialised.
The problem you're trying to solve is to initialise a set of 'plugin' modules without having to #include their code in a central location. CTRP and templates will not help you here. I'm not aware of a (portable) way in C++ to generate code to initialise a set of plugin modules that are not referenced from main().
If you're willing to make the (reasonable) concession of having to list the plugin modules in a central location (without including their headers), there's a simple solution. I believe this is one of those extremely rare cases where a function-scope extern declaration is useful. You may consider this a dirty hack, but when there's no other way, a dirty hack becomes an elegant solution ;).
This code compiles to the main executable:
core/module.h
template<void (*init)()>
struct Module
{
Module()
{
init();
}
};
// generates: extern void initDummy(); Module<initDummy> DummyInstance
#define MODULE_INSTANCE(name) \
extern void init ## name(); \
Module<init ## name> name ## Instance
core/action.h
struct Action // an abstract action
{
};
void addAction(Action& action); // adds the abstract action to a list
main.cpp
#include "core/module.h"
int main()
{
MODULE_INSTANCE(Dummy);
}
This code implements the Dummy module and compiles to a separate library:
dummy/action.h
#include "core/action.h"
struct DummyAction : Action // a concrete action
{
};
dummy/init.cpp
#include "action.h"
void initDummy()
{
addAction(*new DummyAction());
}
If you wanted to go further (this part is not portable) you could write a separate program to generate a list of MODULE_INSTANCE calls, one for each module in your application, and output a generated header file:
generated/init.h
#include "core/module.h"
#define MODULE_INSTANCES \
MODULE_INSTANCE(Module1); \
MODULE_INSTANCE(Module2); \
MODULE_INSTANCE(Module3);
Add this as a pre-build step, and core/main.cpp becomes:
#include "generated/init.h"
int main()
{
MODULE_INSTANCES
}
If you later decide to load some or all of these modules dynamically, you can use exactly the same pattern to dynamically load, initialise and unload a dll. Please note that the following example is windows-specific, untested and does not handle errors:
core/dynamicmodule.h
struct DynamicModule
{
HMODULE dll;
DynamicModule(const char* filename, const char* init)
{
dll = LoadLibrary(filename);
FARPROC function = GetProcAddress(dll, init);
function();
}
~DynamicModule()
{
FreeLibrary(dll);
}
};
#define DYNAMICMODULE_INSTANCE(name) \
DynamicModule name ## Instance = DynamicModule(#name ".dll", "init" #name)
As Mike Seymour stated the static template stuff will not give you the dynamic loading facilities you want. You could load your modules dynamically as plug ins. Put dlls containing an action each into the working directory of the application and load these dlls dynamically at run-time. This way you will not have to change your source code in order to use different or new implementations of CAction.
Some frameworks make it easy to load custom plug ins, for example Qt.

How to use namespaces when implementing methods?

I have a class declaration in a .hpp line enclosed in a named namespace:
namespace mylib
{
class MyClass
{
public:
MyClass();
}
}
I plan to implement the class' functionality in a .cpp file.
However, both of these methods seem to work:
mylib::MyClass::MyClass()
{
}
and
namespace mylib
{
MyClass::MyClass()
{
}
}
And so I am left wondering what is the difference between these methods and whether I should prefer one over the other.
It's personal preference. However you can save code using the namespace keyword with brackets. Also these might be easier to read (knowing that everything is in the same namespace anyway).
Also keep in mind that not using namespace might get rather tedious and confusing once you start using custom types defined within your class, e.g. a different local class used as a return or parameter type:
myNamespace::myClass::myType &myNamespace::myClass::doSomething(const myNamespace::myOtherClass &theOther) {
// ...
}
namespace myNamespace {
myClass::myType &myClass::doSomethingDifferent(const myOtherClass &theOther) {
// ...
}
}
mylib:: contains 7 characters
namespace mylib { } contains 16 characters (excluding spaces)
Hence, by using the second form you will save typing time as long as you define 3 or more methods.

How can I stop letting other clutter / expand my namespace?

Suppose, if I have a namespace in one header file. I don't want that people should be able to expand it to other files. Is it possible in C++ ?
//N.h
namespace N {
//...
}
//Other.h
#include"N.h"
namespace N { // <--- don't allow this
void foo () {}
}
[Note: Asking this for knowledge and curiosity. Because, have heard many times that one should not expand std.]
AFAIK, you can't do this in C++, and I don't see any practical reason for it either.
You can wrap your code into a class instead of a namespace; since a class declaration cannot be spread over several headers, others cannot add to it.
But again, I don't see why you think this is a problem, and I'd be curious to see an example.
You can only ask people to behave, not force them. Perhaps you can try this:
namespace milind
{
namespace Private
{
// Please don't add stuff to my private namespace
... Important implementation details goes here
}
}
You could use a class with all statics instead of a namespace to simulate the behavior.
Found one way. I can encapsulate the namespace inside another dummy type of namespace and then use it. To avoid verbosity, we can use an alias to the existing namespace.
i.e.
//N.h
namespace DUMMY_ { // <--- put a dummy outer namespace
namespace N {
//...
}
}
namespace N = DUMMY_::N; // alias the name to the original name
//Other.h
#include"N.h"
namespace N { // <--- error !!
void foo () {}
}
Edit: With above solution it's less likely that people would expand namespace N. However, as #Charles comment, still DUMMY_ is visible to the reader. Which means one can still do like:
namespace DUMMY_ {
namespace N { // ok
void foo () {}
}
}
So only way remains to prohibit the undesired expansion is by replacing:
namespace N = DUMMY_::N;
with,
#define N DUMMY_::N
This will work as per expected; but we enter the region of macros.

c++ variable visibility

PLEASE READ THE SECOND EDIT FIRST.
I am looking for books or websites that explain in detailed the c/c++ memory management models. One of the things I am trying to understand is:
namespace A {
SomeClass A;
}
vs
namespace A {
static SomeClass A;
}
vs
SomeClass A;
vs
static SomeClass A;
Thank you very much.
EDIT:
Sorry for the confusion, I mixed the concepts together, and asked the wrong questions.
Namespaces allow to group entities like classes, objects and functions under a name. This way the global scope can be divided in "sub-scopes", each one with its own name.
You use keyword using to introduce a name from a namespace into the current declarative region.
For example:
without using namespace you will write:
#include
int main () {
std::cout << "Hello world!\n";
return 0;
}
However you can also write:
#include
using namespace std;
int main () {
cout << "Hello world!\n";
return 0;
}
This allows you not to append napespace identifier before every
In C++ static class has no meaning unlike other OOP languages. You can have static data members methods.
Instead you can create:
1.A static method in class
class SomeClass
{
public: static void myMethod(int x..)
{
}
}
2.Create a free function in namespace
namespace A
{
void myMethod(int x..)
{
}
}
Latter is better suited when you do not need an object. No class no object...
In both cases enclosing a class within namespace allows you to to group entities under a common name.
First, namespaces are only known until compilation, after that they're non-existant. That said, your first half is no different from your second half in the final program, at least as far as I know. Correct me if I'm wrong please.
Then, if both static SomeClass A and SomeClass A are at global scope (file level), then they're the same too.
Next, if both declarations are inside of a class, struct or function, then the static version will be put into the data segment of the executable too, while the non-static variant will be a normal stack variable.
Again, please, correct me if I'm wrong, but that's it as far as I know it.