首页 > 解决方案 > 从类返回 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"){}

这两个都分配一个全新的字符串吗?

标签: c++stringmemory-management

解决方案


对于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::vectorstd::vector&使用比较运算符,则不分配。

编辑:正如 Evg 指出的那样,运算符==有一个需要 astd::string和 a的重载const char*。如果它不存在,bla.GetStr() == "abc"则必须构造并分配一个新字符串,"abc"以便能够比较两者。


推荐阅读