在下面的程序中:
#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;
}
函数ProcessEvent()中的断言失败了,我不知道为什么。我希望作为参数传递给fq.Enqueue()的字符串文字“Hello”可以通过作用域的变化而持久存在(因为这个),并且我希望成员指针m_pstr也可以在作用域的变化中继续指向该字符串文字。有人能给我解释一下吗?
const char[6]
的字符串字面量可以存活,但隐式转换的右值std::string
无法存活。 - PeterT