c++ - 类的 boost::shared_ptr 作为结构成员

标签 c++ boost struct shared-ptr

我有以下文件。

嗯:

#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;
    }

}

主要.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,因此必须存在至少一个 shared_ptr 到您在其上的任何 A 对象调用 someFunction。将其更改为:

boost::shared_ptr<A> a_tmp(boost::make_shared<A>());
a_tmp->someFunction();

关于c++ - 类的 boost::shared_ptr 作为结构成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38995599/

相关文章:

c - 尝试使用 C 将结构复制到 fifo 时出现问题

c - C 中的 typedef for struct

c++ - C++链表递归问题

C++ float 和 valgrind 奇怪的行为

c++ - 尝试将 boost.serialization 包含到我的 VS 项目时遇到问题

c++ - 安装 odeint <boost/config.hpp> 时出错

c - 为什么这个链表初始化不起作用?

c++ - 释放内存(如果可能)

c++ - 如何在arduino上使函数返回字符串?

c++ - 如何对数字元组应用 Action 元组?