【问题标题】:Returning reference to locally dereferenced pointer返回对本地取消引用的指针的引用
【发布时间】:2017-12-07 13:54:04
【问题描述】:

这段代码的行为是否明确?返回的引用是否总是正确的? Bar::method() 调用会一直顺利吗?

struct Bar
{
    void method() {...};
};

struct Foo
{
    static unique_ptr<Bar> bar_ptr;
    static Bar& get_reference()
    {
        return *bar_ptr;
    }
};

unique_ptr<Bar> Foo::bar_ptr = nullptr;

int main()
{
    Foo::bar_ptr = make_unique<Bar>();
    Foo::get_reference().method();

    return 0;
}

【问题讨论】:

  • 是的,为什么不呢? Bar 的构造实例将在 main 返回后销毁。
  • 这取决于你所说的“总是”是什么意思。不,在您致电 make_unique 之前以及在 main() 终止之后的某个时间,这将是不正确的。
  • 那么在 Bar 的实例被销毁之前引用将是正确的,我说得对吗?

标签: c++ c++11 pointers


【解决方案1】:

这段代码的行为是否明确?

是的是的。

struct Bar 的实例将在main() 终止后超出范围,从而被销毁。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 2021-07-19
    • 2021-12-09
    相关资源
    最近更新 更多