重载运算符时指针链断开

得到了以下代码(应该是所有相关代码):

//movable_ptr.hpp
//Michal Cermak

#ifndef MOVABLE_H
#define MOVABLE_H

template<typename T> class movable_ptr;

template<typename T> class enable_movable_ptr {
public:
    //default constructor
    enable_movable_ptr() {};
    enable_movable_ptr(T* p) : ptr_(p) {};

    //operators...
    T& operator*() const { return *ptr_; };
    T* operator->() const { return ptr_; };
    bool operator==(const enable_movable_ptr<T>& p) const { return p.ptr_ == ptr_; };

    T* get() {return ptr_; };
private:
    T* ptr_ = nullptr;
};


template<typename T> class movable_ptr {
public:
    //parameterless constructor
    movable_ptr() {};

    //constructor from T*
    movable_ptr(T* p) : ptr_(p) { add_to_tracked(this); };

    //operators ...
    enable_movable_ptr<T>& operator*() const { return *ptr_; };
    enable_movable_ptr<T>* operator->() const { return ptr_; };
    bool operator==(const movable_ptr<T>& p) const { return p.ptr_ == ptr_; };

    //access to variables
    enable_movable_ptr<T>* get() {return ptr_; };
    void set(enable_movable_ptr<T>* p) { ptr_ = p; };

private:
    enable_movable_ptr<T>* ptr_ = nullptr;
};

template<typename T> movable_ptr<T> get_movable(enable_movable_ptr<T>& p){
    return new movable_ptr<T>(p);
};

#endif

My problem is that when I run the following code (or other similar ones for that matter), the movable_ptr<T> doesn't get de-referenced all the way to A, but gets stuck on enable_movable_ptr<A>, which causes comparisons and other stuff to throw errors, because "'val' is not a member of enable_movable_ptr<A>". It is a member of A though, so if I de-reference correctly, it should then work.

#include <iostream>
#include <memory>
#include <string>

#include "movable_ptr.hpp"

using namespace std;

class A : public enable_movable_ptr<A>
{
public:
    int val;

    A(int val) : val(val) {}
};

void test_ptr_dereference() {
    A x(42);
    auto px = get_movable(x);

    TEST_ASSERT(&*px == &x);
    TEST_ASSERT(&px->val == &x.val);
}

int main(int argc, char* argv[]) {
    test_ptr_dereference();
}

我猜我在重载运算符中做错了什么,但否则没有任何线索。关于如何解决它的任何想法?

评论