持有资源是 RAII 中的类不变性是什么意思?
关于RAII's Wikipedia page它确实指出:
In RAII, holding a resource is a class invariant, and is tied to object lifetime: resource allocation (acquisition) is done during object creation (specifically initialization), by the constructor, while resource deallocation (release) is done during object destruction (specifically finalization), by the destructor.
在D语言
示例中,我们可以轻松理解类不变
的含义:
class Date {
int day;
int hour;
invariant() {
assert(1 <= day && day <= 31);
assert(0 <= hour && hour < 24);
}
}
这是一个约束,指的是类字段可以保留什么来被视为有效状态。然而,持有资源意味着什么?这是否意味着该资源是我的,并且从构造函数构建到析构函数销毁为止都是我的?
最佳答案
block 引用>Does it mean the resource is mine and will be mine from its construction by the constructor, until its destruction by de destrutor
在正确设计的程序中,情况确实如此,但 C++ 中并未强制执行所有权概念。
很容易“搬起石头砸自己的脚”并将资源交给其他对象。例如,当资源是指针时,您可能会意外地在对象之间共享它,如下所示:
struct A { int some_variable; }; struct A_holder { A* ptr; A_holder() { ptr = new A(); } ~A_holder() { delete ptr; } }; int main() { { A_holder a_holder; auto another_A_holder = a_holder; } //error because delete is called twice: //first on A_holder's pointer and a second time on another_A_holder's pointer return 0; }
关于c++ - 在 RAII 中,持有资源是类不变性意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42358121/