Why is the external pointer to a string literal lost when it goes out of scope? (C ++)
In the following program:
#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;
}
the assertion inside the ProcessEvent () function fails and I don't know why. I would expect the string literal "Hello" in the fq.Enqueue () argument to persist across changes in scope (because of this ), and I would expect the pointer member m_pstr to continue to point to this string literal as well through changes in scope. Can someone enlighten me?
source to share
In this case, a temporary string object will be created to store "Hello". And then this temporary limitation is related to the string object s.
void Enqueue (const std::string &s)
This means that the lifetime of the temporary extension extends to the region of the string s. When, when this function exits, s will be destroyed.
So, ProcessEvent
this line has long passed.
source to share