Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

c++ - Returned std::string by value - why does the internal buffer point to existing memory?

class StringPool
{
public:
    explicit StringPool(size_t reserve = 0);
    std::string Pool(const std::string& str);

private:
    std::vector<std::string> m_pool;
};

StringPool::StringPool(size_t reserve)
{
    if (reserve > 0)
        m_pool.reserve(reserve);
}

std::string StringPool::Pool(const std::string& str)
{
    if (str.empty())
        return std::string();

    auto it = std::find(m_pool.begin(), m_pool.end(), str);
    if (it != m_pool.end())
        return *it;
    m_pool.push_back(str);
    return str;
};

int main()
{
    StringPool spool;   
    std::string tmp;
    spool.Pool("HELLO");
    spool.Pool("WORLD");
    tmp = spool.Pool("HELLO");
}

Why does the internal buffer of tmp have the same address of the returned element? Is tmps internal buffer just simply assigned to the pointer of the returned value due to RVO?

I'm unsure of what language mechanisms facilitate this assignment.

question from:https://stackoverflow.com/questions/65915206/returned-stdstring-by-value-why-does-the-internal-buffer-point-to-existing-m

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why does the internal buffer of tmp have the same address of the returned element?

I assume that by returned "element", you mean the internal buffer of the returned string object.

It is unclear whether you refer to the internal address of tmp before the assignment or after the assignment. In practice, the address typically remains the same in this case, and thus the address would not be the same as the address of the returned string's buffer.

The move assignment could change tmp to have the internal address of the returned string. In practice, this won't happen unless the string is long enough to exceed the short string optimisation.

As for why: Because that's how the move assignment of std::string was implemented by your standard library.

just simply assigned to the pointer of the returned value due to RVO?

There may indeed be RVO on the line return std::string();. RVO has no effect on the internal address of tmp.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...