我已经使用弱指针和智能指针实现了一个双链表。该计划是工作,但我有关于怀疑const的getPrev签名方法。如果我把 const一个方法签名的结尾,它会导致绑定引用错误
error: binding reference of type 'std::weak_ptr<Node<Integer> >&' to 'const std::weak_ptr<Node<Integer> >' discards qualifiers
return prev;
Run Code Online (Sandbox Code Playgroud)
这样做的目的不是const标记*this为const吗?根据我的理解,返回类型是非常量的。
这是代码,main.cpp:
#include <memory>
#include <iostream>
#include "DoubleLinkedList.h"
class Integer {
private:
int number;
public:
Integer(int number) : number(number) {}
int get() { return number; }
};
int main() {
DoubleLinkedList<Integer> list;
list.insert(Integer(1));
list.insert(Integer(2));
list.insert(Integer(3));
list.insert(Integer(4));
list.insert(Integer(5));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
DoubleLinkedList.h
#include <memory>
#include <vector>
#include <iostream>
template <typename T>
class Node {
private:
T data;
std::weak_ptr<Node> prev;
std::shared_ptr<Node> next;
public:
Node(): data(0) {}
Node(const T &object) : data(object) {};
T getData() const {
return data;
}
void setData(T data) {
Node::data = data;
}
std::weak_ptr<Node> &getPrev() const {
return prev;
}
void setPrev(const std::weak_ptr<Node> &prev) {
Node::prev = prev;
}
std::shared_ptr<Node> &getNext() {
return next;
}
void setNext(const std::shared_ptr<Node> &next) {
Node::next = next;
}
};
template <typename T>
class DoubleLinkedList {
private:
std::shared_ptr<Node<T>> header;
std::weak_ptr<Node<T>> trailer;
int size;
public:
DoubleLinkedList() : size(0) {}
void insert(const T &value) {
auto node = std::make_shared<Node<T>>(value);
if (size++ == 0) {
header = node;
} else {
auto last = trailer.lock();
last->getNext() = node;
node->getPrev() = last;
}
trailer = node;
}
};
Run Code Online (Sandbox Code Playgroud)
如果您位于const方法内部,则所有数据成员都会被考虑const。
也就是说,在这个函数内部:
std::weak_ptr<Node> &getPrev() const
Run Code Online (Sandbox Code Playgroud)
你可以想象这样的成员变量:
const T data;
const std::weak_ptr<Node> prev;
const std::shared_ptr<Node> next;
Run Code Online (Sandbox Code Playgroud)
应该清楚的是,您不能返回对 const 对象的非常量引用:
const int x;
int& getX()
{
return x; // error
}
Run Code Online (Sandbox Code Playgroud)
该引用将允许您进行修改,x即使它是const,因此这是禁止的(形式上:非常量引用不能绑定到 const 对象)。
在,const的成员函数内部是 a ,因此 a出于完全相同的原因不能绑定到它。Nodeprevconst std::weak_ptr<Node>std::weak_ptr<Node>&
看来insert您确实打算修改node(通过更改其prev值),在这种情况下该getPrev函数不应该是 const(因为您打算修改该对象)。但这种访问可能应该保留给特定的DoubleLinkedList外部用户,而不是某个任意的外部用户。然后就变成了界面设计的问题:代码的哪些部分是实现细节以及如何对用户隐藏这些部分?用户应该与哪些部分进行交互(破坏东西的机会最小)?