سؤال

#include <memory>

struct a {};
struct b : public a {};

std::shared_ptr<b> get()
{
    std::shared_ptr<a> temp(new b);
    return std::static_pointer_cast<b>(temp); // atomic ref-count inc/dec
}

As far as I know, the only way to downcast shared_ptr is static_pointer_cast. However, it only takes const reference and creates downcasted copy of the argument. I want to avoid copy if it's possible, because copy construction and destruction of shared_ptr implies atomic increment/decrement operation.

There are some move constructors that take other instance of shared_ptr, but they don't support downcast.

Is is possible to do avoid copy in standard-compliant way?

هل كانت مفيدة؟

المحلول

No, there's no way to avoid the copy.

This is because there's no inheritance relationship between std::shared_ptr<a> and std::shared_ptr<b>, so you can't arbitrarily convert between them.

If you want to take ownership (by moving) of a pointer being passed to a constructor, why not use unique_ptr instead? IF you aren't taking ownership don't pass it as a smart pointer at all.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top