我怎么知道是否调用了方法,但是很早?
例如,我有一个Foo结构,它具有一些可配置的成员:
struct Foo {
int a;
int b;
Foo& setA(int a) {
this->a = a;
return *this;
}
Foo& setB(int b) {
this->b = b;
return *this;
}
};
现在,我有一个返回Foo的函数,如果没有对成员函数的进一步调用,则应立即使用它。例如:
Foo getFoo() {
static Foo foo;
// <-- Here, I want to call some useFoo(foo) if no member functions are called
return foo;
}
// This function is used like this:
getFoo().setA(3);
^-- here, we call setA so don't useFoo now
getFoo();
^-- but here, I want useFoo to be called automatically
最佳答案
您在问题中提出的建议实际上是不可能的。这会打破因果关系:如果在返回并可能使用它之前没有调用任何成员函数,则无法调用useFoo
,因为返回后可以使用某些成员函数。
您可以做的是,如果未设置标志,则从useFoo
的析构函数中调用Foo
,然后在每个成员函数调用上设置该标志。但是,您需要注意如何处理副本/移动!
关于c++ - C++知道是否调用了成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63219069/