【发布时间】:2018-02-06 18:46:59
【问题描述】:
我尝试发送一个带有多态类的 shared_ptr 函数。 我的目标是找到一种最好的方式来发送我的 shared_ptr 不增加 ref_count。
编辑:我不搜索替换我的 shared_ptr 的解决方案,因为我想调用 shared_ptr.reset() 例如。
目前,void doGenericTemplate(std::shared_ptr<CLASS>& ptr) 是我想要的结果,但我更喜欢程序中的单个函数。
- 您还有其他解决方案吗?
此外,我不明白为什么函数 void doGeneric(std::shared_ptr<Base>& ptr) 无法编译(等效于没有 shared_ptr 工作正常:请查看完整代码中的 doClassic)。
- 你有解释吗?
谢谢!
部分代码
#include <iostream>
#include <memory>
class Base
{
public:
Base() = default;
virtual ~Base() = default;
virtual void run() = 0;
};
class Derived1: public Base
{
public:
Derived1() = default;
virtual ~Derived1() = default;
void run()
{
std::cout << " Derived1";
}
};
class Derived2: public Base
{
public:
Derived2() = default;
virtual ~Derived2() = default;
void run()
{
std::cout << " Derived2";
}
};
// This function works but increase count
void doGenericCopy(std::shared_ptr<Base> ptr)
{
ptr->run();
std::cout << " Ref count: " << ptr.use_count() << std::endl;
}
// This function works without increase count = OK !
void doSpecificD1(std::shared_ptr<Derived1>& ptr)
{
ptr->run();
std::cout << " Ref count: " << ptr.use_count() << std::endl;
}
// Compilation error = FAILED !
void doGeneric(std::shared_ptr<Base>& ptr)
{
ptr->run();
std::cout << " Ref count: " << ptr.use_count() << std::endl;
}
// Working fine for all Derivate = OK !
template<typename CLASS>
void doGenericTemplate(std::shared_ptr<CLASS>& ptr)
{
ptr->run();
std::cout << " Ref count: " << ptr.use_count() << std::endl;
}
int main()
{
auto d1 = std::make_shared<Derived1>();
auto d2 = std::make_shared<Derived2>();
std::cout << "With copy: " << std::endl;
doGenericCopy(d1);
doGenericCopy(d2);
std::cout << "Specific: " << std::endl;
doSpecificD1(d1);
std::cout << "Template: " << std::endl;
doGenericTemplate(d1);
doGenericTemplate(d2);
// Compilation issue
//doGeneric(d1);
}
完整代码
结论
目前在 c++ 中,shared_ptr 在语言中还没有特定的工具来使用模板内类的多态性。
最好的方法是重构我的代码,避免管理 shared_ptr (ref_count, reset)。
谢谢大家!
【问题讨论】:
-
TL;博士。没有阅读大量代码,需要 MCVE 来回答“为什么函数无法编译”。在一般问题上,通过引用传递
shared_ptr很好,但通常更好的办法是接受对父类的直接引用。
标签: c++ c++11 polymorphism pass-by-reference