【发布时间】:2021-06-28 10:40:54
【问题描述】:
我有以下代码:
#include <string>
#include <queue>
#include <thread>
#include <iostream>
using namespace std;
class MsgType {
public:
virtual string getData() const = 0;
static MsgType* getMsg();
};
class Msg1 : public MsgType {
string getData() const override final {
return "Msg1";
}
};
class Msg2 : public MsgType {
string getData() const override final {
return "Msg2";
}
};
queue<shared_ptr<MsgType>> allMsgs;
MsgType* MsgType::getMsg() {
shared_ptr<MsgType> msg_sp = nullptr;
if (!allMsgs.empty()) {
msg_sp = allMsgs.front();
allMsgs.pop();
}
if (msg_sp) {
MsgType* mt = msg_sp.get();
cout << "[in the method] " << mt->getData() << endl;
return mt;
} else {
return nullptr;
}
}
int main() {
MsgType* msg1 = new Msg1();
MsgType* msg2 = new Msg2();
shared_ptr<MsgType> msg;
msg.reset(msg1);
allMsgs.push(msg);
msg.reset(msg2);
allMsgs.push(msg);
MsgType* tryGetMsg = MsgType::getMsg();
cout << "[out of the method] " << tryGetMsg->getData() << endl;
}
在MsgType::getMsg() 方法中我可以看到输出,但在main() 中我看不到。我相信它正在尝试调用虚拟的MsgType::getData()。
如何在此方法之外获取MsgType,以访问派生类的方法?
谢谢!
【问题讨论】:
-
问题是您对
tryGetMsg->getData()的调用无效。由于您在getMsg中弹出指针,并且共享ptrmsg_sp在函数出口处被销毁,因此返回的指针指向一个已经被销毁的对象。 -
在不转移所有权时返回一个原始指针是可以的。不转移所有权时的原始指针参数是可以的。对于其他情况,请使用
std::unique_ptr(转到选项),或(如果必须)std::shared_ptr或std::weak_ptr。
标签: c++ abstract-class shared-ptr