QString 的生命周期问题

发布于 2024-11-19 05:30:42 字数 490 浏览 7 评论 0原文

我有一个这样的类:

class SomeClass {
    public:
        QString data;
        SomeClass(const QString &);
};

在 .cpp 文件中:

SomeClass::SomeClass(const QString &_data) {
    data = _data;
}

然后我像这样使用它:

SomeClass c("foobar");

这将调用 QString("foobar") 并将其传递给 SomeClass 的构造函数。但是这个 QString 是一个自动对象,因此它的生命周期将在构造函数之后消失。另一方面,除非修改,否则data不会被复制(据我了解Qt文档)。这段代码是否可能存在终身问题,或者我错了?怎样设计比较好呢?

I have a class like this:

class SomeClass {
    public:
        QString data;
        SomeClass(const QString &);
};

and in the .cpp file:

SomeClass::SomeClass(const QString &_data) {
    data = _data;
}

then I use it like this:

SomeClass c("foobar");

This will call QString("foobar") and will pass it to the constructor of the SomeClass. But this QString is an automatic object so its lifetime will be gone after the constructor. On the other hand data won't be copied(as far as I understand Qt docs) unless modified. Is it possible to have lifetime issues with this code or am I wrong? How to design it better?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情何以堪。 2024-11-26 05:30:42

一切都好。当您销毁临时 QString 数据时,数据会被修改,因此将执行复制。数据修改意味着它将在任何一侧进行修改,无论是引用数据的字符串还是包含数据的字符串。

All is OK. When you destroy your temporary QString data is modified, so copy would be performed. Data modification means that it will be modified at any side, in string that references data or in string that contains data.

画尸师 2024-11-26 05:30:42

你的代码没问题。事件的顺序是:

  1. 当您将 const char* "foobar" 传递给构造函数时,会创建一个临时 QString(让我们称之为 xx),
  2. 数据会被分配到该字符串,即 data 和 xx 都引用现在有一个字符串主体2 xx 的引用计数
  3. 超出范围,字符串主体的引用计数变为 1,并且数据仍然引用该主体。

Your code is ok. The sequence of events is:

  1. a temporary QString (let us call it xx) is created when you pass the const char* "foobar" to the constructor
  2. data is assigned that string, i.e. both data and xx reference the string body which now has a ref count of 2
  3. xx goes out of scope, the ref count of the string body goes to 1 and data still references this body.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文