Automatic counter for derived class / Alternative? - c++

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.

Related

Best practice for handling const class data

Say you have a certain class in which each instance of it needs to access the exact same set of data. It is more efficient to declare the data outside the class rather than have each instance make its own one, but doesn't this breach the 'no globals' rule?
Example code:
Foo.h
class Foo{
Foo();
void someFunction();
};
Foo.cpp
#include "Foo.h"
//surely ok since it's only global to the class's .cpp?
const int g_data[length] = {
//contains some data
};
Foo::someFunction(){
//do something involving g_data ..
}
..rather than making 'g_data' a member variable. Or is there some other way which avoids creating a global?
Use the modifier static which modifies the declaration of a class member so that is shared among all class instances. An example:
class A {
int length = 10;
static int g_data[length]; //Inside the class
}
And then you can access it like this:
int main(void) {
std::cout << "For example: " << A::g_data[2] << std::endl;
}
You can find more on this matter here
That's what a static member is for.
Thus you will have in your declaration :
class Foo{
Foo();
void someFunction();
static int const sharedData[length];
};
And somewhere in your cpp file :
int const Foo::sharedData[length] = { /* Your data */ };
Summarily, yes - your "global" is probably ok (though it'd be better in an anonymous namespace, and there are a few considerations).
Details: lots of answers recommending a static class member, and that is often a good way to go, but do keep in mind that:
a static class member must be listed in the class definition, so in your case it'll be in Foo.h, and any client code that includes that header is likely to want to recompile if you edit the static member in any way even if it's private and of no possible direct relevance to them (this is most important for classes in low-level libraries with diverse client code - enterprise libraries and those shared across the internet and used by large client apps)
with a static class member, code in the header has the option of using it (in which case a recompile will be necessary and appropriate if the static member changes)
if you put the data in the .cpp file, it's best in an anonymous namespace so it doesn't have external linkage (no other objects see it or can link to it), though you have no way to encapsulate it to protect it from access by other functions later in the .cpp's translation unit (whereas a non-public static class member has such protection)
What you really want is data belonging to the type, not to an instance of that type. Fortunately, in C++ there is an instrument doing exactly that — static class members.
If you want to avoid the global and have a more object-oriented solution, take a look at the Flyweight pattern. The Boost Flyweight library has some helper infrastructure and provides a decent explanation of the concept.
Since you are talking about efficiency, it may or not be a good idea to use such an approach, depending on your actual goal. Flyweights are more about saving memory and introduce an additional layer of indirection which may impact runtime performance. The externally stored state may impact compiler optimizations, especially inlining and reduce data locality which prevents efficient caching. On the other hand, some operations which like assignment or copying can be considerably faster because there is only the pointer to the shared state that needs to be copied (plus the non-shared state, but this has to be copied anyway). As always when it comes to efficiency / performance, make sure you measure your code to compare what suits your requirements.

C++ typedef struct vs class

I am not very familiar with C++ , and while I am trying some test programms I came to a question regarding the best if I may say so way to define some primitive elements in C++ code.
Let's take a class that describes rectangles. It would create them, draw them , rotate, resize, etc... now in most cases we have to deal with points on the canvas.
The rectangle its self is described by 2 points: Upper Left and Lower Right corner.
Also in order to Rotate it, you need an angle, and a point(anchor point).
Or maybe to move it you need a new anchor point for the given rectangle. I guess I made my point in using points .
So what is more efficient ? to define this primitive point as a class or as a struct?
class cPoint
{
public:
int X;
int Y;
};
or
typedef struct
{
int X;
int Y;
}sPoint;
Niether are more efficient. On a technical level, there is no difference between a class and a struct aside from default visibility of members (public in struct, private in class) and default inheritance model (public in struct, private in class).
They typedef struct {} name model is not idiomatic in C++. In fact, it's an abomination -- a holdover from C. Don't use this model. Use this struct name {}; instead. Using the typedef struct {} name; model doesn't gain you anything in C++ (it was needed in C), and may cost you sojmething in terms of maintainability. For instance, it might be harder to grep for typedef struct declarations. But since it doesn't gain you anything by doing this, there's no compelling reason not to simply do struct name {}; in C++.
Aside from technical issues, the differences between struct and class are semantic ones. It is traditional and expected that objects declared as structs are simple objects which consist of only public: data members (so-called PODs). If it has private or protected data, is expected to be derived from, or has any methods, it is declared as a class.
This guideline is open to interpretation, and is just that -- a guideline. There is nothing to prevent you from declaring an abstract base class as a struct, for example. However you may want to consider following this guideline in order to follow the Principle of Least Surprise, making your code easier to understand and maintain.
Both are nearly equivalent. More precisely, struct { is the same as class {public:
An optimizing compiler would probably generate exactly the same code. Use MELT or simply pass -fdump-tree-all (beware, that option produces hundreds of dump files) to g++ (assuming you use a recent GCC compiler) -preferably with some optimization like -O - to find out (or look at the produced assembler code with g++ -O -fverbose-asm -S ...)
typedef struct is actually the C way to do this. In C++ the two versions would look very similar: Your class as written, and the struct as follows:
struct sPoint
{
int X;
int Y;
};
The two forms are functionally identical but you can provide your future maintainers with significant information by picking and sticking to some convention about how they're used. For example one approach is that if you intend to make the data elements private and give it useful methods (for example if you use inline accessors you can insert print calls every time the methods are used) then by all means make it a class. If you intend to have the data be public and access them as members then make it a struct.
There's no performance difference between a class and a struct
A class defaults to private access, whilst a struct defaults to public access. If interoperability with C is an issue for you then you'll have to use struct, and obviously it can't have any member functions.
As an aside, there's no std::is_struct in the standard library. Instead the std::is_class method returns true if the type is a class or a structure.
Simply put, the first way is more C++, and the second way is more C. Both work, while the first way is more 'standard' now.
A struct in C++ is like a class that would have public members by default*
There is no other formal difference, though your code would probably look confusing if you started using structs as classes, especially the inheritance mechanisms where data privacy is a major benefit.
If you are about to declare private/protected members, there is really little point in using a struct, though your code will still be 100% legal.
*including inherited members, since the zealots and nitpickers around seem to think the point is of a capital importance and only ignorant heatens would fail to mention it.
Except for the fact that this fine doctrine point is defined (or rather hinted, since the inference that base classes are simply defining inherited members is left to the sagacity of the reader) in another verse of the Stoustrup Holy Bible, there is really nothing to fuss about IMHO.
To properly declare the struct in your example, use
struct sPoint {
int X;
int Y;
};
In general, structs and classes in C++ are identical, except that data is public in a struct by default. The other difference is that the struct keyword cannot be used as the type in a template, although a struct can be used as the parameter.
There is a more thorough discussion here: C++ - struct vs. class
technically, struct{} and class{} are the same.
they differ on semantic level, with different member visibility.
struct{...} is equivalent to class{public:...}
And, it is also legal to declare a class using struct keyword. (add member functions, access specifier to struct{})
Generally, using struct for Plain-Old-Data (POD) type, class for Object-Oriented type to improve readability.
typedef struct{} should only be used to hide implementation detail(eg: supply a close-source library to users)
From my opinion, in your case, using struct is better, because Point's member need to be modified directly by other code.

A few questions about C++ classes

I have two basic questions. The first one is about function in other classes. If I have a header file with a class in it and I want to use that function in another class I have created, do I always have to construct a class object to run a function in that class like:
someclass class; <----object construction
class.somefunction();
Is there a way just to call the function with the object construction?
And the second question is it okay to put multiple small classes in one header file?
Functions should only be member functions if they act on an object of the class. Functions that don't act on an object should just be plain global functions (or class static):
// Global function
void foo() { /* do something */ }
// Static function
class Foo
{
public:
static void foo() { /* do something */ }
};
For your second question, yes it's ok. Generally people stick to one class per file, but in my opinion there's nothing wrong with having a few small classes in a single file.
If your function is declared static then you don't need an object instance to call it.
class Foo
{
public:
static void Bar() {}
};
// ...later
Foo::Bar();
To answer your second question, yes it's sometimes ok. I've done that before with small utility structs that are related to each other. Usually I'm just being lazy and don't want to bother making separate files.
Is there a way just to call the function with the object construction?
Only if the function is declared static. (ok, that's a lie, its possible without constucting a object if you subvert the type system, but it's not a good idea)
And the second question is it okay to put multiple small classes in one header file?
Sure, it's done all of the time.
1 static as already mentioned
2 do what feels natural. Keep related classes together. One of the problems with JAva is its fanatical enforcement of one class per file
However - unforgivable sin is spreading the implementation of class a throughout the implementations of classes b c and d
Ie all of a class implementation should be in one .cpp file.
delcare the function as static.
Are you talking about inner classes? If thats the case, then its totally legit.

Objects of a class share same code segment for methods?

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.

Multiple Singleton Instances

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?