c++奇特的临时引用
C++ strange reference to temporary
我不明白为什么下面的代码在编译时因为"返回对临时的引用"而失败。对我来说,单例不能是临时的,因为它是静态的!?
感谢#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::singleton
是std::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;
}
证明相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 强制转换为引用类型
- 引用一个已擦除类型(void*)的指针
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 具有默认值的引用获取函数
- 如何使用基类指针引用派生类成员
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 如何引用基类的派生类?