拦截C ++隐式副本构造函数,或调用其功能

tru7

鉴于:

class Foo {

private:
    static int cntFoos;

    //... stuff...

public:
     Foo() { cntFoos++; }
     ~Foo() { cntFoos--; }
};

...其中“东西”可以是任何属性集。(想法是要有一个该类实例的计数器)

然后:

Foo aFoo;
Foo twoFoo=aFoo;

将调用自动复制构造函数,因此我会错过计算这一点的机会。

有没有办法使该计数器反映自动创建的新实例?如果实现显式复制构造函数,则必须一一分配所有属性。但是,我想要一个浅的,按成员复制的副本。我不需要执行深层复制,因此实现显式复制构造函数似乎很多不必要的工作。

乔希·凯利

由于您想要大多数成员的默认行为,并且只需要对一个(静态)成员进行特殊处理,为什么不将这种特殊处理封装在其自己的类中并使其成为该类的成员变量呢?像这样:

template<typename T>
class InstanceCounter
{
public:
  static int Count;

  // Automatically invoked when a class containing it is created.
  InstanceCounter() { Count++; }

  // Automatically invoked when a class containing it is destroyed.
  ~InstanceCounter() { Count--; }

  // Automatically invoked when a class containing it is copy-constructed.
  InstanceCounter(const InstanceCounter& rhs) { Count++; }

  // No need to override operator=

  // Allow this counter to be used as an int.    
  operator int() const { return Count; }
};

template<typename T>
int InstanceCounter<T>::Count;

class Foo
{
public:
  InstanceCounter<Foo> count;
};

实施说明:

  • 我制作InstanceCounter了一个模板,以便不同的类可以轻松地拥有自己的实例数。
  • 对于C ++ 11,您还需要为提供一个move构造函数和一个move赋值运算符InstanceCounter

或者,使用CRTP习惯用法,可能更好些:

template<typename T>
class InstanceCounted
{
public:
  static int InstanceCount;

  // Automatically invoked when a class containing it is created.
  InstanceCounted() { InstanceCount++; }

  // Automatically invoked when a class containing it is destroyed.
  ~InstanceCounted() { InstanceCount--; }

  // Automatically invoked when a class containing it is copy-constructed.
  InstanceCounted(const InstanceCounted& rhs) { InstanceCount++; }

  // No need to override operator=
};

template<typename T>
int InstanceCounted<T>::InstanceCount;

class Foo : public InstanceCounted<Foo>
{
  // insert class contents here
};
// Now we can access Foo::InstanceCount.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章