从函数 - 线程安全返回一个QString? [英] Return a QString from a function - thread safe?

查看:183
本文介绍了从函数 - 线程安全返回一个QString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Qt的新手 - 但这可能是一个非常基本的c ++问题。我有一个简单的函数返回一个QString:

I'm new to Qt - but this may be a very basic c++ issue. I have a simple function that returns a QString:

QString testclass::myfunc(int i)
{
    QString result;
    switch (i) {
    case 1: result = "one"; break;
    case 2: result = "two"; break;
    }
    return result;
}

这样安全吗? c编译器是否确保返回值保留在内存中足够长的时间以供调用函数使用? (或者这会危及内存损坏)。如果是后者,什么是正确的方式返回一个QString? (结果var必须是静态的?结果必须是testclass的成员var)

Is this safe? Does the c compiler ensure the return value stays in memory long enough to be used by the calling function? (Or does this risk memory corruption). If the latter, what is the right way to return a QString? (Does the result var have to be static? Does result have to be a member var of testclass?)

QString是否包含常量? (什么id情况3分配结果到一个随机字符串)

Does it matter that QString contains constants? (What id case 3 assigned result to a random string)

如果myfunc是一个静态方法,我想从不同的线程调用?我需要通过引用传入一个额外的Qstring,以确保每个调用者获得自己的变量(并返回void)?

What if myfunc is a static method that I want to call from different threads? Would I have to pass in an extra Qstring by reference to ensure each caller gets their own variable (and return void)?

这里是实际的功能(清理了一点) - 并注意,这个功能是静态的,如果有区别:

Here is the actual function (cleaned up a bit) - and note that this function is STATIC in case that makes a difference:

QString L::toString(const L::editions &level)
{
    QString levelStr;
    switch (level) {
        case L::one:
            levelStr = "one";
            break;
        case L::two:
            levelStr = "two";
            break;
        case L::three:
            levelStr = "thre";
            break;
        default:
            levelStr = "Internal Error";
            break;
    }
    return levelStr;
}

,但是valgrind抱怨(第121行是'levelStr =one )

and yet valgrind complains (line 121 is 'levelStr = "one";')

34 bytes in 1 blocks are definitely lost in loss record 197 of 716
  in L::toString(L::edition const&) in /mnt/lserver2/data/development/haast/src/linfo.cpp:121
  1: malloc in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so
  2: QArrayData::allocate(unsigned long, unsigned long, unsigned long, QFlags<QArrayData::AllocationOption>) in /opt/Qt/5.3/gcc_64/lib/libQt5Core.so.5.3.1
  3: QString::QString(int, Qt::Initialization) in /opt/Qt/5.3/gcc_64/lib/libQt5Core.so.5.3.1
  4: /opt/Qt/5.3/gcc_64/lib/libQt5Core.so.5.3.1
  5: QString::fromUtf8_helper(char const*, int) in /opt/Qt/5.3/gcc_64/lib/libQt5Core.so.5.3.1
  6: QString::fromUtf8(char const*, int) in <a href="file:///opt/Qt/5.3/gcc_64/include/QtCore/qstring.h:492" >/opt/Qt/5.3/gcc_64/include/QtCore/qstring.h:492</a>
  7: QString::operator=(char const*) in <a href="file:///opt/Qt/5.3/gcc_64/include/QtCore/qstring.h:609" >/opt/Qt/5.3/gcc_64/include/QtCore/qstring.h:609</a>
  8: L::toString(L::Lconst&amp;) in <a 


推荐答案

http:// qt -project.org/doc/qt-5/qstring.html#details


QString类提供了一个Unicode字符串。

The QString class provides a Unicode character string.

QString存储一个16位QChars的字符串,其中每个QChar对应
一个Unicode 4.0字符。 (代码值高于
65535的Unicode字符使用代理对存储,即两个连续的QChars。)

QString stores a string of 16-bit QChars, where each QChar corresponds one Unicode 4.0 character. (Unicode characters with code values above 65535 are stored using surrogate pairs, i.e., two consecutive QChars.)

Unicode是一种国际标准,支持大多数写
系统今天使用。它是US-ASCII(ANSI X3.4-1986)
和Latin-1(ISO 8859-1)的超集,所有US-ASCII / Latin-1字符都是
相同的代码位置。

Unicode is an international standard that supports most of the writing systems in use today. It is a superset of US-ASCII (ANSI X3.4-1986) and Latin-1 (ISO 8859-1), and all the US-ASCII/Latin-1 characters are available at the same code positions.

在后台,QString使用隐式共享(写时复制)
减少内存使用,并避免不必要的数据复制。
也有助于减少存储16位字符
而不是8位字符的内在开销。

Behind the scenes, QString uses implicit sharing (copy-on-write) to reduce memory usage and to avoid the needless copying of data. This also helps reduce the inherent overhead of storing 16-bit characters instead of 8-bit characters.

除了QString,Qt提供QByteArray类来存储
个原始字节和传统的8位\0结束的字符串。对于大多数
目的,QString是您要使用的类。它用于整个
的Qt API,Unicode支持确保您的应用程序
将很容易翻译,如果你想扩大你的应用程序的
市场在某一点上。当需要存储原始二进制数据时,以及当
内存保护至关重要(如在嵌入式系统中)时,QByteArray是
的两种主要情况。

In addition to QString, Qt also provides the QByteArray class to store raw bytes and traditional 8-bit '\0'-terminated strings. For most purposes, QString is the class you want to use. It is used throughout the Qt API, and the Unicode support ensures that your applications will be easy to translate if you want to expand your application's market at some point. The two main cases where QByteArray is appropriate are when you need to store raw binary data, and when memory conservation is critical (like in embedded systems).

基本上QString是真棒,几乎不用担心。你可以使用它在任何地方,但你喜欢。如果你经常遇到任何类型的慢速附加字符串太频繁,有一种特殊的方式使用字符串构建器,但根据我的经验,有很多其他地方需要改进之前,使QString更好。

Basically QString is awesome and almost worry free. You can use it wherever, and however you like. If you are running into any sort of slow down from appending strings too often, there is a special way to use a string builder, but in my experience, there are plenty of other places to improve before trying to make QString better.

并直接回答您的问题:

这样安全吗? c编译器是否确保返回值保留在内存中足够长的时间以供调用函数使用? (或者这会危及内存损坏)。如果是后者,什么是正确的方式返回一个QString? (结果var必须是静态的?结果必须是testclass的成员var?)

Is this safe? Does the c compiler ensure the return value stays in memory long enough to be used by the calling function? (Or does this risk memory corruption). If the latter, what is the right way to return a QString? (Does the result var have to be static? Does result have to be a member var of testclass?)

在上面提到的所有上述情况下,它是安全的。共享指针等保存在内存中,只要任何函数具有QString的句柄。一旦它完全超出范围,它会自动清理。

In all of the above cases mentioned above, it is safe. Shared pointers and the like keep it in memory as long as any function has a handle to the QString. Once it goes completely out of scope, it will clean itself up.

QString是否包含常量? (什么id情况3分配结果到一个随机字符串)

Does it matter that QString contains constants? (What id case 3 assigned result to a random string)

不,没关系。

如果myfunc是一个静态方法,我想从不同的线程调用怎么办?我必须通过引用传递一个额外的Qstring,以确保每个调用者获得自己的变量(并返回void)?

What if myfunc is a static method that I want to call from different threads? Would I have to pass in an extra Qstring by reference to ensure each caller gets their own variable (and return void)?

你应该用交叉线程保护,作为 QMutexLocker

You should wrap it with cross thread protection, such as a QMutexLocker.

更新:QMutexLocker示例

UPDATE: QMutexLocker example

// In your constructor

m_mutex = new QMutex();


// When accessing a shared element across threads

{
    QMutexLocker locker(m_mutex);
    // Accessing a variable is now threadsafe!
    m_sharedDataString += "!";
}

希望有帮助。

这篇关于从函数 - 线程安全返回一个QString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆