就像這樣:
#include <memory>
// everything is an Object - yuk, but ok, if you wish...
struct Object : std::enable_shared_from_this<Object>
{
};
struct GameObject : Object
{
};
struct IRenderable
{
virtual void render() {};
};
struct RederableGameObject : GameObject, IRenderable
{
auto as_shared_renderable() -> std::shared_ptr<IRenderable>
{
// builds a new shared pointer to IRenderable which
// uses the same lifetime control block as me
return std::shared_ptr<IRenderable>
{
this->shared_from_this(), // where to get the control block
this // what to point to
};
}
};
文檔:
見構造數目(8)
http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr
更新:
這裏爲自由函數從任何物體,只要它最終公開從std::enable_shared_from_this
衍生獲取一個正確shared_pointer起點
#include <memory>
#include <type_traits>
namespace notstd
{
// stuff that I think *should be* std
using namespace std;
// a trait to determine whether class T is derived from template
// Tmpl<...>
template <typename T, template <class...> class Tmpl>
struct is_derived_from_template_impl
{
static std::false_type test(...);
template <typename...Us>
static std::true_type test(Tmpl<Us...> const &);
using result = decltype(test(std::declval<T>()));
};
template <typename T, template <class...> class Tmpl>
using is_derived_from_template = typename is_derived_from_template_impl<T, Tmpl>::result;
template <typename T, template <class...> class Tmpl>
constexpr auto is_derived_from_template_v = is_derived_from_template<T, Tmpl>::value;
// free function version of shared_from_this
template<class T>
auto shared_from(enable_shared_from_this<T>* p)
-> std::shared_ptr<T>
{
return p->shared_from_this();
}
// specific shared_ptr construction from type T
template<class T>
auto shared_from(T*p)
-> enable_if_t
<
is_derived_from_template_v
<
T,
enable_shared_from_this
>,
std::shared_ptr<T>
>
{
return std::shared_ptr<T>(p->shared_from_this(), p);
}
}
// everything is an Object - yuk, but ok, if you wish...
struct Object : std::enable_shared_from_this<Object>
{
};
struct GameObject : Object
{
};
struct IRenderable
{
virtual void render() {};
};
extern int emit(const char* str);
struct RederableGameObject : GameObject, IRenderable
{
auto as_shared_renderable() -> std::shared_ptr<RederableGameObject>
{
return notstd::shared_from(this);
}
auto as_shared_renderable() const -> std::shared_ptr<const RederableGameObject>
{
return notstd::shared_from(this);
}
void e() const {
emit("const");
}
void e() {
emit("mutable");
}
};
int main()
{
auto rgo = std::make_shared<RederableGameObject>();
// prove it works
auto p1 = rgo->as_shared_renderable();
// prove it works with a const object also
auto p2 = static_cast<const RederableGameObject&>(*rgo).as_shared_renderable();
p1->e();
p2->e();
}
也許是https://stackoverflow.com/q/20219385/103167的副本?看看'std :: dynamic_pointer_cast'不能解決你的問題。 –
我現在就試試。 – Matthew
請注意,shared_ptr很重且很慢。在實際應用中,它主要用於性能無關緊要的地方。 –