QString 的生命周期问题
我有一个这样的类:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一切都好。当您销毁临时 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.
你的代码没问题。事件的顺序是:
Your code is ok. The sequence of events is: