holding a resource is a class invariante 在 RAII 中是什么意思?
What does holding a resource is a class invariante mean in RAII?
持有资源是 RAII 中的 class 不变性是什么意思?
在 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 language
为例,我们可以很容易地理解Class Invariant
是什么意思:
class Date {
int day;
int hour;
invariant() {
assert(1 <= day && day <= 31);
assert(0 <= hour && hour < 24);
}
}
这是一个约束,指的是class字段可以保持在有效状态。但是,持有资源意味着什么?这是否意味着该资源是我的,并且从构造函数构建到它被 de destrutor 销毁都是我的?
Does it mean the resource is mine and will be mine from its construction by the constructor, until its destruction by de destrutor
在正确设计的程序中确实如此,但所有权的概念在 C++ 中并未强制执行。
很容易 "shoot yourself in the foot" 并将资源提供给其他对象。例如,当资源是一个指针时,你可以不小心在对象之间共享它,像这样:
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;
}
持有资源是 RAII 中的 class 不变性是什么意思?
在 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 language
为例,我们可以很容易地理解Class Invariant
是什么意思:
class Date {
int day;
int hour;
invariant() {
assert(1 <= day && day <= 31);
assert(0 <= hour && hour < 24);
}
}
这是一个约束,指的是class字段可以保持在有效状态。但是,持有资源意味着什么?这是否意味着该资源是我的,并且从构造函数构建到它被 de destrutor 销毁都是我的?
Does it mean the resource is mine and will be mine from its construction by the constructor, until its destruction by de destrutor
在正确设计的程序中确实如此,但所有权的概念在 C++ 中并未强制执行。
很容易 "shoot yourself in the foot" 并将资源提供给其他对象。例如,当资源是一个指针时,你可以不小心在对象之间共享它,像这样:
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;
}