假设你写了一个 A 类,构造函数是私有(private)的(以防止其他人在堆栈上创建它),然后有一天另一个开发人员添加了一个新的构造函数,比如 A(int),并想在 main() 中使用:
一个(1)
在堆栈上创建它。你如何防止这种情况发生?
我的解决方案:
声明一个公共(public)构造函数
A(void& input )
{
Cerr << “please do not create it on stack” << endl ;
exit(1);
}
我不确定它是否正确?
谢谢
最佳答案
正如其他人所说,您不能阻止可以编辑您的类(class)的人让它做几乎任何事情......但是......
...如果您想要一个比注释更易于编译器执行的方法,您可以继承一个没有默认构造函数的类。任何编写构造函数的人(希望)都会注意到它。您可以通过它的名字来提示人们采取某些预防措施。
像这样:
class DoNotStackConstruct {
protected:
DoNotStackConstruct(const char* dummy) {}
};
class A : protected DoNotStackConstruct {
private:
A () : DoNotStackConstruct ("PLEASE make all A constructors private!") {
// your code here
}
public:
static std::tr1::shared_ptr<A> newA() {
return std::tr1::shared_ptr<A>(new A);
}
/* ... a bunch of code ... */
/* ... then someone later adds the following ... */
public:
A (int i) {
// can't force them to make it private, but...
// this won't compile without mentioning DoNotStackConstruct
}
};
一旦你开始使用 C++11 就会有“委派构造函数”,这个技巧会少一些 dentry :
Can I call a constructor from another constructor (do constructor chaining) in C++?
然后他们将能够委托(delegate)给 A()
而无需访问源代码行并复制“嘿,不要让你的构造函数公开!”文本。但默认情况下,他们在第一次尝试时仍会遇到编译器错误。
关于c++ - 如何防止其他人在堆栈上创建您的类的新实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7910517/