Pointer chain broken when overloading operators

女生的网名这么多〃 提交于 2020-04-17 21:55:58

问题


Got this code (should be all that is relevant):

//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();
}

I am guessing I did something wrong in the overloaded operators, but otherwise have no clue. Any ideas on how to fix it?

来源:https://stackoverflow.com/questions/61111132/pointer-chain-broken-when-overloading-operators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!