Can I stop people deriving from my class?

本文探讨了C++中虚函数调用的实际效率,并解释了为何通常无需担心其带来的性能开销。此外,还介绍了一种防止类被继承的方法,以确保对象复制的安全性。

Yes, but why do you want to? There are two common answers:

  • for efficiency: to avoid my function calls being virtual
  • for safety: to ensure that my class is not used as a base class (for example, to be sure that I can copy objects without fear of slicing)
In my experience, the efficiency reason is usually misplaced fear. In C++, virtual function calls are so fast that their real-world use for a class designed with virtual functions does not to produce measurable run-time overheads compared to alternative solutions using ordinary function calls. Note that the virtual function call mechanism is typically used only when calling through a pointer or a reference. When calling a function directly for a named object, the virtual function class overhead is easily optimized away.

If there is a genuine need for "capping" a class hierarchy to avoid virtual function calls, one might ask why those functions are virtual in the first place. I have seen examples where performance-critical functions had been made virtual for no good reason, just because "that's the way we usually do it".

The other variant of this problem, how to prevent derivation for logical reasons, has a solution. Unfortunately, that solution is not pretty. It relies on the fact that the most derived class in a hierarchy must construct a virtual base. For example:

	class Usable;

	class Usable_lock {
		friend class Usable;
	private:
		Usable_lock() {}
		Usable_lock(const Usable_lock&) {}
	};

	class Usable : public virtual Usable_lock {
		// ...
	public:
		Usable();
		Usable(char*);
		// ...
	};

	Usable a;

	class DD : public Usable { };

	DD dd;  // error: DD::DD() cannot access
        	// Usable_lock::Usable_lock(): private  member
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值