관리 메뉴

개발자비행일지

C++ 초기화 리스트 본문

▶ Ardupilot

C++ 초기화 리스트

Cyber0946 2020. 9. 3. 11:04

Ardupilot에서 library의 SITL 폴더에 있는 Sim_Aricraft.cpp 파일을 분석하던 도 중 , C++에 익숙치 않는 내가 이해 할 수 없는 문법이 존재했다. 콜론(:) 의 존재이다.!!! 한참을 구글링 하다가 이 존재가 

초기화 리스트 란 것을 알아냈다. 

이 초기화 리스트는 클래스의 각 멤버를 생성자에서 초기화 할 때, 생성자 뒤에 콜론연산자(:)를 사용해서 객체의 멤버를 초기화 할 때 사용하는 리스트 이다. 초기화 리스트 또는 콜론 초기화라고 한다. 

 

class Aircraft {
public:
    Aircraft(const char *frame_str);

    // called directly after constructor:
    virtual void set_start_location(const Location &start_loc, const float start_yaw);

    /*
      set simulation speedup
     */
    void set_speedup(float speedup);

    /*
      set instance number
     */
    void set_instance(uint8_t _instance) {
        instance = _instance;
    }

    /*
      set directory for additional files such as aircraft models
     */
    void set_autotest_dir(const char *_autotest_dir) {
        autotest_dir = _autotest_dir;
    }

    /*  Create and set in/out socket for extenal simulator */
    virtual void set_interface_ports(const char* address, const int port_in, const int port_out) {};

    /*
      step the FDM by one time step
     */
    virtual void update(const struct sitl_input &input) = 0;

    void update_model(const struct sitl_input &input);

    /* fill a sitl_fdm structure from the simulator state */
    void fill_fdm(struct sitl_fdm &fdm);

    /* smooth sensors to provide kinematic consistancy */
    void smooth_sensors(void);

    /* return normal distribution random numbers */
    static double rand_normal(double mean, double stddev);

    // get frame rate of model in Hz
    float get_rate_hz(void) const { return rate_hz; }

    const Vector3f &get_gyro(void) const {
        return gyro;
    }

    const Vector3f &get_velocity_ef(void) const {
        return velocity_ef;
    }

    const Vector3f &get_velocity_air_ef(void) const {
        return velocity_air_ef;
    }

    const Matrix3f &get_dcm(void) const {
        return dcm;
    }

    const Vector3f &get_mag_field_bf(void) const {
        return mag_bf;
    }

    float gross_mass() const { return mass + external_payload_mass; }

    virtual void set_config(const char* config) {
        config_ = config;
    }


    const Location &get_location() const { return location; }

    const Vector3f &get_position() const { return position; }

    void get_attitude(Quaternion &attitude) const {
        attitude.from_rotation_matrix(dcm);
    }

    const Location &get_home() const { return home; }
    float get_home_yaw() const { return home_yaw; }

    void set_sprayer(Sprayer *_sprayer) { sprayer = _sprayer; }
    void set_parachute(Parachute *_parachute) { parachute = _parachute; }
    void set_gripper_servo(Gripper_Servo *_gripper) { gripper = _gripper; }
    void set_gripper_epm(Gripper_EPM *_gripper_epm) { gripper_epm = _gripper_epm; }
    void set_precland(SIM_Precland *_precland);

protected:
    SITL *sitl;
    Location home;
    bool home_is_set;
    Location location;

    float ground_level;
    float home_yaw;
    float frame_height;
    Matrix3f dcm;                        // rotation matrix, APM conventions, from body to earth
    Vector3f gyro;                       // rad/s
    Vector3f gyro_prev;                  // rad/s
    Vector3f ang_accel;                  // rad/s/s
    Vector3f velocity_ef;                // m/s, earth frame
    Vector3f wind_ef;                    // m/s, earth frame
    Vector3f velocity_air_ef;            // velocity relative to airmass, earth frame
    Vector3f velocity_air_bf;            // velocity relative to airmass, body frame
    Vector3f position;                   // meters, NED from origin
    float mass;                          // kg
    float external_payload_mass = 0.0f;  // kg
    Vector3f accel_body;                 // m/s/s NED, body frame
    float airspeed;                      // m/s, apparent airspeed
    float airspeed_pitot;                // m/s, apparent airspeed, as seen by fwd pitot tube
    float battery_voltage = -1.0f;
    float battery_current = 0.0f;
    float rpm1 = 0;
    float rpm2 = 0;
    uint8_t rcin_chan_count = 0;
    float rcin[8];
    float range = -1.0f;                 // rangefinder detection in m

    struct {
        // data from simulated laser scanner, if available
        struct vector3f_array points;
        struct float_array ranges;
    } scanner;
    
    // Wind Turbulence simulated Data
    float turbulence_azimuth = 0.0f;
    float turbulence_horizontal_speed = 0.0f;  // m/s
    float turbulence_vertical_speed = 0.0f;    // m/s

    Vector3f mag_bf;  // local earth magnetic field vector in Gauss, earth frame

    uint64_t time_now_us;

    const float gyro_noise;
    const float accel_noise;
    float rate_hz;
    float achieved_rate_hz;
    float target_speedup;
    uint64_t frame_time_us;
    float scaled_frame_time_us;
    uint64_t last_wall_time_us;
    uint8_t instance;
    const char *autotest_dir;
    const char *frame;
    bool use_time_sync = true;
    float last_speedup = -1.0f;
    const char *config_ = "";

    // allow for AHRS_ORIENTATION
    AP_Int8 *ahrs_orientation;

    enum GroundBehaviour {
        GROUND_BEHAVIOR_NONE = 0,
        GROUND_BEHAVIOR_NO_MOVEMENT,
        GROUND_BEHAVIOR_FWD_ONLY,
        GROUND_BEHAVIOR_TAILSITTER,
    } ground_behavior;

    bool use_smoothing;

    AP_Terrain *terrain;
    float ground_height_difference() const;

    virtual bool on_ground() const;

    // returns height above ground level in metres
    float hagl() const;  // metres

    /* update location from position */
    void update_position(void);

    /* update body frame magnetic field */
    void update_mag_field_bf(void);

    /* advance time by deltat in seconds */
    void time_advance();

    /* setup the frame step time */
    void setup_frame_time(float rate, float speedup);

    /* adjust frame_time calculation */
    void adjust_frame_time(float rate);

    /* try to synchronise simulation time with wall clock time, taking
       into account desired speedup */
    void sync_frame_time(void);

    /* add noise based on throttle level (from 0..1) */
    void add_noise(float throttle);

    /* return wall clock time in microseconds since 1970 */
    uint64_t get_wall_time_us(void) const;

    // update attitude and relative position
    void update_dynamics(const Vector3f &rot_accel);

    // update wind vector
    void update_wind(const struct sitl_input &input);

    // return filtered servo input as -1 to 1 range
    float filtered_idx(float v, uint8_t idx);
    float filtered_servo_angle(const struct sitl_input &input, uint8_t idx);
    float filtered_servo_range(const struct sitl_input &input, uint8_t idx);

    // extrapolate sensors by a given delta time in seconds
    void extrapolate_sensors(float delta_time);

    // update external payload/sensor dynamic
    void update_external_payload(const struct sitl_input &input);

    void add_shove_forces(Vector3f &rot_accel, Vector3f &body_accel);
    void add_twist_forces(Vector3f &rot_accel);

private:
    uint64_t last_time_us = 0;
    uint32_t frame_counter = 0;
    uint32_t last_ground_contact_ms;
    const uint32_t min_sleep_time;

    struct {
        bool enabled;
        Vector3f accel_body;
        Vector3f gyro;
        Matrix3f rotation_b2e;
        Vector3f position;
        Vector3f velocity_ef;
        uint64_t last_update_us;
        Location location;
    } smoothing;

    LowPassFilterFloat servo_filter[4];

    Sprayer *sprayer;
    Gripper_Servo *gripper;
    Gripper_EPM *gripper_epm;
    Parachute *parachute;
    SIM_Precland *precland;
};

} // namespace SITL
Aircraft::Aircraft(const char *frame_str) :
    ground_level(0.0f),
    frame_height(0.0f),
    dcm(),
    gyro(),
    gyro_prev(),
    ang_accel(),
    velocity_ef(),
    mass(0.0f),
    accel_body(0.0f, 0.0f, -GRAVITY_MSS),
    time_now_us(0),
    gyro_noise(radians(0.1f)),
    accel_noise(0.3f),
    rate_hz(1200.0f),
    autotest_dir(nullptr),
    frame(frame_str),
#if defined(__CYGWIN__) || defined(__CYGWIN64__)
    min_sleep_time(20000)
#else
    min_sleep_time(5000)
#endif
{
    // make the SIM_* variables available to simulator backends
	// SIM_* variables can search in mav.param or using mavproxy command param show 
    sitl = AP::sitl();
	
    set_speedup(1.0f);

    last_wall_time_us = get_wall_time_us();
    frame_counter = 0;

    // allow for orientation settings, such as with tailsitters
    enum ap_var_type ptype;
    ahrs_orientation = (AP_Int8 *)AP_Param::find("AHRS_ORIENTATION", &ptype);
    terrain = reinterpret_cast<AP_Terrain *>(AP_Param::find_object("TERRAIN_"));
}
#include <iostream>

class Foo {
public:
  int bar;
  Foo(int num): bar(num) {};
};

int main(void) {
  std::cout << Foo(42).bar << std::endl;
  return 0;
}
//초기화 리스트
Foo(int num): bar(num) {};

//함수에서 초기화
Foo(int num)
{
   bar = num;
}

그냥 생성자 함수{} 내에서 초기화하는 것과, 이렇게 초기화 리스트를 쓰 는것의 차이는

초기화 리스트에서 초기화를 하는 경우, 생성자가 호출될 때 객체의 생성과 초기화가 한 번에 이루어집니다.

생성자 함수 내{}에서 초기화를 하는 경우, 객체가 생성되어, default생성자로 초기화된 상태에서 다시 한 번 할당받게 하게 됩니다. 이 경우엔 default할당-유저할당의 2단계를 거치게 돼서 오버헤드가 생깁니다.

'▶ Ardupilot' 카테고리의 다른 글

Drone -Gyro Sensor  (0) 2020.12.06
매틀랩 단축키  (0) 2020.10.08
Back Ground For Ardupilot, Mavlink  (0) 2020.08.01
시스템 연속시간 시스템, 이산시간 시스템, 시스템의 속성  (0) 2020.07.24
칼만이득  (0) 2020.07.15