我们如何防止实例化一个类 [英] How can we prevent instantiation a class

查看:53
本文介绍了我们如何防止实例化一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨伙计,



帮助我找到一种方法来避免在堆栈上实例化c ++类,但可以在堆上实例化。



问候,

Vikas

Hi Folks,

Help me to find a way to avoid instantiation of a c++ class on stack but can be instantiated on heap.

Regards,
Vikas

推荐答案

参考此讨论

< a href =http://stackoverflow.com/questions/4735778/preventing-classes-from-being-instantiated-on-the-stack-or-as-data-member> http://stackoverflow.com/questions / 4735778 / prevent-classes-from-being-as-stack-on-the-stack-or-as-data-member



可能是对你有用。
Refer this discussion
http://stackoverflow.com/questions/4735778/preventing-classes-from-being-instantiated-on-the-stack-or-as-data-member

may be it is useful for you.


你可以使用 Singleton Pattern&它用C ++实现 [ ^ ]。


可以通过将构造函数设为私有来实现该功能。您仍然需要一个静态函数来获取堆分配的句柄。这就是我通常的做法(你要求的行为相同)



PS 这不是完整的代码,只是半生不熟的解决方案告诉你方向。

The functionality can be achieved by making the constructor private. You will still need a static function to get the heap allocated handle. This is how i usually do it (the same behavior you asked for)

P.S. this is not complete code, just half baked solution to show you the direction.
#include <iostream>

using namespace std;

class A
{
private:
	A()
	{

	}
	
public:

	static A* CreateAndGetInstancePointer()
	{
		return new A();
	}

	int test()
	{
		return 2;
	}

};

int _tmain(int argc, _TCHAR* argv[])
{
	// This will give compile time error
	//A a;
	
	//cout << a.test();

	A *pa = A::CreateAndGetInstancePointer();
	
	cout << pa->test();
	
	return 0;
}

</iostream>


这篇关于我们如何防止实例化一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆