离开作用域时,为什么指向字符串文字的外部指针会丢失?(C++)

sif*_*man 3 c++ stl string-literals

在以下程序中:

#include <string>
#include <deque>
#include <assert.h>

struct Foo {
    // member var
    const std::string *m_pstr;

    // ctor
    Foo (const std::string *pS) : m_pstr (pS) {}

    // copy ctor
    Foo (const Foo& other) : m_pstr (other.m_pstr) {}

    // swap
    void swap (Foo &other) { std::swap (m_pstr, other.m_pstr); }

    // assignment operator
    Foo& operator=(Foo tmp)
    {
        this->swap (tmp);
        return *this;
    }

    // dtor
    ~Foo () {}
};


struct FooQueue {
    // member var
    std::deque<Foo> m_q;

    void Enqueue (const Foo &f)
    {
        m_q.push_back (f);
        assert (*(m_q.front().m_pstr) == std::string("Hello")); // This Passes
    }

    void Enqueue (const std::string &s)
    {
        Foo f (&s);
        Enqueue (f);
        assert (*(m_q.front().m_pstr) == std::string("Hello")); // This Passes
    }
};


void ProcessEvent (FooQueue &fq)
{
    fq.Enqueue ("Hello");
    assert (*(fq.m_q.front().m_pstr) == std::string("Hello"));  // This Fails
}


int main (int argc, char* argv[])
{
    FooQueue fq;
    ProcessEvent (fq);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

函数ProcessEvent()中的断言失败了,我不知道为什么.我希望fq.Enqueue()参数中的字符串文字"Hello"能够通过范围内的更改来保持(因为这样),我希望成员指针m_pstr也可以通过更改继续指向该字符串文字.范围.有人可以开导我吗?

rav*_*avi 5

在这种情况下,将构造一个临时字符串对象来存储"Hello".然后这个临时绑定到字符串对象s.

void Enqueue (const std::string &s)
Run Code Online (Sandbox Code Playgroud)

这意味着临时的生命周期延长到字符串s的范围.但是当此函数退出时,s将被销毁.

所以,在ProcessEvent那个字符串早已消失.