【发布时间】:2020-04-09 16:02:55
【问题描述】:
所以我得到了这个代码:
//movable_ptr.hpp
//Michal Cermak
template<typename T> class movable_ptr;
template<typename T> class enable_movable_ptr {
public:
//default constructor
enable_movable_ptr() {};
//move constructor and assignment
enable_movable_ptr(enable_movable_ptr<T>&& p) {
first_ = p.getFirst();
p.retarget_to(this);
};
enable_movable_ptr<T>& operator=(enable_movable_ptr<T>&& p) {
if (this != &p)
{
first_ = p.getFirst();
p.retarget_to(this);
delete &p;
}
return *this;
};
//retargets all pointers in the linked list to a new address
void retarget_to(T* p)
{
if (first_ != nullptr)
{
auto current = first_;
do
{
current->set(p);
current = current->getNext();
} while (current != first_);
}
};
movable_ptr<T>* getFirst() { return first_; };
void setFirst(movable_ptr<T>* p) { first_ = p; };
private:
movable_ptr<T>* first_ = nullptr;
};
template<typename T> class movable_ptr {
public:
//constructors and stuff...
//access to variables
T* get() {return ptr_; };
void set(T* p) { ptr_ = p; };
movable_ptr<T>* getNext() { return next_; };
void setNext(movable_ptr<T>* p) { next_ = p; };
movable_ptr<T>* getPrevious() {return prev_; };
void setPrevious(movable_ptr<T>* p) { prev_ = p; };
private:
T* ptr_ = nullptr;
movable_ptr<T>* next_ = this;
movable_ptr<T>* prev_ = this;
};
我的问题是我需要将T * 赋予retarget_to,但我在移动构造函数中使用retarget_to(this) 并在enable_movable_ptr 中赋值。通过enable_movable_ptr<T> * 而不仅仅是T *。问题是,我假设 T 继承自 enable_movable_ptr,它永远不会直接使用,只能通过从它继承的对象。例如:
class A : public enable_movable_ptr<A>
{
public:
int val;
A(int val) : val(val) {}
};
然后这样使用:
A x(42);
A y = move(x);
在这种情况下,this 将是enable_movable_ptr<A> *,但我需要一些可以给我A * 的东西。基本上我需要一个指向 = 运算符的左值的指针,同时在所述运算符的重载中。有没有办法做到这一点,还是我要求一些不可能的事情?
【问题讨论】:
标签: c++ pointers lvalue move-constructor