【问题标题】:Why is an external pointer to a string literal lost when leaving scope? (C++)为什么离开范围时指向字符串文字的外部指针会丢失? (C++)
【发布时间】: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


【解决方案1】:

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

void Enqueue (const std::string &s)

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

所以,在ProcessEvent 中,该字符串早已不复存在。

【讨论】:

  • 是的!当然。所以我的错误假设是 std::string("Hello") 的生命周期与静态“Hello”相同。谢谢所有提供正确答案的人。
【解决方案2】:

您正在排队一个临时的std::string,它是从文字“Hello”转换而来的。 调用fq.Enqueue() 后临时对象将被销毁,并且您的队列将引用已删除的对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-30
    • 2011-04-12
    • 1970-01-01
    • 2014-09-29
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多