I am writing a library of utility classes, many of which are singletons. I have implemented them as such using inheritance:
template <class T>
class Singleton {
public:
T& getInstance() {
if(m_instance == 0) {
m_instance = new T;
}
return m_instance;
}
private:
static T* m_instance;
};
class SomeClass : public Singleton<SomeClass> {
public:
SomeClass() {}
virtual ~SomeClass() {}
void doSomething() {;}
};
Obviously this is a simple example, not an actual class. Anyways, I am finding that using code such as:
SomeClass::getInstance().doSomething();
Will create more than one instance of SomeClass. I am thinking this may be due to the fact that it is being used outside my library (.a) file as well as internally. For example, I am using a UI library not written by myself which is separately compiled and to which I am making additions. Some of these additions utilize singletons which are also being used in my .a library.
Is the separate compilation causing this? Something else?
The only way I have managed to get around the issue is to create a global object in my main.cpp file which I initialize with any singletons I will need. Then all code accesses this common global object with calls such as:
GlobalObject::getSomeClass().doSomething()
I hate having to add an additional method to this object every time I create another singleton. Plus the syntax seems clearer and more familiar using the first access method:
SomeClass::getInstance().doSomething();
Please let me know if you have any thoughts, opinions, etc.
Thanks.
Your problem is that your template is going to be instantiated in more than one compilation unit as it is completely inline. Therefore in every compilation unit that uses the template you will end up creating one singleton (per compilation unit). What you would need is to force global linkage, so that all compilation units reference the same template instantiation. The upcoming C++ standard will support this via extern template. What you can do now is to disable automatic instantiation in your project and manually instantiate the templates that you use explicitly. This way when you use the template in any compilation unit you will generate an unknown reference to the implementation which can then be satisfied by the linker from the (one) compilation unit where you do the explicit instantiation.
Are multiple threads accessing getInstance at the same time? That could cause multiple instances to be created. Consider:
Thread 1 executes the "if (m_instance==0)" and finds it true
Thread 2 executes the "if (m_instance==0)" and finds it true
Thread 1 allocates a new T
Thread 2 allocates a new T
Then one of them overwrites the other, and returns either one of the instances or the other (depending on compiler optimizations, etc.)
Every template class you create from Singleton is going to have it's own static m_instance member... those are not shared across the different classes because when the templates are instantiated, it actually generates different classes for each set of template parameters. Judging by the way you're doing your inheritance, this probably means that you'll end up with an instance of Singleton for every one of the classes that derive from it. Perhaps this is the cause of your issue?
Related
Right now I have two last problem with the first part of my library. And the first one is this thing not possible in C++ without hack (if I want the constexpr version), it's a derived class counter:
class FooBase {
protected:
static int Counter;
};
class Foo : public FooBase {
public:
static const int Type;
};
const int Foo::Type = ++FooBase::Counter;
struct FooTest : public Foo {};
Must be in a source file:
int FooBase::Counter = 0;
Why I need this counter? Well I use it as a type and an index into another array.
I have two problem with that:
The Type is not constexpr, but this thing seems not really possible
I have the only line of code that need to be put into a source file of my whole library
I can know how many derived class there is (with a macro that's not horrible) if it's can help, but I don't have any idea about something better.
Even if it's means add class or whatever, I'd like to see your suggestions/alternatives. If you can at least remove the int FooBase::Counter = 0; line, it will be nice.
PS: I don't have any C++ limitations, TS are welcome.
PSS: The real case is a little more complex and use CRTP, I hope it won't be a problem.
It is not possible in principle to have a derived class counter to be a compile time constant. The reason is that the compiler cannot know, when compiling one translation unit, how many derived classes are in other translation units, or in which order you will link them.
Even worse, you might decide to put some object files containing derived classes into a dynamic library that you load at runtime. In that case, the total number of derived classes may change during the run time of the program. And again, there is no way for the compiler to determine if that is the case.
So in short, what you are seeing is not a specific shortcoming of the C++ language, but a fundamental restriction of the separate compilation model. Which means, if you want to do it, you need to write an external tool operating on the complete source code for generating the initializer expressions of the constexpr variables.
I'm writing a C++ hardware abstraction layer (HAL), which needs to be as fast as possible.
Polymorphism offers the best API, but Virtual Table lookups really kill the speed of the code.
This lead me to using templates in conjunction with policies to get compile-time polymorphism. But because templates with different arguments get instantiated as completely different types, I can not use them interchangeably in function calls unless the function is a template as well.
However, I dont want to force the user of my HAL library to write all function as templates because I have used templates.
For illustration purposes, suppose this is my HAL:
template<typename T_POLICY>
class I2CManager {
public:
void send(uint8_t data) {
T_POLICY::send(data);
++sent_data;
}
private:
int sent_data; // Just to illustrate that I2CManager has state
};
class I2C1 {
static void send(uint8_t data) { /* Run some code here */ }
};
class I2C2 {
static void send(uint8_t data) { /* Run other code here */ }
};
// OTHER HW
template<typename T_POLICY>
class UARTManager { ··· };
class UART1 { ··· };
class UART2 { ··· };
template<typename T_POLICY>
class TIMERManager { ··· };
class TIMER1A { ··· };
class TIMER1B { ··· };
This works and I can now create a I2CManager with different policies, such as follows. I can even have several I2CManagers running with different policies at the same time.
I2CManager<I2C1> i2c1;
I2CManager<I2C2> i2c2;
i2c1.send(0x11); // This works
i2c2.send(0x11); // This also works
Now, i2c1 and i2c2 have the same public methods, yet they are not interchangeable. Consequently, the user of my HAL library is forced to use templates as well.
// THIS DOES NOT WORK
void foo(I2CManager m) { m.send(0x11); }
foo(my_manager_1);
// BUT THIS WORKS
template<typename T>
void foo(I2CManager<T> m) { m.send(0x11); }
foo(i2c1);
Can I somehow get compile-time polymorphism but allow the end-user to treat it as if it was normal polymorphism? I don't care if the inner code in my library gets ugly or difficult to read for the sake of speed, but the API has to be as simple and intuitive as possible.
Actually, I want foo() to be specialized (and replicated in code) for the different parameters as if it was a template, but I don't want the user of my library to notice it is a template function. Altought alternatives to templates are also welcome.
I don't know if this is even possible, but I have read something about concepts which will appear in the next C++ standard. I want compile-time polymorphism, but as userfrliendly as runtime polymorhism.
Considerations:
Because I'm interfacing HW, each instantiation of my HWManagers with
different policies will be unique (i.e. There is only one
HWManager instance, and one HWManager instance,
and may or may not exist simultaneously).
All instances are created by the library as global variables, and are
not heapable.
All policy methods are extremely short, so having multiple unique
instances due to templates is preferable to Virtual Tables for the
sake of execution speed.
Code size does not matter (its for embedded systems), but RAM usage
and execution speed does. I need as much as possible to be solved
during compile time. Again, I'm willing to have a over-bloated
executable for the sake of avoiding run-time resolutions.
Only up to C++03 supported
Code example edited
All instances are created by the library as global variables, and are not heapable.
You mean something like this, right?
static HWManager<DrierPolicy> drierManager;
static HWManager<FridgePolicy> fridgeManager;
Then, what wrong with letting the user know about them and allow her/him to use those directly like:
drierManager.doStuff();
fridgeManager.doStuff();
And then...
Because I'm interfacing HW, each instantiation of my HWManagers with different policies will be unique
Then why implement the doStuff method as instance ones? Aren't some static methods good enough?
(those are questions, not critiques. Yes, I know, this is hardly an answer - it may be one though - but I needed the extra formatting that the comments do not provide)
I am writing a distributed programming framework and I have reached a wall on what it comes to templated object declaration and creation on client side. The problem is that I have a object that I need to create in the client side of the network. Somewhere in the client I have:
At Server Side:
template <typename T>
class myRemoteObject{
myRemoteObject<T>(){
// tells client to create an object of type T
sendCreateObject( encodeType(T) ); // This is working
}
};
int main(){
...
myRemoteObject obj;
...
}
At the client side:
case (message.type){
OBJ_TYPE_INT:
objPtr = new myObject<int>();
break;
OBJ_TYPE_FLOAT:
objPtr = new myObject<float>();
break;
}
That brings me lots of problems. First, it is not flexible because I have to explicitly declare every type I use inside my framework statically, if I want to also use containers (vector etc) I also would have to explicetly instantiate them.
Second, it is very slow to compile. myObject has a lot of templated functions and compiling just 4 of those instantiations would occupy 1.5G of ram and would take a while too. I got to the point that it would occupy 6GB of RAM and take more than 1h (never finished).
So, I opted for explicit instantiation. I created several .cpp files (12) that explicetly instantiated myObject with different types, declared myObject templates in a separate file and included just the .h containig template signatures in the code cited before. Although, that sill limits the frameworks capabilities and
Anybody knows a way to do that purely as a template? So I need to instantiate only the types being used by the main program? I tried to put the instantiation of myObject inside myRemoteObject, but it didn't work...
ps.: I am using C++2011
The problem is that you are trying to instantiate templates, which are solved at compilation time, with a data type of a message that is solved in run time, too late. My only suggestion is that you use an Abstract Factory design pattern http://www.tutorialspoint.com/design_pattern/abstract_factory_pattern.htm , https://en.wikipedia.org/wiki/Abstract_factory_pattern with a getObject method. In the ConcreteFactory, in the implementation of getObject() or createObject(), you instantiate the corresponding object and return it.
Each ConcreteFactory creates an object of certain type (int, float, etc.) and returns it.
For any new type you could create a new plugin with the corresponding ConcreteFactory.
This can help you solve part of the problem.
In my company's C++ codebase I see a lot of classes defined like this:
// FooApi.h
class FooApi {
public:
virtual void someFunction() = 0;
virtual void someOtherFunction() = 0;
// etc.
};
// Foo.h
class Foo : public FooApi {
public:
virtual void someFunction();
virtual void someOtherFunction();
};
Foo is this only class that inherits from FooApi and functions that take or return pointers to Foo objects use FooApi * instead. It seems to mainly be used for singleton classes.
Is this a common, named way to write C++ code? And what is the point in it? I don't see how having a separate, pure abstract class that just defines the class's interface is useful.
Edit[0]: Sorry, just to clarify, there is only one class deriving from FooApi and no intention to add others later.
Edit[1]: I understand the point of abstraction and inheritance in general but not this particular usage of inheritance.
The only reason that I can see why they would do this is for encapsulation purposes. The point here is that most other code in the code-base only requires inclusion of the "FooApi.h" / "BarApi.h" / "QuxxApi.h" headers. Only the parts of the code that create Foo objects would actually need to include the "Foo.h" header (and link with the object-file containing the definition of the class' functions). And for singletons, the only place where you would normally create a Foo object is in the "Foo.cpp" file (e.g., as a local static variable within a static member function of the Foo class, or something similar).
This is similar to using forward-declarations to avoid including the header that contains the actual class declaration. But when using forward-declarations, you still need to eventually include the header in order to be able to call any of the member functions. But when using this "abstract + actual" class pattern, you don't even need to include the "Foo.h" header to be able to call the member functions of FooApi.
In other words, this pattern provides very strong encapsulation of the Foo class' implementation (and complete declaration). You get roughly the same benefits as from using the Compiler Firewall idiom. Here is another interesting read on those issues.
I don't know the name of that pattern. It is not very common compared to the other two patterns I just mentioned (compiler firewall and forward declarations). This is probably because this method has quite a bit more run-time overhead than the other two methods.
This is for if the code is later added on to. Lets say NewFoo also extends/implements FooApi. All the current infrastructure will work with both Foo and NewFoo.
It's likely that this has been done for the same reason that pImpl ("pointer to implementation idiom", sometimes called "private implementation idiom") is used - to keep private implementation details out of the header, which means common build systems like make that use file timestamps to trigger code recompilation will not rebuild client code when only implementation has changed. Instead, the object containing the new implementation can be linked against existing client object(s), and indeed if the implementation is distributed in a shared object (aka dynamic link library / DLL) the client application can pick up a changed implementation library the next time it runs (or does a dlopen() or equivalent if it's linking at run-time). As well as facilitating distribution of updated implementation, it can reduce rebuilding times allowing a faster edit/test/edit/... cycle.
The cost of this is that implementations have to be accessed through out-of-line virtual dispatch, so there's a performance hit. This is typically insignificant, but if a trivial function like a get-int-member is called millions of times in a performance critical loop it may be of interest - each call can easily be an order of magnitude slower than inlined member access.
What's the "name" for it? Well, if you say you're using an "interface" most people will get the general idea. That term's a bit vague in C++, as some people use it whenever a base class has virtual methods, others expect that the base will be abstract, lack data members and/or private member functions and/or function definitions (other than the virtual destructor's). Expectations around the term "interface" are sometimes - for better or worse - influenced by Java's language keyword, which restricts the interface class to being abstract, containing no static methods or function definitions, with all functions being public, and only const final data members.
None of the well-known Gang of Four Design Patterns correspond to the usage you cite, and while doubtless lots of people have published (web- or otherwise) corresponding "patterns", they're probably not widely enough used (with the same meaning!) to be less confusing than "interface".
FooApi is a virtual base class, it provides the interface for concrete implementations (Foo).
The point is you can implement functionality in terms of FooApi and create multiple implementations that satisfy its interface and still work with your functionality. You see some advantage when you have multiple descendants - the functionality can work with multiple implementations. One might implement a different type of Foo or for a different platform.
Re-reading my answer, I don't think I should talk about OO ever again.
For example we have code
class MyClass
{
private:
int data;
public:
int getData()
{
return data;
}
};
int main()
{
MyClass A, B, C;
return 0;
}
Since A, B and C are objects of MyClass, all have their own memory.
My question is that, are all of these objects share same memory for methods of class ( getData() in this case) or all objects have separate code segment for each object.?
Tnahks in advance....
The C++ Standard has nothing to say on the subject. If your architecture supports multiple code segments, then whether multiple segments are used is down to the implementation of the compiler and linker you are using. It's highly unlikely that any implementation would create separate segments for each class or object, however. Or indeed produce separate code for each object - methods belong to classes, not individual objects.
They usually share the same code segment.
Same.
You could be interested in knowledge of how things in C++ are implemented under the hood.
In general with classes and objects the following is how it works:
A class is a description of data and operations on that data.
An object is a specification of the type of object (the class it represents) and the values of the attributes. Because the type of the object is saved the compiler will know where to find the methods that are being called on the object. So even though a new copy of the data is created when a new object is made, the methods still are fixed.
In your example, MyClass::getData() is 'inline', so in that case the location of the instructions for each instance may well be in different locations under some circumstances.
Most compilers only truly in-line code when optimisation is enabled (and even then may choose not to do so). However, if this in-line code were defined in a header file, the compiler would necessarily generate code for each compilation unit in which the class were used, even if it were not in-lined within the compilation unit. The linker may or may not then optimise out the multiple instances of the code.
For code not defined inline all instances will generally share the same code unless the optimiser decides to inline the code; which unless the linker is very smart, will only happen when the class is instantiated and used in the same compilation unit in which it was defined.