Reputation: 5552
Do you think there will be any difference between performance/memory utilization in the following two cases? Would a compiler optimize the first piece of code to not make any difference between the two.
class VersionBase
{
public:
VersionBase(int iVer) : m_iVersion(iVer) {…};
int GetVersion() const { return m_iVersion; };
private:
const int m_iVersion;
}
class SomeVersionedDataObject : VersionBase
{
VersionedDataObject() : VersionBase(2) {…}; // Set version to whatever is the latest for the class
…
…
}
vs
class SomeVersionedDataObject
{
public:
VersionedDataObject()
int GetVersion() const { return m_iVersion; };
private:
static const int m_iVersion = 2;
}
Upvotes: 2
Views: 174
Reputation: 299790
Having myself dealt with serialization a fair bit, I settled on something different (and threw inheritance out of the window):
inline int version(SomeVersionedDataObject const&) { return 2; }
The memory footprint is equivalent to that of a static int const version
case, except that the implementation of the version
method is free to be a tad more clever (ie, you can have versions for polymorphic classes that dispatch to a virtual
method, ...).
And of course, it's quite easy to provide a default version for those objects that do not need one yet:
int version(...) { return 0; }
I prefer it to encoding information in some base classes, because I can extend any class with it without modifying the class itself.
Upvotes: 1
Reputation: 171117
A non-static class member, even if const
, has to be part of every object of the class. So the second definition will use less memory, assuming at least two instances are created.
EDIT
A solution with little memory usage and code duplicity would be as follows:
// In one header
template <int version>
class VersionBase
{
public:
int GetVersion() const { return s_version; };
private:
static const int s_version;
};
template <int version>
const int VersionBase::s_version = version;
// Anywhere, using the header above
class SomeVersionedDataObject : public VersionBase<2>
{
:::
};
Upvotes: 3