考虑到一些函数是const而另一些函数是非const, QString的正确使用/修改
Proper usage/modification of QString given that some functions are const and others non-const
我正在对QString执行一些操作以减少它,但我不想影响原始字符串。我是Qt的新手,我对使用各种QString函数的正确方法感到困惑,因为有些是const,而有些则不是。到目前为止,这是我所拥有的:
// this needs to be const so it doesn't get modified.
// code later on is depending on this QString being unchanged
const QString string = getString();
我需要调用的方法是QString::simplified()
、QString::remove()
和QString::trimmed()
。令人困惑的部分是什么是正确的方法来做到这一点,simplified()
和trimmed()
是const
,但remove()
不是。请记住,我要复制原件并直接对副本进行修改,这是我的:
// simplified() is a const function but no problem because I want a copy of it
QString copy = string.simplified();
// remove is non-const so it operates on the handle object, which is what I want
copy.remove( "foo:", Qt::CaseInsensitive );
// trimmed() is const, but I want it to affect the original
copy = copy.trimmed();
使用copy = copy.trimmed()
是处理这种情况的正确方法吗?这将实现我的目标,让copy被修剪()为下一次使用吗?有没有更好的(更优雅、更高效、更英伦的)方法来做到这一点?
我已经检查了QString Qt文档,无法令人满意地回答这些问题。
我认为答案很简单,因为优化的原因。
在幕后,
QString
使用隐式共享(写时复制)来减少内存使用并避免不必要的数据复制。这也有助于减少存储16位字符而不是8位字符的固有开销。
通常,当它们返回对修改字符串的引用以获得最终结果时,我会添加一些不同的参数。(更优雅的方式…)
例如:QString str = " Hello Worldn!";
QString str2 = str.toLower().trimmed().simplified();
if(str2.contains("world !"))
{
qDebug() << str2 << "contains "world !"";
}
这里有更多关于隐式共享的信息:
http://qt project.org/doc/qt - 4.8 -/-隐式- sharing.html
希望对你有帮助。
相关文章:
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 从函数返回const char*数组
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 在 const 函数中通过引用和指针返回之间的区别
- 使用 std::string () const 函数启动线程或未来
- 在运算符重载定义中使用成员函数(const错误)
- 使用共享指针的函数调用,其对象应为 const
- 将函数参数"const char*"转换为"std::string_view"是
- 为什么返回类型的'const'限定符对标有 __forceinline/内联的函数没有影响?
- 使用按引用调用时,不能在没有对象的情况下调用成员函数 const
- 在呼叫运算符函数const中调用运算符时错误
- 我需要用c ++ 98重写c ++ 11代码,c ++ 11正在使用lambda函数[&](const Output & o
- 函数 const 本地对象在C++会发生什么
- int const函数(参数)、int函数(const参数)和int函数(parameters)const之间的区别是什
- const_cast为函数const设置规则并破坏规则
- 构造函数"const variables"设置的用于表示C++数组的边界?
- 将char**传递给C++中的函数(const char**)
- 复制构造函数const char*和Shared_ptr
- 使函数"const"的意图是什么
- c++嵌套映射不匹配成员函数const成员