将派生类的std :: shard_ptr转换为基类的shard_ptr
convert std::shard_ptr of derived class to that of base class
#include <iostream>
#include <memory>
class Base{
};
class Derive : public Base{
};
void foo(std::shared_ptr<Base>& p){
}
void bar(const std::shared_ptr<Base>& p){
}
int main(){
auto base = std::make_shared<Base>();
foo(base);
bar(base);
auto derive = std::make_shared<Derive>();
foo(derive);
bar(derive);
return 0;
}
g -std = c 0x test.cpp
编译器说:
test.cpp:21:5: error: no matching function for call to 'foo'
foo(derive);
^~~
test.cpp:9:6: note: candidate function not viable: no known conversion from 'std::__1::shared_ptr<Derive>' to
'std::shared_ptr<Base> &' for 1st argument
void foo(std::shared_ptr<Base>& p){
您可以解释为什么您不能将派生类的共享_ptr传递给foo(),而您可以将其传递给bar()接收共享_ptr的const reference
对不起,我的英语不好。谢谢。
调用 foo(derive)
需要从 derive
构建临时的 std::shared_ptr<Base>
,并且非const lvalue-reference不能绑定到临时对象。要调用foo
,您将需要构造一个可以传递到它的命名std::shared_ptr<Base>
:
auto derive = std::make_shared<Derive>();
std::shared_ptr<Base> b = derive;
foo(b);
bar(derive)
很好,因为const引用可以与临时性结合。未命名的临时std::shared_ptr<Base>
是由derive
构建的,对该临时性的引用将传递给bar
。
相关文章:
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- C++中的指针否定 (!ptr == NULL)
- 从const ptr*转换为ptr*时出现问题
- 这是MSVC 2013中具有共享PTR的单例的正确实现吗?
- 对唯一 ptr 无效读取的引用向量
- C++ 类型转换基础 PTR 到派生 PTR 保存在引用类中
- 如何使用非类型参数传递模板化类的 Ref 或 Ptr
- 唯一 ptr 将所有权移动到包含对象的方法