c++奇特的临时引用

C++ strange reference to temporary

本文关键字:引用 c++      更新时间:2023-10-16

我不明白为什么下面的代码在编译时因为"返回对临时的引用"而失败。对我来说,单例不能是临时的,因为它是静态的!?

感谢
#include <memory>
class Parent {
public:
    static const std::shared_ptr<Parent>& get_default_value();
    static const std::shared_ptr<Parent>& get_some_other_value();
};
class Child: public Parent {
public:
    Child(){}
    static const std::shared_ptr<Child>& singleton;
};
const std::shared_ptr<Child>& singleton = std::make_shared<Child>();
const std::shared_ptr<Parent>& Parent::get_default_value() {
    return singleton;
}
const std::shared_ptr<Parent>& Parent::get_some_other_value() {
    //FILL ME
}

证明

编辑:Parent的默认值是Child的单例。(之前有一些其他的名字,但这是令人困惑的)。

编辑2:我还想有引用shared_pointers,因为默认情况下发生了很多,是一个单例,所以不妨节省空间

编辑3:我想要一个std::shared_ptr&作为类型结果,因为我希望接口对默认值和其他值 保持一致编辑4:由于不相关的原因,其他值需要为shared_ptr<>.

您的问题是Child::singletonstd::shared_ptr<Child>&类型,但get_singleton返回std::shared_ptr<Parent>&std::shared_ptr<Child>可以转换为std::shared_ptr<Parent>,但不能转换为std::shared_ptr<Parent>&,因此它必须创建一个std::shared_ptr<Parent>类型的临时对象并返回对该对象的引用。

通常没有理由通过引用返回shared_ptr。只要按值返回,它就会编译。

声明它的方式不是临时的。声明静态变量do:

const std::shared_ptr<Child>& Child::singleton = std::make_shared<Child>();

注意Child:: ?同样在函数get_singleton中使用:

const std::shared_ptr<Parent>& Parent::get_singleton() {
    return Child::singleton;
}

根据Dirk的分析,转换是问题所在,这是一个很好的解决方案:

class Parent {
public:
    static const std::shared_ptr<Parent>& get_singleton();
};
class Child: public Parent {
public:
    Child(){}
    static const std::shared_ptr<Parent>& singleton;
};
const std::shared_ptr<Parent>& singleton = std::make_shared<Child>();
const std::shared_ptr<Parent>& Parent::get_singleton() {
    return singleton;
}
证明