简体   繁体   中英

How can I get elements of a struct as a type boost::shared_ptr

I have a struct like this

struct Observation
{   
  observation_id id;
  ObsVector z;
  ObsMatrix R;
  double confidence;

  typedef boost::shared_ptr<Observation> Ptr;
  typedef boost::shared_ptr<const Observation> ConstPtr;
};

So I have a file EFK.h where I need a struct Observation

 class EFK
 {
   public:
    Observation::Ptr observer (new Observation);
  /// Something else
 }

So in the EFK.cpp file I want to use some variables of the struct

void EFK::update (ObsVector input, ObsVector delta)
{
   /// Some stuff
   input.z = observer->z -delta.z;
}

but when I compile I get this

*error: invalid use of member function (did you forget the ‘()’ ?)
     input.z = observer->z - delta.z;*
                       ^

And I don't know why . This is has something to be with the boos::shared_ptr?

Thank you

If you want to have a default value for attribute observer , write:

class EFK
{
public:
   Observation::Ptr observer = new Observation;
   /// Something else
};

Or:

class EFK
{
public:
   EFK() : observer(new Observation)
   {}

   Observation::Ptr observer;
   /// Something else
};

The syntax of Type name(...) , is the one of a function declaration.

I might read the question wrong - it's not entirely clear.

Responding just to the title "How can I get elements of a struct as a type shared_ptr " you can and should use aliasing-constructors of shared pointer:

Observation::Ptr p = std::make_shared<Observation>();
// take shared_ptr to a **member** of p
std::shared_ptr<ObsVector> member_z(p, &p->z);

This shared the ownership of the shared_ptr for p . Meaning that p will not be deleted until member_z is reset/destructed either:

p.reset(); // Observation stays alive
std::cout << "p has been reset\n";
member_z.reset(); // destructor of Observation runs now!
std::cout << "member_z has been reset\n";

Prints

p has been reset
~Observation
member_z has been reset

LIVE DEMO

Live On Coliru

#include <memory>
#include <iostream>

struct ObsVector { 
    double x,y,z; 
    ObsVector operator-(ObsVector const& o) const { return { x-o.x, y-o.y, z-o.z }; }
};

struct Observation
{   
    ~Observation() { std::cout << __FUNCTION__ << "\n"; }

    ObsVector z;
    typedef std::shared_ptr<Observation> Ptr;
};

int main() {
    Observation::Ptr p = std::make_shared<Observation>();
    // take shared_ptr to a **member** of p
    std::shared_ptr<ObsVector> member_z(p, &p->z);

    p.reset(); // Observation stays alive
    std::cout << "p has been reset\n";
    member_z.reset(); // destructor of Observation runs now!
    std::cout << "member_z has been reset\n";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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