作为结构成员的类的boost::shared_ptr
boost::shared_ptr of a class as a struct member
我有以下文件。
a.h:
#ifndef __A__
#define __A__
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
class A: public boost::enable_shared_from_this<A>{
public:
void somefunction();
};
#endif
a.cpp:
#include "a.h"
#include "b.h"
void A::somefunction()
{
Node new_node;
new_node.id_ = 1;
new_node.ptr = shared_from_this();
C* c = C::GetInstance();
c->addNode(new_node);
}
b.h:
#ifndef __B__
#define __B__
#include "a.h"
#include <vector>
typedef boost::shared_ptr<A> a_ptr;
struct Node{
size_t id_;
a_ptr ptr;
};
class C {
public:
static C *GetInstance(){
if(m_pInstance == nullptr){
m_pInstance = new C();
}
return m_pInstance;
}
void addNode(Node& node);
void show();
private:
static C* m_pInstance;
std::vector<Node> nodes_;
};
#endif
b.cpp:
#include "b.h"
#include <iostream>
C* C::m_pInstance = nullptr;
void C::addNode(Node& node){
nodes_.push_back(node);
}
void C::show(){
for(size_t i=0; i< nodes_.size(); i++){
if(nodes_[i].ptr != nullptr)
std::cout << nodes_[i].id_ << " " << "pointer not null" << std::endl;
}
}
main.cpp:
#include "a.h"
#include "b.h"
int main(){
A a_tmp;
a_tmp.somefunction();
C* c_tmp = C::GetInstance();
c_tmp->show();
return 0;
}
我想做的是使用一个结构来存储类a实例的指针。但我无法解决这些文件之间的关系。有人能给我一些想法吗?
更新:
问题是,当我编译这些文件时。我有
In b.h, error: ‘A’ was not declared in this scope typedef boost::shared_ptr<A> a_ptr;
更新:
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_weak_ptr> >'
A a_tmp;
a_tmp.somefunction();
这是行不通的。由于A::someFunction
调用shared_from_this
,因此对于调用someFunction
的任何A
对象,都必须至少存在一个shared_ptr
。将其更改为:
boost::shared_ptr<A> a_tmp(boost::make_shared<A>());
a_tmp->someFunction();
相关文章:
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- dopen():不以 root 身份运行时"failed to map segment from shared object"
- C++中的指针否定 (!ptr == NULL)
- 从const ptr*转换为ptr*时出现问题
- 无法使用 libtool 将 -shared 参数传递给 g++
- boost::shared_ptr和std::shared-ptr的同居
- 我可以用std::shared_ptr而不是boost::shared-ptr构建boost库吗
- shared-ptr-C++shared_ptr与unique_ptr用于资源管理