#include <iostream>
#include <memory>
class Parent {
public:
virtual void Print() { std::cout << "Parent" << std::endl; }
};
class Child : public Parent {
public:
void Print() override { std::cout << "Child" << std::endl; }
};
template <typename ty>
class A {
public:
A(ty t) : t_(t) {}
void Print() { t_.Print(); }
private:
ty t_;
};
int main() {
std::shared_ptr<A<Child>> a = std::make_shared<A<Child>>(Child());
std::shared_ptr<A<Parent>> b = std::reinterpret_pointer_cast<A<Parent>>(a);
std::cout << "a.use_count: " << a.use_count()
<< ", b.use_count: " << b.use_count() << std::endl;
std::cout << "a address: " << a.get() << ", b address: " << b.get()
<< std::endl;
b->Print();
getchar();
return 0;
}
上图这种情况,常规的转换不能保证“转换以后,引用计数是正确的”。
用reinterpret_pointer_cast转换以后,可以保证这一点。