尝试“复制” shared_ptr上载行为会导致对副本构造函数进行无限递归(这会导致segfault)

时间:2019-06-05 08:33:54

标签: c++ templates c++17 template-meta-programming

我正在尝试复制shared_ptr行为以更好地理解c ++ 17中的模板元编程和type_traits。 具体来说,我想复制向上转换的行为,即无需进行任何明确的强制转换就可以将shared_ptr< Derived >分配/复制到shared_ptr< Base >的机会。

类型检查有效,但是在尝试复制或分配派生对象时,在复制构造函数中出现无限循环的段错误。

通用模板类

#pragma once

#include <memory>
#include <type_traits>

template <typename T>
class Generic {
    public:
        template <typename DerivedT>
        using Assignable = typename std::enable_if<std::is_assignable<T, DerivedT>::value, Generic<T> &>::type;

        Generic() : _ptr(nullptr) {}


        Generic(T *ptr) : _ptr{ptr} {};

        Generic(Generic && cptr) :
                _ptr(std::move(cptr._ptr))
        {}

        Generic(const Generic & cptr) :
                _ptr{cptr._ptr}
        {}

        template <typename DerivedT, typename = Assignable<DerivedT>>
        Generic(const Generic<DerivedT> &cptr) 
            : Generic(static_cast<const Generic &>(cptr)._ptr)
        {}

        ~Generic() = default;

        Generic & operator=(Generic && cptr) = default;

        Generic & operator=(const Generic & cptr) {
            _ptr = cptr._ptr;
            return *this;
        }

        template <typename DerivedT>
        Assignable<DerivedT> operator=(const Generic<DerivedT> &cptr) {
            _ptr = static_cast<const Generic &>(cptr)._ptr;
            return *this;
        }

    private:
        T* _ptr;
};

main.cpp

#include "Generic.hpp"

struct Base {
};

struct Derived : public Base {
};

int main() {
    Generic<Derived> derived = Generic<Derived>();
    Generic<Base> base(derived);
    //Generic<Base> base = derived;
}

1 个答案:

答案 0 :(得分:4)

您的问题可以减少为:

template <typename T>
class Generic {
    public:
        Generic() = default;

        Generic(T *ptr) : _ptr{ptr} {};

        template <typename Derived>
        Generic(const Generic<Derived> &cptr) :
          Generic(static_cast<const Generic &>(cptr)._ptr)
        {}

    private:
        T* _ptr = nullptr;
};

struct Base {
};

struct Derived : public Base {
};

int main() {
    Generic<Derived> derived = Generic<Derived>();
    Generic<Base> base(derived);
}

问题在于,使用static_cast<const Generic &>(cptr)会隐式创建Generic<T>形式的Generic<Derived>实例,从而递归地调用构造函数 ad infinitum

可能的解决方法是:

template <typename T>
class Generic {
    public:
        Generic() = default;

        Generic(T *ptr) : _ptr{ptr} {};

        template <typename Derived>
        Generic(const Generic<Derived> &cptr) :
          Generic(cptr._ptr)
        {}

    private:
        T* _ptr = nullptr;

    template <typename U>
    friend class Generic;
};

struct Base {
};

struct Derived : public Base {
};

int main() {
    Generic<Derived> derived = Generic<Derived>();
    Generic<Base> base(derived);
}