【发布时间】:2021-08-15 08:23:57
【问题描述】:
我正在使用 C++ 编写解释性语言。现在的问题是我想实现重新分配之类的功能:
VAR a = [1,"2",[3,4]]
VAR a[0] = 100
在我的语言中,List 是shared_ptr<Data> 的vector,这样您就可以在一个列表中存储不同类型的数据。如果有人要更改元素,我可以得到shared_ptr<Data> elem,以及即将分配的shared_ptr<Data> value。
类似:
shared_ptr<Data> elem = visit(elem_node)
shared_ptr<Data> value = visit(value_node)
*elem = *value;
抱歉,我忘了说 visit() 返回的是一个值,而不是一个引用,这就是为什么我没有让 elem=value;
事实证明,唯一改变的是来自Data 类的数据成员。
但我想要的是让shared_ptr“重新指向”一个新对象。有可能吗?
我试过dynamic_pointer_cast,如果原始元素和新值是同一类型,一切都很好。但正如我所指出的,我允许在一个列表中包含不同类型的元素,所以这只能是我的最后一根稻草。
我已经根据 Remy Lebeau 的回答编写了一个演示代码(谢谢):
#include <iostream>
#include <string>
#include <vector>
#include <memory>
using namespace std;
struct Data
{
virtual ~Data() = default;
virtual void print() = 0;
};
struct Integer : Data
{
int value;
Integer(int val) : value(val) {}
void print() override { cout << "integer(" << value << ")" << endl; }
};
struct String : Data
{
string value;
String(string val) : value(val) {}
void print() override { cout << "string(\"" << value << "\")" << endl; }
};
struct RuntimeResult
{
RuntimeResult success(const shared_ptr<Data> &value)
{
this->value = value;
return (*this);
}
shared_ptr<Data> registry(const RuntimeResult &res)
{
// this is for handling error
// but this simplify version simply return value;
return res.value;
}
shared_ptr<Data> value;
};
int main()
{
// simulate a List variable
vector<shared_ptr<Data>> list;
list.push_back(make_shared<Integer>(123456));
list.push_back(make_shared<String>("hello"));
RuntimeResult res;
// inside registry, it should be something like visit_IndexNode(elem_node)
// to interprete a node on AST Tree
// but the return is simply like what have shown below
shared_ptr<Data> elem = res.registry(RuntimeResult().success(list.at(0)));
// Using Visual Studio 2019's debugging mode
// we can see that elem's ptr == list[0]'s ptr
// in other word, they are pointing to the same thing(123456)
shared_ptr<Data> value = res.registry(RuntimeResult().success(make_shared<String>("test")));
elem = value;
elem->print(); // "test"
list[0]->print(); // still 123456
return 0;
}
这正是我的问题
【问题讨论】:
标签: c++ vector polymorphism shared-ptr