有没有办法判断我们是否在构造函数中被调用?
Is there a way to tell if we're being called inside a constructor?
我想创建一个非静态方法,只有类的同一实例(或其子类之一)的构造函数才能调用。除了面向密钥的访问保护模式之外,还有什么优雅的方法可以做到这一点吗?
class MyClass
{
public:
void foo()
{
assert(foo was called from the constructor); //how?!
if (some condition or other)
throw ExceptionThatOnlyClientsThatConstructTheObjectCanHandle(); //hence my requirement
}
};
class MySubClass : public MyClass
{
public:
MySubClass()
{
blah(); //correct use of foo() through blah()
foo(); //correct use of foo() directly
}
void blah() { foo(); } //correctness depends on who called blah()
};
int main()
{
MySubClass m;
m.foo(); // incorrect use of foo()
m.blah(); // incorrect use of foo() through blah()
return 0;
}
编辑:请看我下面的评论,但我认为这要么是(1)面向传递密钥的访问控制的特殊情况,要么是(2)确保异常得到处理的特殊情况。看到这样,构造函数的事情就是转移注意力。
否。如果没有其他变量告诉你,这是不可能的。你能做的最好的事情是让方法private
,这样只有你的类才能调用它。然后确保只有构造函数调用它。除此之外,你只想让构造函数调用它,你有没有尝试过不使用函数,只把代码放在那里?
相关文章:
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 确保所有构造函数调用相同的函数 c++ 设计模式
- 减少复制构造函数调用
- 使用回调函数从构造函数调用虚拟/派生方法的替代方法?
- 在 Google 测试中,我可以从构造函数调用 GetParam() 吗?
- C++ - 从另一个类构造函数调用类构造函数
- 在C++中初始化带有和不使用构造函数调用的对象有什么区别
- 是否可以从移动构造函数调用默认构造函数?
- 在模板生成器模式中分解重复的构造函数调用
- std::atexit 从全局对象的构造函数调用时的排序
- 对构造函数调用的约束
- 编译器错过了无效的构造函数调用,并调用不存在的(或私有的)默认构造函数
- 用构造函数调用填充向量
- 创建指针时是否没有构造函数调用
- 使用 emplace_back 避免移动构造函数调用的最佳方法?
- C++ 抽象类构造函数调用
- 为什么函数参数将带有参数的构造函数调用
- 为什么比“构造函数”调用更多的“解构器”调用
- 将对象传递给函数并不是导致构造函数调用