c++ - 从类返回 std::string 是否分配内存?
问题描述
从类中返回 a std::string
(以及就此而言,std::vector
)是否分配内存?
如果我有这门课:
class Bla
{
public:
Bla();
const std::string& GetStr() const
{
return m_Str;
}
private:
std::string m_Str;
};
我有一些这样的代码:
std::string currentString = Bla.GetStr();
if (Bla.GetStr() == "abc"){}
这两个都分配一个全新的字符串吗?
解决方案
对于std::string
:
#include <string>
class Bla
{
public:
Bla() {}
const std::string& GetStr() const
{
return m_Str;
}
private:
std::string m_Str = "Hi";
};
int main() {
Bla bla;
std::string currentString = bla.GetStr(); //1. will allocate new string
const std::string& secondString = bla.GetStr(); //2. will be a const reference to m_Str
if (bla.GetStr() == "abc") {} //3. will be a const reference to m_str, and therefore not another allocated string
}
如果将GetStr()
const 引用的结果分配给普通的std::string
,例如1.
,则将分配字符串。
如果将 const 引用的结果分配GetStr()
给另一个 const 引用,例如2.
,它们将引用同一个对象,即m_Str
.
如果将GetStr()
const 引用的结果与另一个字符串或字符串文字(如3.
)进行比较,则不会分配字符串,并且将与引用的对象进行比较,在这种情况下m_Str
与另一个字符串进行比较,在这种情况下是一个const char[]
(又名字符串文字)。(这里比较的是“abc”)。
m_Str
但是,将被分配。
对于std::vector
:
如果返回 的函数的结果std::vector&
被分配给一个普通的std::vector
(不是一个引用),它被分配。
如果返回 的函数的结果std::vector&
被分配给另一个对向量的引用,那么它将不会被分配。
如果返回 的函数的结果std::vector&
与另一个比较std::vector
或std::vector&
使用比较运算符,则不分配。
编辑:正如 Evg 指出的那样,运算符==
有一个需要 astd::string
和 a的重载const char*
。如果它不存在,bla.GetStr() == "abc"
则必须构造并分配一个新字符串,"abc"
以便能够比较两者。
推荐阅读
- archunit - ArchUnit 在检查传入访问时不排除测试类
- security - 使用 SSR Nuxt 时如何拨打私人电话?
- django - 按映射键过滤嵌套列表
- c# - 为什么调试时VS中总有一个工作线程没有名字?
- c# - 使用 C# 创建 Instagram 帐户
- android - 尝试使用 /kittinunf/fuel lib 从 android ver 9 及更低版本访问 tls 1.3 站点
- nopcommerce - 如何在 NopCommerce 4.40.3 中删除标签
- django - django-单击href链接会将我重定向到索引页面而不是指向的网页
- jquery - 如何修复停止 DIVI 编辑屏幕 DIVI 编辑器工作的 jQuery 错误
- mongodb - 如何对数组中的特定数组求和?