如何知道对象是静态还是动态分配在构造函数上? [英] How can I tell if an object is statically or dynamically allocated on the constructor?

查看:293
本文介绍了如何知道对象是静态还是动态分配在构造函数上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

检测动态分配的对象?


略有不同的结构,它的实例被静态或动态分配。
对象应该只有一个默认构造函数。因此,有两个构造函数,每个情况一个,并让用户明确选择正确的构造函数是不成问题。



有什么正确的方法来实现这个? / p>

这就是我现在这样做的方法:
我重载该对象的new运算符,malloc的内存,并使用返回的指针作为指针(尚未初始化)实例,并将对象的特定数据成员设置为某个magic-value。
然后,在consutrctor中,我检查成员的值。如果是magic-value,那么对象是99.9%的动态分配。



这种方法对于我来说在relase和debug模式下还没有失败,看起来像一个可怕的黑客。

解决方案

你应该能够实现你想要的,而留下一个用户可访问的默认构造函数它将用于静态和自动对象 - 你似乎忽略自动对象的存在,例如局部变量,所以我想你想要对待这些情况相同)。



使运算符新和一个单独的构造函数private,并创建一个公共静态方法(这是一个工厂方法设计模式)只有一个返回新的TheClass(123); (假设单独的构造函数采取例如一个整数,但当然你可以选择任何类型的参数,因为参数没有被使用)。



你知道你说的对象应该有一个构造函数,但从用户的角度来看,行为,并且在用户部分没有显式选择构造函数(他不能显式地调用 new ,但必须通过提供的工厂方法,就是这样)。


Possible Duplicate:
Detect dynamically allocated object?

I have an object that requires a slightly different construction wether it's instance is staticly or dynamically allocated. The object should only have a single default constructor. So having two constructors, one for each case, and having the user explicitly select the proper constructor is out of the question.

Is there any proper way to acheive this?

That's how I do this at the moment: I overload the new operator for that object, malloc the memory, and use the returned pointer as a pointer to the (yet un-initialized) instance, and set a specific data member of the object to some magic-value. Then, within the consutrctor, I check the value of the member. If it's the magic-value, then the object is 99.9% dynamically allocated.

This method haven't yet failed for me under either relase and debug modes, however, it seems like a terrible hack.

解决方案

You should be able to achieve what you want while leaving a single user-accessible default constructor (which will be used for static and auto objects -- you appear to ignore the existence of auto objects, e.g. local variables, so I imagine you want to treat these cases the same).

Make operator new and a separate constructor both private, and make a public static method (it's a case of the "factory method" design pattern) which only does a return new TheClass(123); (assuming the separate constructor takes for example an integer, but of course you can pick any type of argument you want, as the argument isn't used anyway).

You know you said the object should have a single constructor, but from the user's point of view that's exactly of the class is behaving, and there's no "explicit selection of constructor" on the user's part (he just can't call new explicitly but must go through your supplied factory method, that's all).

这篇关于如何知道对象是静态还是动态分配在构造函数上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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