2

您认为以下两种情况下的性能/内存利用率会有什么不同吗?编译器是否会优化第一段代码以使两者之间没有任何区别。

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
    …
    …
}

对比

class SomeVersionedDataObject
{
public: 
    VersionedDataObject()
    int GetVersion() const { return m_iVersion; };
private:
    static const int m_iVersion = 2;
}
4

2 回答 2

3

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>
{
  :::
};
于 2013-06-18T07:13:38.597 回答
1

在自己处理了一些序列化之后,我选择了一些不同的东西(并将继承扔出窗外):

inline int version(SomeVersionedDataObject const&) { return 2; }

内存占用相当于一个static int const version案例的内存占用,除了version方法的实现可以自由一点更聪明(即,您可以拥有分派给virtual方法的多态类的版本,...)。

当然,为那些还不需要的对象提供默认版本非常容易:

int version(...) { return 0; }

我更喜欢它而不是在某些基类中编码信息,因为我可以用它扩展任何类而无需修改类本身

于 2013-06-18T10:40:08.143 回答