我有这段代码:
#include <iostream>
#include <memory>
#include <string>
class base {
public:
virtual void method() = 0;
virtual ~base() = default;
};
class test: public base, public std::enable_shared_from_this<test> {
private:
std::string text;
public:
test(std::string text): text(std::move(text)) {}
~test() = default;
virtual void method() override {
std::cout << "text: " << text;
std::cout << " this: " << this->shared_from_this().get() << std::endl;
}
static std::unique_ptr<base> create(std::string text) {
return std::unique_ptr<base>(new test(std::move(text)));
}
};
static auto create_test(std::string text) {
return test::create(std::move(text));
}
int main(int argc, char* argv[]) {
std::shared_ptr<base> shared = create_test("some text");
shared->method();
return 0;
}
当我运行这个程序时,我得到异常“bad_weak_ptr”。 你能解释为什么“enable_shared_from_this”没有初始化?
当我将unique_ptr<base>
的实例更改为unique_ptr<test>
时,它可以正常工作。
$ ./test
terminate called after throwing an instance of 'std::bad_weak_ptr'
what(): bad_weak_ptr
text: some textAborted (core dumped)
答案 0 :(得分:1)
您还期待什么?您正在使用shared_ptr<base>
。 Base不是enable_shared_from_this
所固有的,因此它的共享指针无法初始化shared_from_this
使用的弱引用。
完全按照设计工作。
答案 1 :(得分:0)
您可以使用此{k: v.tolist() for k, v in df.set_index([0, 1]).iterrows()}
{('a', 'b'): [1, 2], ('a', 'c'): [2, 4]}
函数将{'position': Point(x=0.7938064310002948, y=0.4000015952566877, z=0.28522708748065545), 'orientation': Quaternion(x=-0.18674837754140436, y=0.7484662663927322, z=-0.5955181308876427, w=0.22423524999844527)}
构建的共享指针强制转换为test
:
base
否则,它将无效
create
按预期工作,但请考虑this:
std :: enable_shared_from_this允许当前由名为pt的std :: shared_ptr管理的对象t安全地生成额外的std :: shared_ptr实例pt1,pt2,...这些实例与pt共享t的所有权。
在您的代码中,您没有在static std::shared_ptr<base> create(std::string text) {
return std::shared_ptr<test>(new test(std::move(text)));
}
中创建任何enable_shared_from_this
上面的shared_pointer
函数完成了这项工作。