【发布时间】:2015-01-16 11:32:47
【问题描述】:
在以下程序中:
#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”能够在范围变化中持续存在(因为this),并且我希望成员指针 m_pstr 也可以继续指向该字符串文字范围的变化。有人能启发我吗?
【问题讨论】:
-
const char[6]类型的字符串文字仍然存在,但隐式转换的右值std::string不存在
标签: c++ stl stdstring string-literals