c++ - 在 RAII 中,持有资源是类不变性意味着什么?

标签 c++ raii invariants

持有资源是 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);
  }
}

这是一个约束,指的是类字段可以保留什么来被视为有效状态。然而,持有资源意味着什么?这是否意味着该资源是我的,并且从构造函数构建到析构函数销毁为止都是我的?

最佳答案

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;
}

参见https://rmf.io/cxx11/rule-of-zero零规则

关于c++ - 在 RAII 中,持有资源是类不变性意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42358121/

相关文章:

c++ - 创建RAII类时应如何处理错误?

opengl-es - 什么是 OpenGL 着色器语言中的不变量变化

c# - DDD - 如何强制执行不变量但特定于客户要求?

C++读取缓冲区中的整个文件

c++ - 关于资源管理器类的 RAII 问题

C++:setsockopt() 可以被信号忽略吗?

c++ - 从 std::map 中的 vector 获取数据

c++ - 具有强异常保证的同步 STL 容器插入

c++ - 尝试在 C++ 中将两个动态创建的矩阵(2d vector )相乘

c++ - 如何将按键事件发送到 QWebElement?