简体   繁体   English

类的boost :: shared_ptr作为struct成员

[英]boost::shared_ptr of a class as a struct member

I have the following files. 我有以下文件。

ah: 啊:

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

bh: bh:

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

What I want to do is to use a struct to store the pointer of class A instance. 我想要做的是使用一个结构来存储A类实例的指针。 But I cannot resolve the relationship between these files. 但是我无法解决这些文件之间的关系。 Can someone give me some ideas ? 有人可以给我一些想法吗?

UPDATE: 更新:

The problem is, when I compile these files. 问题是,当我编译这些文件时。 I got 我有

In b.h, error: ‘A’ was not declared in this scope typedef boost::shared_ptr<A> a_ptr;

UPDATE: 更新:

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();

This will not work. 这是行不通的。 Since A::someFunction calls shared_from_this , there must exist at least one shared_ptr to any A object on which you call someFunction . 由于A::someFunction调用shared_from_this ,必须存在至少一个shared_ptr任何A在其上调用对象someFunction Change this to: 更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM