C++ -- How to prevent an object from being allocating on stack?
you have a class A, where you set ctor to be private, so a client can't call
A a;
to create ob开发者_Python百科j on stack. But someday another developer adds a new ctor:
A(int)
and try to call "A a(1);" inside main(). So this will create a obj on stack. How do you prevent that?
Here is my solution but I don't know whether or not it makes sense.
Use private or protected destructor for the class A and provides a factory function to allocate the object and a function to release the resource (i.e. call destructor)
Thank you
Make the destructor private/protected. Works on the stack of a instantiation context which is not a friend or member of the corresponding class.
Once you are providing the user the source code, you are entrusting the user and allowing him to modify the code as per his requirements, but then you would not want him to change it, thats a conflict.
精彩评论