mardi 31 octobre 2023

Use C++11 condition_varible to make 3 threads print 1-100 in turns. But the dead lock confuses me

I want to write a program use 3 threads to print 1-100 in turns using C++11 condition_variable, but dead lock confused me, here are my code:

the tmp.cpp is:

#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>


std::condition_variable cv12;
std::condition_variable cv23;
std::condition_variable cv31;

std::mutex mtx;

void Print(int i) {
  while (i <= 100) {
    if (i % 3 == 1) {
      {
        std::unique_lock<std::mutex> l(mtx);
        cv31.wait(l);
        std::cout << i << std::endl;
      }

      cv12.notify_all();
    } else if (i % 3 == 2) {
      {
        std::unique_lock<std::mutex> l(mtx);
        cv12.wait(l);
        std::cout << i << std::endl;
      }

      cv23.notify_all();
    } else if (i % 3 == 0) {
      {
        std::unique_lock<std::mutex> l(mtx);
        cv23.wait(l);
        std::cout << i << std::endl;
      }

      cv31.notify_all();
    }
    i += 3;
  }
}

int main() {
  std::thread t1(Print, 1);
  std::thread t2(Print, 2);
  std::thread t3(Print, 3);

  cv31.notify_all();

  t1.join();
  t2.join();
  t3.join();

  return 0;
}

the run command is:

$ g++ -g -o tmp tmp.cpp  && ./tmp

But the output sometimes could just and stops.

╰─$ ./tmp                
1
2
    

When I ask GPT or Claud, they give me no advice, that imply my code may correct, when I use gdb to debug for the deadlock, but this program always run correctly in gdb, which dead lock never occurs.

I refer to the ways of condition varible wait usage, may should add a Predicate, but I don't want to write more global varible to handle this, and I find the Predicate is optional, so I don't know where is the bug in my code?

How to prevent core dump in C++ using YAML-CPP and ImGui and converting data types correctly?

enter image description here

Here, my code:

#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include <GLFW/glfw3.h>
#include <yaml-cpp/yaml.h>
#include <iostream>
#include <fstream>
#include <vector>
// convert from YAML to datatypes
bool ConvertYAMLToInt(const YAML::Node& node, int& output) {
    if (node.IsScalar() && node.Type() == YAML::NodeType::Scalar) {
        try {
            output = node.as<int>();
            return true;
        } catch (const YAML::BadConversion& e) {
            // Handle conversion error if needed
        }
    }
    return false;
}

bool ConvertYAMLToDouble(const YAML::Node& node, double& output) {
    if (node.IsScalar() && node.Type() == YAML::NodeType::Scalar) {
        try {
            output = node.as<double>();
            return true;
        } catch (const YAML::BadConversion& e) {
            // Handle conversion error if needed
        }
    }
    return false;
}

bool ConvertYAMLToBool(const YAML::Node& node, bool& output) {
    if (node.IsScalar()) {
        std::string value = node.as<std::string>();
        if (value == "true") {
            output = true;
            return true;
        } else if (value == "false") {
            output = false;
            return true;
        }
    }
    return false;
}
//global variables
std::string file_path = "/home/user/robot/imgui/config/behaviors.yaml";
YAML::Node config;
YAML::Node copy_config;
YAML::Node LoadYAML(const std::string& filename)
{
    return YAML::LoadFile(filename);
}
void attributeYAML(YAML::Node& attribute_native){
    for (const auto& attributeNode: attribute_native){
        if (attributeNode.IsScalar()){
            int loadInt; double loadDouble; bool loadBool; 

            if (ConvertYAMLToInt(attributeNode, loadInt)){
                attribute_native = loadInt;
            }
            else if (ConvertYAMLToDouble(attributeNode, loadDouble)){
                attribute_native = loadDouble;
            }
            else if (ConvertYAMLToBool(attributeNode, loadBool)){
                attribute_native = loadBool;      
            }
            else{
                std::string name = attributeNode.as<std::string>();
                ImGui::Text("%s", name.c_str());
            }
        }
        else if (attributeNode.IsMap()){
            for (const auto& attribute_second : attributeNode){
                std::string memberName = attribute_second.first.as<std::string>();
                ImGui::Text("%s:", memberName.c_str());
                ImGui::Indent();
                attributeYAML(const_cast<YAML::Node&>(attribute_second.second)); // Menghilangkan const
                //attributeYAML(attribute_second.second);
                ImGui::Unindent();
            }
        }
   
        else if (attributeNode.IsSequence()){
            ImGui::Indent();
            for (auto attribute_third = attributeNode.begin(); attribute_third != attributeNode.end(); ++attribute_third){
                YAML::Node newNode = *attribute_third;
                attributeYAML(newNode);
            }
            ImGui::Unindent();
        }
    }
}
void renderButton(YAML::Node& config){
    for (const auto& behaviorsNode: config){
        std::string topicNode = behaviorsNode.first.as<std::string>();

        bool isButtonPressed = ImGui::Button(topicNode.c_str()); 
        if (isButtonPressed) {
            ImGui::OpenPopup(topicNode.c_str()); // open popup when button is clicked
        }
        
        ImGui::SetNextWindowSize(ImVec2(500,500));
        if (ImGui::BeginPopup(topicNode.c_str())){ // begin popup
            ImGui::Text("Behaviors: %s", topicNode.c_str());
            ImGui::Separator();

         
            for (const auto& secondTopic : behaviorsNode.second)
            {
                std::string secondName = secondTopic.first.as<std::string>();
                attributeYAML(const_cast<YAML::Node&>(secondTopic.second));
            }

            ImGui::EndPopup(); // end popup
        }
    }
}
int main(int, char**)
{
    if (!glfwInit())
        return 1;

    const char* glsl_version = "#version 130"; // GL 3.0 + GLSL 130

    GLFWwindow* window = glfwCreateWindow(1280, 640, "Welcome to App", nullptr, nullptr);
    if (window == nullptr)
        return 1;
    glfwMakeContextCurrent(window);
    glfwSwapInterval(1); // Enable vsync

    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImGuiIO& io = ImGui::GetIO();
    io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
    io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;

    ImGui::StyleColorsDark();

    ImGui_ImplGlfw_InitForOpenGL(window, true);
    ImGui_ImplOpenGL3_Init(glsl_version);

    ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);

    //outside while loop  
    config = LoadYAML(file_path);
    copy_config = config;

    while (!glfwWindowShouldClose(window))
    {
        glfwPollEvents();

        ImGui_ImplOpenGL3_NewFrame();
        ImGui_ImplGlfw_NewFrame();
        ImGui::NewFrame();

        //the starting of code
        ImGui::Text("The available functions of the robot.");
        ImGui::Separator();

        renderButton(config);

        //rendering
        ImGui::Render();
        int display_w, display_h;
        glfwGetFramebufferSize(window, &display_w, &display_h);
        glViewport(0, 0, display_w, display_h);
        glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
        glClear(GL_COLOR_BUFFER_BIT);
        ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());

        glfwSwapBuffers(window);
    }

    //clean up
    ImGui_ImplOpenGL3_Shutdown();
    ImGui_ImplGlfw_Shutdown();
    ImGui::DestroyContext();

    glfwDestroyWindow(window);
    glfwTerminate();

    return 0;
}
standstill:
    type: "standstill"
    control:
        control_horizon:
            - {duration: 1.0, num_of_controls: 4}

        max_acc: {x: 1.0, y: 1.0, theta: 1.0}

    required_inputs:
        velocity: "velocity"

    outputs:
        markers: "behavior_markers"

slow_standstill:
    type: "standstill"
    control:
        control_horizon:
            - {duration: 1.0, num_of_controls: 1}

        max_acc: {x: 1.0, y: 1.0, theta: 1.0}

    required_inputs:
        velocity: "velocity"

    outputs:
        markers: "behavior_markers"

joypad:
    type: "joypad"
    control:
        control_horizon:
            - {duration: 2.0, num_of_controls: 20}

        max_acc: {x:  0.5, y:  0.5, theta:  1.0}
        max_vel: {x:  0.5, y:  0.3, theta:  1.0}
        min_vel: {x: -0.3, y: -0.3, theta: -1.0}

        skip_vel_ramp: false

        footprint:
            - {x:  0.426, y:  0.326}
            - {x: -0.7,   y:  0.326}
            - {x: -0.7,   y: -0.326}
            - {x:  0.426, y: -0.326}
        footprint_padding: 0.3

    required_inputs:
        velocity: "velocity"
        laser: "combined_laser"
        joypad: "joypad"

    outputs:
        markers: "behavior_markers"

ptp:
    type: "ptp"
    control:
        control_horizon:
            - {duration: 1.0, num_of_controls: 5}
            - {duration: 2.0, num_of_controls: 6}
            - {duration: 1.0, num_of_controls: 2}

        max_acc: {x: 0.5, y:  0.5, theta:  1.0}
        max_vel: {x: 0.5, y:  0.3, theta:  0.75}
        min_vel: {x: -0.25, y: -0.3, theta: -0.75}

        is_unicycle: false # if unicycle make goal_state_intercept_angle non zero

        weights:
            goal_state:
                pos: {x: 20.0, y: 20.0, theta: 10.0}
                vel: {x: 10.0, y: 10.0, theta: 10.0}
            goal_state_intercept_angle: 0.0

            acc_limit: {x: 10000.0, y: 10000.0, theta: 10000.0}
            vel_limit: {x: 1000.0, y: 1000.0, theta: 1000.0}

            laser_pts_repulsion: 100.0

        footprint: {min_x: -0.7, max_x: 0.43, min_y: -0.33, max_y: 0.33}
        min_inflation_dist: 0.21
        max_inflation_dist: 1.0

        initial_guess:
            num_of_vel_x_samples: 4
            num_of_vel_y_samples: 5
            num_of_vel_theta_samples: 11
            quadratic_theta_samples: true
            apply_elliptical_filter: false
            num_of_controls: 1
            sample_time: 4.0
            states_per_control: 4
            frequency: 2

        shorten_control_horizon: true

    required_inputs:
        laser: "combined_laser"
        velocity: "velocity"
        localization: "mcl_optimal_raycast"

    outputs:
        markers: "behavior_markers"

standstill_to_lane_following_transition:
    type: "ptp"
    control:
        control_horizon:
            - {duration: 1.0, num_of_controls: 5}
            - {duration: 2.0, num_of_controls: 6}
            - {duration: 1.0, num_of_controls: 2}

        max_acc: {x: 0.5, y:  0.5, theta:  1.0}
        max_vel: {x: 0.5, y:  0.3, theta:  0.75}
        min_vel: {x: 0.0, y: -0.3, theta: -0.75}

        is_unicycle: false # if unicycle make goal_state_intercept_angle non zero

        weights:
            goal_state:
                pos: {x: 10.0, y: 10.0, theta: 20.0}
                vel: {x: 10.0, y: 10.0, theta: 10.0}
            goal_state_intercept_angle: 0.0

            acc_limit: {x: 10000.0, y: 10000.0, theta: 10000.0}
            vel_limit: {x: 1000.0, y: 1000.0, theta: 1000.0}

            laser_pts_repulsion: 100.0

        footprint: {min_x: -0.7, max_x: 0.43, min_y: -0.33, max_y: 0.33}
        min_inflation_dist: 0.25
        max_inflation_dist: 0.95

        initial_guess:
            num_of_vel_x_samples: 3
            num_of_vel_y_samples: 5
            num_of_vel_theta_samples: 11
            quadratic_theta_samples: false
            apply_elliptical_filter: true
            num_of_controls: 1
            sample_time: 4.0
            states_per_control: 4
            frequency: 4

        shorten_control_horizon: false

        reverse_motion_goal_threshold_linear: 0.3
        reverse_motion_goal_threshold_heading: 1.0

    required_inputs:
        laser: "combined_laser"
        velocity: "velocity"
        localization: "mcl_optimal_raycast"

    outputs:
        markers: "behavior_markers"

lane_following_to_standstill_transition:
    type: "ptp"
    control:
        control_horizon:
            - {duration: 1.0, num_of_controls: 5}
            - {duration: 2.0, num_of_controls: 6}
            - {duration: 1.0, num_of_controls: 2}

        max_acc: {x: 0.5, y:  0.5, theta:  1.0}
        max_vel: {x:  0.5, y:  0.3, theta:  0.75}
        min_vel: {x: -0.25, y: -0.3, theta: -0.75}

        is_unicycle: false # if unicycle make goal_state_intercept_angle non zero

        weights:
            goal_state:
                pos: {x: 10.0, y: 10.0, theta: 10.0}
                vel: {x: 20.0, y: 10.0, theta: 10.0}
            normal_state:
                pos: {x: 0.0, y: 0.0, theta: 0.0}
                vel: {x: 0.0, y: 0.0, theta: 0.0}
            goal_state_intercept_angle: 0.0

            acc_limit: {x: 10000.0, y: 10000.0, theta: 10000.0}
            vel_limit: {x: 1000.0, y: 1000.0, theta: 1000.0}

            laser_pts_repulsion: 300.0

        footprint: {min_x: -0.7, max_x: 0.43, min_y: -0.33, max_y: 0.33}
        min_inflation_dist: 0.28
        max_inflation_dist: 0.95

        initial_guess:
            num_of_vel_x_samples: 4
            num_of_vel_y_samples: 5
            num_of_vel_theta_samples: 11
            quadratic_theta_samples: true
            apply_elliptical_filter: true
            num_of_controls: 1
            sample_time: 4.0
            states_per_control: 4
            frequency: 3

        shorten_control_horizon: true

        reverse_motion_goal_threshold_linear: 0.3
        reverse_motion_goal_threshold_heading: 1.0

    required_inputs:
        laser: "combined_laser"
        velocity: "velocity"
        localization: "mcl_optimal_raycast"

    outputs:
        markers: "behavior_markers"

lane_following:
    type: "lane_following"
    control:
        control_horizon:
            - {duration: 0.6, num_of_controls: 3}
            - {duration: 1.4, num_of_controls: 4}
            - {duration: 2.0, num_of_controls: 4}

        max_acc: {x: 0.5, y:  0.5, theta:  1.0}
        max_vel: {x: 1.25, y:  0.2, theta:  0.8}
        min_vel: {x: 0.0, y: -0.2, theta: -0.8}

        normal_target_vel: 1.25
        slow_target_vel: 0.25

        weights:
            goal_state:
                pos: {x: 0.0, y: 0.0, theta: 20.0}
                vel: {x: 10.0, y: 5.0, theta: 5.0}
            ideal_path_perp_dist: 20.0
            lane_wall_repulsion: 100.0

            acc_limit: {x: 10000.0, y: 10000.0, theta: 10000.0}
            vel_limit: {x: 1000.0, y: 1000.0, theta: 1000.0}

            laser_pts_repulsion: 100.0

        footprint: {min_x: -0.7, max_x: 0.7, min_y: -0.33, max_y: 0.33}
        inflation_dist: 0.27

        initial_guess:
            custom:
                kp_vel: {x: 1.0, y: 0.5, theta: 1.0}
                num_of_samples: 8
                sample_time: 0.5

    perception:
        laser_filter_box: {min_x: -1.0, max_x: 100.0, min_y: -5.0, max_y: 5.0}
        corner_pt_spline_offset_dist: 2.0
        corner_pt_spline_resolution_dist: 0.1
        lane_wall_dist: 0.2
        lane_index_lookahead: 20

    transition_condition:
        pre:
            goal_tolerance_linear: 1.0
            goal_tolerance_angular: 0.5
            max_vel: {x: 1.0, y: 0.2, theta: 0.1}
            forward_tf_x_min: 0.5
            forward_tf_x_max: 1.0
        post:
            goal_tolerance_linear: 1.5
            goal_tolerance_heading: 0.8

    required_inputs:
        laser: "combined_laser"
        velocity: "velocity"
        localization: "mcl_optimal_raycast"
        kelojson_map: "kelojson_map"

    outputs:
        markers: "behavior_markers"
        traffic_request: "traffic_request"
        alarm: "alarm"

enter_transfer_station:
    type: "transfer_station"
    control:
        control_horizon:
            - {duration: 0.2, num_of_controls: 2}
            - {duration: 0.8, num_of_controls: 4}

        max_acc: {x: 0.5, y:  0.5, theta:  1.0}
        max_vel: {x: 0.3, y:  0.1, theta:  0.2}
        min_vel: {x: 0.0, y: -0.1, theta: -0.2}

        mockup: false

        p_controller_states:
            - success_box: {min_x: -1.2, max_x: -0.8, min_y: -0.02, max_y:  0.02}
              success_theta_tolerance: 0.02
              valid_box: {min_x: -2.0, max_x: -0.7, min_y: -0.4, max_y:  0.4}
              valid_theta_tolerance: 0.5
              kp_vel: {x: 0.4, y: 1.0, theta: 1.0}
              max_acc: {x: 0.5, y:  0.5, theta:  1.0}
              max_vel: {x: 0.15, y:  0.1, theta:  0.5}
              min_vel: {x: 0.0, y: -0.1, theta: -0.5}
            - success_box: {min_x: -0.02, max_x: 0.05, min_y: -0.03, max_y:  0.03}
              success_theta_tolerance: 0.02
              valid_box: {min_x: -1.25, max_x: 0.06, min_y: -0.05, max_y:  0.05}
              valid_theta_tolerance: 0.1
              kp_vel: {x: 0.75, y: 0.5, theta: 0.5}
              max_acc: {x: 0.2, y:  0.2, theta:  0.5}
              max_vel: {x: 0.15, y:  0.1, theta:  0.2}
              min_vel: {x: 0.02, y: -0.1, theta: -0.2}

        footprint:
            - {x:  0.426, y:  0.326}
            - {x: -0.7,   y:  0.326}
            - {x: -0.7,   y: -0.326}
            - {x:  0.426, y: -0.326}
        footprint_padding: -0.015

    perception:
        laser_filter_box: {min_x: -1.0, max_x: 5.0, min_y: -2.0, max_y: 2.0}
        station_polygon_inflation_dist: 0.5
        # clustering params
        cluster_distance_threshold: 0.05
        min_cluster_size: 5
        regression_error_threshold: 0.1
        # line filtering params
        min_line_angle: 1.1
        max_line_angle: 2.1
        min_line_length: 0.6
        max_line_length: 1.1
        # post processing
        prev_pose_linear_tolerance: 0.2
        prev_pose_angular_tolerance: 0.2
        pose_buffer_max_size: 5
        perception_pose_to_goal_tf: {x: -0.46, y: -0.005, theta: -0.0}

    transition_condition:
        pre:
            bounding_box: {min_x: -1.5, max_x: -0.8, min_y: -0.3, max_y: 0.3}
            angular_tolerance: 0.1
            goal_tf: {x: 1.23, y: 0.0, theta: 0.0}

    perception_retry_counter_threshold: 30
    control_retry_counter_threshold: 30

    required_inputs:
        velocity: "velocity"
        localization: "mcl_optimal_raycast"
        front_laser: "front_laser"
        back_laser: "back_laser"

    outputs:
        markers: "behavior_markers"
        robot_pose: "robot_pose_in_goal_frame"

exit_transfer_station:
    type: "transfer_station"
    control:
        control_horizon:
            - {duration: 0.2, num_of_controls: 2}
            - {duration: 0.8, num_of_controls: 4}

        max_acc: {x:  0.5, y:  0.5, theta:  1.0}
        max_vel: {x:  0.05, y:  0.1, theta:  0.2}
        min_vel: {x: -0.3, y: -0.1, theta: -0.2}

        mockup: false

        p_controller_states:
            - success_box: {min_x: 0.3, max_x: 0.7, min_y: -0.02, max_y:  0.02}
              success_theta_tolerance: 0.02
              valid_box: {min_x: 0.2, max_x: 2.0, min_y: -0.05, max_y:  0.05}
              valid_theta_tolerance: 0.15
              kp_vel: {x: 0.2, y: 0.2, theta: 1.0}
              max_acc: {x:  0.05, y:  0.2, theta:  0.5}
              max_vel: {x:  0.0, y:  0.1, theta:  0.2}
              min_vel: {x: -0.2, y: -0.1, theta: -0.2}
            - success_box: {min_x: -0.1, max_x: 0.1, min_y: -0.1, max_y:  0.1}
              success_theta_tolerance: 0.1
              valid_box: {min_x: -0.15, max_x: 1.0, min_y: -0.2, max_y:  0.2}
              valid_theta_tolerance: 0.2
              kp_vel: {x: 0.75, y: 1.0, theta: 1.0}
              max_acc: {x:  0.5, y:  0.1, theta:  1.0}
              max_vel: {x:  0.0, y:  0.02, theta:  0.5}
              min_vel: {x: -0.2, y: -0.02, theta: -0.5}

        footprint:
            - {x:  0.356, y:  0.326}
            - {x: -1.0,   y:  0.326}
            - {x: -1.0,   y: -0.326}
            - {x:  0.356, y: -0.326}
        footprint_padding: -0.03

    perception:
        laser_filter_box: {min_x: -5.0, max_x: 5.0, min_y: -2.0, max_y: 2.0}
        station_polygon_inflation_dist: 0.5
        # clustering params
        cluster_distance_threshold: 0.1
        min_cluster_size: 5
        regression_error_threshold: 0.1
        # line filtering params
        min_line_angle: 1.1
        max_line_angle: 2.1
        min_line_length: 0.5
        max_line_length: 1.1
        # post processing
        prev_pose_linear_tolerance: 0.2
        prev_pose_angular_tolerance: 0.2
        pose_buffer_max_size: 5
        perception_pose_to_goal_tf: {x: -1.8, y: 0.0, theta: -0.0}

    transition_condition:
        pre:
            bounding_box: {min_x: -0.5, max_x: 0.8, min_y: -0.3, max_y: 0.3}
            angular_tolerance: 0.3
            goal_tf: {x: 0.52, y: 0.0, theta: 0.0}

    perception_retry_counter_threshold: 30
    control_retry_counter_threshold: 30

    required_inputs:
        velocity: "velocity"
        localization: "mcl_optimal_raycast"
        front_laser: "front_laser"
        back_laser: "back_laser"

    outputs:
        markers: "behavior_markers"
        robot_pose: "robot_pose_in_goal_frame"

gripper_close:
    type: "gripper"
    open: false
    control:
        control_horizon:
            - {duration: 1.0, num_of_controls: 2}

        max_acc: {x: 0.1, y: 0.1, theta: 0.1}

        mockup: false

    required_inputs:
        velocity: "velocity"
        gripper: "gripper"

    outputs:
        markers: "behavior_markers"
        gripper: "gripper"

gripper_open:
    type: "gripper"
    open: true
    control:
        control_horizon:
            - {duration: 1.0, num_of_controls: 2}

        max_acc: {x: 0.1, y: 0.1, theta: 0.1}

        mockup: false

    required_inputs:
        velocity: "velocity"
        gripper: "gripper"

    outputs:
        markers: "behavior_markers"
        gripper: "gripper"

robile_charging:
    type: "robile_charging"
    mockup: false
    ignore_input: true

    wait_duration_before_start_charge: 1.0
    wait_duration_after_stop_charge: 1.0

    control:
        control_horizon:
            - {duration: 1.0, num_of_controls: 2}

        max_acc: {x: 0.1, y: 0.1, theta: 0.1}

    required_inputs:
        velocity: "velocity"
        # robile_master_battery: "robile_master_battery"

    outputs:
        markers: "behavior_markers"
        robile_master_battery: "robile_master_battery"

In the ImGui picture provided, there is a button labeled 'behaviors corresponding to behavior.yaml' in the image. Clicking this button should ideally open a new window, but when compiled, it results in a core dump. Where is the wrong in my code?

Also, the code shown seems to have difficulties when converting YAML input data to various data types, such as int, double, and bool. It should be that the conversions must strictly match the data types, meaning int should be converted to int, double to double, and bool to bool. However, in my case, it will convert int to double or double to int. How to resolve this issue, ensure that the data type conversions are consistent and correctly handled?

lundi 30 octobre 2023

C++ Class, the member object in the Class can be created using ’this‘ pointer outside the construct func?

#include<stdio.h>
#include <iostream>
class myClass;

struct Member
{
    Member(myClass* m)
    {
        std::cout << "member is created" << std::endl;
        my_class = m;
    }
    myClass* my_class;
};



class myClass
{
public:
    myClass()
    {
        std::cout << "myClass is created" << std::endl;
    }

    Member my_member =  Member(this);
    int x = 1;
};

void test() 
{
    myClass mClass;
    std::cout << mClass.my_member.my_class->my_member.my_class->my_member.my_class->x;
}

int main()
{
    test();
}

i define a Member Class, and it can construct with a myClass pointer. importantly, i define the my_member outside the myClass constructor, will it lead to recursive construction? the code above runs well, is it explainable? when does the 'this' pointer is created and can be used?

dimanche 29 octobre 2023

Iterating to arbitrary element within operator++ in class Iterator

What’s the best design for building an iterator that has to iterate further within the operator++ on a dynamically allocated list.

Meaning, for example, that I want the operator++ to go to the next element with some arbitrary property. i.e. the iterator may go forward more than one element.

Is storing the size of the list inside the iterator class proper design?

How to make this function return the highest value in the array

I was trying to make this function return the highest element in the array. I input elements in the array using pointer. After the code run, it only displays the first element in the array. I tried using this code int SIZE = sizeof(ptr) / sizeof(ptr[0]); in the main function, but i got a variable redefinition error. please help

 #include <iostream>


   using namespace std;

   double gethighest(const double ptr[], int SIZE)
     {
double highest = ptr[0];
for (int count = 0; count < SIZE; count++)
   {

    if (ptr[count] > highest)
        highest = ptr[count];

    return highest;
    }
      }
   int main()
          {
double* ptr = nullptr;
int SIZE;
double value;
cout << "Enter the size of the array" << endl;
cin >> SIZE;
ptr = new double[SIZE];

  for (int count = 0; count < SIZE; count++)
         {
      cout << "Enter the values of the array: ";
      cin >> ptr[count];
      while (ptr[count] < 0)
       {
          cout << "Invalid entry, enter a positive value: ";
          cin >> ptr[count];
       }
             }
 
  double highest = gethighest(ptr, SIZE);
  


    cout << "The highest value of the array is: " << highest;

          }
    

Simple Stack and Map program stuck

What is wrong with this simple program and why it is going in hang status on cpp.sh

#include <stack>
#include <map>
#include <set>
#include <iostream>

using namespace std;

int main()
{    
    string expression {")"};    
    stack<char> mystack;
    map<char, char> mymap{ {'(', ')'}, {'[', ']'}, {'{', '}'} };
    set<char> myset{ ')', ']', '}'};

    for(auto &i: expression)
    {
        if(mymap.count(i) == 1)
        {
            mystack.push(i);
        }
        
        else if(myset.count(i) == 1)
        {
            cout << "Received :: " << i << endl;
            
            if(mymap.at(mystack.top()) == i)
            {
                cout << " Popped: " << mystack.top() << endl;
                mystack.pop();
            }
            else
            {
                cout << "Non Balanced" << endl;
                break;
            }
        }
    }
    if(mystack.size() != 0)
    {
        cout << "Non Balanced" << endl;
    }
    return 0;
}

samedi 28 octobre 2023

Is std::uniform_int_distribution

According to the cppreference documentation on std::uniform_int_distribution,

The effect is undefined if [IntType] is not one of: short, int, long, long long, unsigned short, unsigned int, unsigned long, or unsigned long long.

I'm not sure of how this applies to std::size_t - namely with these 3 confusions:

  1. On one hand, std::size_t, as far as I know, is usually a typedef of one of the unsigned types in that list.
  2. However, I'm not sure if the standard mandates that always be the case.
  3. I'm not sure if "undefined if [IntType] is not one of: ..." implies IntType has to nominally match something from that list (the type has to explicitly be one of those, by name) or whether it can structurally match (so a typedef to one of those is considered acceptable as well).

Is std::uniform_int_distribution<std::size_t> undefined behavior?

Custom operator for SDL

I have a class, it have a operator which returns a SDL_Renderer

class renderer {
public:
  explicit renderer(SDL_Window *window);
  ~renderer() = default;

  operator const SDL_Renderer *() const;

private:
  renderer_ptr _renderer;
};

I would like to use it on a SDL_CreateTextureFromSurface.

SDL_CreateTextureFromSurface(r, surface)

Where r is const std::shared_ptr<renderer> r

I tried other ways, like

SDL_CreateTextureFromSurface(r.get(), surface)

and

SDL_CreateTextureFromSurface(*r, surface)

But no luck.

I remember that this used to work, but nowadays my C++ skills have rusted.

How can I use this operator while using a shared_ptr?

Overloading operator>> with chaining taking multiple inputs [duplicate]

Aim of the below code is to take input strings of any length from cin (or for tha matter input stream)

istream& operator>>(istream& is, MyString& rhs)
{
    cout << __PRETTY_FUNCTION__ << endl;
    
    size_t inpChunkSize{256};
    size_t allocCap{256};
    size_t totReadBytes{0};

    char *tmpHoldingBuff{nullptr};


    char *input = new char[allocCap];

    while(!cin.eof())
    {
        cin.read(input + totReadBytes, inpChunkSize);
        totReadBytes += cin.gcount();

        // if 256 bytes have been used up, then new chunk has to be allocated. 
        if (cin.gcount() == inpChunkSize)
        {
            allocCap += inpChunkSize;

            tmpHoldingBuff = new char[allocCap];
            strncpy(tmpHoldingBuff, input, totReadBytes);
            
            delete [] input;
            
            input = tmpHoldingBuff;
        }
    }
    
    rhs = MyString(input);
    rhs.display();

    return is;
}

int main(int argc, char *argv[])
{
    
    MyString s1, s2;
    cin >> s1 >> s2;
    
    return 0;
}

I want s1 and s2 to be input just like we do for say int's.

But I see that once I input one string and do ^D, then input for s2 is never asked and it is initialised to null

What wrong is happening here ?

$ ./Misc/OLNonMembFuncs 
std::istream& operator>>(std::istream&, MyString&)
This is s1^D(This is s1)
std::istream& operator>>(std::istream&, MyString&)
()

vendredi 27 octobre 2023

is COM's IUnknown useless with the advent of unique_ptr and shared_ptr?

Is there any reason to use COM's IUnknown interface in C++11 or later ?

AFAIK COM was created as sort of a better C++98, does C++11 make COM obsolete?

Am I right that after C++11 the majority of COM code is legacy?

Assigning std::variant from sub-variant

Given a std::variant<A,B,C,...> is it possible to assign from a aub-type std::variant<A, B>?

On MSVC 2019 I get "no suitable user defined conversion" on direct assignment. With std::visit one could implement the folowing:

std::variant<A, B, C> x;
std::variant<A, B> y;
std::visit([&x](const auto& value) {
    x = value;
}, y);

Is there a more elegant way to implement such an assignment?

What is the purpose of defining an alias of the type of struct itself in it's own struct definition

What is the purpose of the alias definition of type aliasing struct type __variant_idx_cookie itself in following struct definition of __variant_idx_cookie?

struct __variant_idx_cookie { using type = __variant_idx_cookie; };

jeudi 26 octobre 2023

c++, how can i delete one element of map whin the element itself

i have two classes in differnt source file, class A in a.hpp and a.cpp, class B in b.hpp and b.cpp, A is a singleton class, it create B object, and store b in a map, when B object created, it create a thread, and i want b can remove itself from that map which is A's member when the thread run out, but my program throw a exception.

// main.cpp

#include <iostream>
#include "a.hpp"

int main() {
    A::get_instance().add(1);
    int pause = 0; std::cin >> pause;
    return 0;
}
// a.hpp

#ifndef __A_HPP__
#define __A_HPP__

#include <unordered_map>
#include <memory>
#include "b.hpp"

class A {
public:
    void add(int i);
    void remove(int i);
    static A& get_instance();
private:
    std::unordered_map<int, std::shared_ptr<B>> map_b_;
};


#endif
// a.cpp

#include "a.hpp"

void A::add(int i) {
    std::cout << "add: " << i << std::endl;
    map_b_[i] = std::move(std::make_shared<B>(i));
    std::this_thread::sleep_for(3s);
}
void A::remove(int i) {
    std::cout << "remove: " << i << std::endl;
    if (map_b_.count(i)) {
        map_b_.erase(i);
    }
}
A& A::get_instance() {
    static A instance;
    return instance;
}
// b.hpp

#ifndef __B_HPP__
#define __B_HPP__

#include <thread>
#include <chrono>
#include <atomic>
#include <iostream>
using namespace std::chrono_literals;

class B {
public:
    B(int id);
    ~B();
    void stop();
    void run();
private:
    std::atomic<bool> run_flag_;
    std::thread thr_;
    int id_;
};


#endif
b.cpp

#include "b.hpp"
#include "a.hpp"

B::B(int id) {
    id_ = id;
    run_flag_ = true;
    std::thread t(&B::run, this);
    thr_ = std::move(t);
}
B::~B() {
        std::cout << "~B(): " << id_ << std::endl;
    stop();
}
void B::stop() {
    run_flag_ = false;
    if (thr_.joinable()) {
        thr_.join();
    }
}
void B::run() {
    int count = 0;
    while (count < 3 && run_flag_) {
        std::cout << "processing id: " << id_ << std::endl;
        std::this_thread::sleep_for(1s);
        count ++;
    }
    A::get_instance().remove(id_);
}
# CMakeLists.txt
# CMake 最低版本号要求
cmake_minimum_required (VERSION 2.8)

# 项目信息
project (demo)
SET(CMAKE_BUILD_TYPE "Debug")
# 指定生成目标
add_executable(
    ${PROJECT_NAME} 
    main.cpp
    a.cpp
    b.cpp
)
find_package(Threads REQUIRED) 
target_link_libraries(${PROJECT_NAME} Threads::Threads)

i have run the code in my linux docker, but it throw an error, like this, i want know how can i do it to remove one itself from container.

root@53d8817a43a8:~/test-cpp/build# ./demo
add: 1
processing id: 1
processing id: 1
processing id: 1
remove: 1
~B(): 1
terminate called after throwing an instance of 'std::system_error'
  what():  Resource deadlock avoided
Aborted

mercredi 25 octobre 2023

type deducing only the arguments types for a variadic template

I am trying to apply a variadic template function to a tuple. I found following solution that works for C++14 (see https://stackoverflow.com/a/37100646/2712726).

#include <tuple>
template <typename T, typename U> void my_func(T &&t, U &&u) {}
int main(int argc, char *argv[argc]) {
  std::tuple<int, float> my_tuple;
  std::apply([](auto &&... args) { my_func(args...); }, my_tuple);
  return 0;
}

I also found many solutions for C++11 but non of those compiled. So I implemented my own solution, which also does not compile.

Following code shows my attempt. My question is why type deduction in the last statement u.apply(f) fails and if I can help the compiler somehow.

#include <iostream>
#include <tuple>

using namespace std;

template <typename... T>
struct parameter_pack : public parameter_pack<T>... {
    parameter_pack(const T&... t) : parameter_pack<T>(t)... {}

    // C++11
    template <template <typename...> class Func>
    void apply(Func<T...> f) {
        f(h, parameter_pack<T>::h...);
    }
    //c++14 works
    // template <typename Func>
    // void apply(Func f) {
    //     f(parameter_pack<T>::h...);
    // }
};

template <typename H>
struct parameter_pack<H> {
    parameter_pack(const H& h) : h(h) {}
    const H& h;
};

template <typename... T>
parameter_pack<T...> make_parameter_pack(const T&... t) {
    return parameter_pack<T...>(t...);
}

// test function f()
template <typename H>
void f(const H& h) {
    std::cout << h << std::endl;
}

template <typename H, typename... T>
void f(const H& h, const T&... t) {
    f(h);
    f(t...);
}

int main() {
    auto u = make_parameter_pack(1, 1.1, "hello");
    std::cout << std::endl;
    // C++11
    u.apply(f); // compiler error

    //C++14 works
    // auto lambda = [&](const auto&... args) {
    //    f(args...);
    // };
    // u.apply(lambda);
}

The compiler says:

<source>:49:7: error: no matching member function for call to 'apply'
   49 |     u.apply(f);
      |     ~~^~~~~
<source>:12:10: note: candidate template ignored: couldn't infer template argument 'Func'
   12 |     void apply(Func<T...> f) {
      |          ^
1 error generated.
Compiler returned: 1

mardi 24 octobre 2023

Catching a Diamond Of Death Exception (boost::system::system_error and std::system_error)

I have a library, and I wish to leverage the design of boost::system::system_error. C++ adopted this design in 2011 with std::system_error. I would like for client code to have the option of working with Boost exceptions or with Standard exceptions. Therefore, when my library code needs to communicate an error, I throw my own exception type that inherits from boost::system::system_error and std::system_error:

class my_exception : public std::system_error, public boost::system::system_error {
  // implementation
};

Unfortunately, this is a Deadly Diamond of Death with respect to the common base class std::runtime_error. Nonetheless, client code is able to catch these exceptions as either std::system_error or as boost::system::system_error:

try {
  a_function_that_might_throw_my_exception();
} catch (const std::system_error& ex) {
  // Works as intended - correctly catches a reference to the `my_exception` object
}

try {
  a_function_that_might_throw_my_exception();
} catch (const boost::system::system_error& ex) {
  // Also works
}

However, an expression of type my_exception cannot bind to a reference to std::runtime_error (or it's base class, std::exception), due to the ambiguity of the diamond: should it bind to std::system_error's base class object, or should it bind to boost::system::system_error's base class object? The result is that the thrown object is not caught at all:

try {
} catch (const std::runtime_error& ex) {
  // Doesn't catch here!
} catch (...) {
  std::printf("Sadness\n");
}

Godbolt demonstration

The main question: Is there a way to communicate to the compiler which base class subobject shoud be preferred when binding a deadly-diamond-type to a reference-to-base? In normal code you could static_cast<const std::runtime_error&>(ex) or static_cast<const boost::system::system_error&>(ex), but I can't write a static_cast into the compiler's magical exception-handling code.

Secondary question: Is there a better way make my code interoperable with both std:: and boost::system:: error handling?

C++, ROS to ROS2 keeping compatibility for service callbacks

I've been working on a framework on top of ROS for the last couple of years and now I'm trying to make it compatible with both ROS and ROS2. For now I fixed the CMAKE the namespaces and the headears for messages, services and actions.

Now I need to work on the service callbacks.

Migration guide from ROS1 to ROS2

This is the guide that shows how it should be done in ROS2 compared to ROS1

// In ROS 1 it goes something like this
#include "nav_msgs/GetMap.h"

bool service_callback(
    nav_msgs::GetMap::Request & request,
    nav_msgs::GetMap::Response & response)
{
    /* if failed throw an exception (or return false) */
    /* if success */
    return true;
}
// In ROS 2 it should go like this
#include "nav_msgs/srv/get_map.hpp"  // This has been fixed

void service_callback(
    const std::shared_ptr<nav_msgs::srv::GetMap::Request> request,
    std::shared_ptr<nav_msgs::srv::GetMap::Response> response)
{
    /* if failed just throw an exception */
    /* if success */
    return;
}

The problem is that the ROS1 solution uses reference to the objects for both request and response, i looked at the available overloads for the callback and there are none that allowes you to use shared pointers instead. ROS2 uses shared pointers where the request is const and the response is not.

I already have my method that let me get instantiate a service with callback:

/*-----------------------------------------------------------------------------------------
 : GET SERVER : Returns a Server object
 *-----------------------------------------------------------------------------------------
 return a service server with normalized methods
 - server   : the server object to store the advertised service into
 - key      : the name of the topic (regardless of its namespace or node)
 - callback : the callback for the advertised service, an object method that takes a reference of both request and response
 - that     : pointer to the object that will receive messages through its callback
 - node     : the node or namespace this publisher is declared into
 return "true" if the serviceServer has been instantiated correctly, "false" otherwise
 *-----------------------------------------------------------------------------------------
 e.g.
 (key="data", node="") -> the publisher will be initialized in the handler namespace: /node-name/data
 (key="/data", node="") -> the publisher will be initialized in the root: /data
 (key=<any>, node="node-name") -> the publisher will be initialized in the specified node namespace: /node-name-namespace/<any>
 */
template <typename MReq, typename MRes, class N>
inline bool getServer(Server& server, string key, bool(N::*callback)(MReq &, MRes &), N* that,
                        const string& node=string()) {
    try {
        if (node.length() > 0 && !this->addNamespace(node, key)) return false;
        lock_guard<boost::mutex> lock(this->get_mutex());
        AdvertiseServiceOptions ops;
        ops.template init<MReq, MRes>(key, bind(callback, that, _1, _2));
        server = Server(key, this->advertiseService(ops));
        return true;
    } catch (...) {
        tgo::Exception exc = tgo::getException( std::current_exception() );
        std::cout << "GET SERVER : " << node << "/" << key << " : " << exc.what() << std::endl;
        return false;
    }
};

Where the Server class extends ServiceServer from ROS1.

Is there a workaround you may think of?

Since in this method I use a bind, I tried to convert the two placeholders to MReq and MRes respectively but the compiler doesn't seem to like it...

ops.template init<MReq, MRes>(key, bind(callback, that, make_shared<MReq>(_1), make_shared<MRes>(_2)));

it gives me this error

/usr/include/c++/11/ext/new_allocator.h: In instantiation of ‘void __gnu_cxx::new_allocator<_Tp>::construct(_Up*, _Args&& ...) [with _Up = double; _Args = {const std::_Placeholder<1>&}; _Tp = double]’:
/usr/include/c++/11/bits/alloc_traits.h:516:17:   required from ‘static void std::allocator_traits<std::allocator<_CharT> >::construct(std::allocator_traits<std::allocator<_CharT> >::allocator_type&, _Up*, _Args&& ...) [with _Up = double; _Args = {const std::_Placeholder<1>&}; _Tp = double; std::allocator_traits<std::allocator<_CharT> >::allocator_type = std::allocator<double>]’
/usr/include/c++/11/bits/shared_ptr_base.h:519:39:   required from ‘std::_Sp_counted_ptr_inplace<_Tp, _Alloc, _Lp>::_Sp_counted_ptr_inplace(_Alloc, _Args&& ...) [with _Args = {const std::_Placeholder<1>&}; _Tp = double; _Alloc = std::allocator<double>; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/11/bits/shared_ptr_base.h:650:16:   required from ‘std::__shared_count<_Lp>::__shared_count(_Tp*&, std::_Sp_alloc_shared_tag<_Alloc>, _Args&& ...) [with _Tp = double; _Alloc = std::allocator<double>; _Args = {const std::_Placeholder<1>&}; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/11/bits/shared_ptr_base.h:1342:14:   required from ‘std::__shared_ptr<_Tp, _Lp>::__shared_ptr(std::_Sp_alloc_shared_tag<_Tp>, _Args&& ...) [with _Alloc = std::allocator<double>; _Args = {const std::_Placeholder<1>&}; _Tp = double; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/11/bits/shared_ptr.h:409:59:   required from ‘std::shared_ptr<_Tp>::shared_ptr(std::_Sp_alloc_shared_tag<_Tp>, _Args&& ...) [with _Alloc = std::allocator<double>; _Args = {const std::_Placeholder<1>&}; _Tp = double]’
/usr/include/c++/11/bits/shared_ptr.h:862:14:   required from ‘std::shared_ptr<_Tp> std::allocate_shared(const _Alloc&, _Args&& ...) [with _Tp = double; _Alloc = std::allocator<double>; _Args = {const std::_Placeholder<1>&}]’
/usr/include/c++/11/bits/shared_ptr.h:878:39:   required from ‘std::shared_ptr<_Tp> std::make_shared(_Args&& ...) [with _Tp = double; _Args = {const std::_Placeholder<1>&}]’
main.cpp:29:58:   required from here
/usr/include/c++/11/ext/new_allocator.h:162:11: error: cannot convert ‘const std::_Placeholder<1>’ to ‘double’ in initialization
  162 |         { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
      |           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I hoped to start using shared pointers instead of references here on and make ROS1 as well use them exploiting the bind object.

I would be ok using something like this:

template <typename MReq, typename MRes, class N>
inline bool getServer(Server& server, string key,
                      bool(N::*callback)(const shared_ptr<MReq>, shared_ptr<MRes>), N* that,
                      const string& node=string()) {
    try {
        if (node.length() > 0 && !this->addNamespace(node, key)) return false;
        lock_guard<boost::mutex> lock(this->get_mutex());
        AdvertiseServiceOptions ops;
        auto binded_method = bind(callback, that, make_shared<MReq>(_1), make_shared<MRes>(_2));
        ops.template init<MReq, MRes>(key, binded_method);
        server = Server(key, this->advertiseService(ops));
        return true;
    } catch (...) {
        tgo::Exception exc = tgo::getException( std::current_exception() );
        std::cout << "GET SERVER : " << node << "/" << key << " : " << exc.what() << std::endl;
        return false;
    }
};

EDIT

I'm checking for lambdas but since this is a templated function I'm not sure it's going to work.

lundi 23 octobre 2023

How to link c++11 std::chronos to use clock_gettime()

I want the std::chrono::steady_clock and std::chrono::system_clock to use POSIX functions clock_gettime/clock_settime from the <time.h>, instead it is picking up _gettimeofday() from <sys/time.h>.

When I peaked into the src of stdlib here: https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/src/c%2B%2B11/chrono.cc And the posix header file <time.h> in the compiler, I concurred that I need to add the following flags to the make file (to allow std::chrono to use clock_gettime()).

CXXFLAGS +=
-D_GLIBCXX_USE_CLOCK_MONOTONIC
-D_GLIBCXX_USE_CLOCK_REALTIME
-D_POSIX_TIMERS
-D_POSIX_MONOTONIC_CLOCK \

I defined these functions in time.c file and included them in the build. Linked them as given below:

LIB_NAMES +=
<my_libraries>
c \

I'm using gcc 8.3 & newlibc.

I expect the calls to std::chrono::steady_clock::now(), std::chrono::system_clock::now() to use clock_gettime() function instead of _gettimeofday().

I have an accurate hardware time that is being accessed from clock_gettime(). I have verified this by directly calling it in application functions. I'd like to use c++ std::chrono instead.

What am I missing?

Multiple definitions of ... first defined here

When I compile the program:

g++ -std=c++11 SpringMass.cpp SpringDamperMass.cpp main.cpp -o main

...I get multiple errors with the same pattern:

usr/bin/ld: /tmp/cciHWp7J.o:(.bss+0x0): multiple definition of `vec'; /tmp/ccicqdBO.o:(.bss+0x0): first defined here
/usr/bin/ld: /tmp/cciHWp7J.o:(.bss+0x40): multiple definition of `tes'; /tmp/ccicqdBO.o:(.bss+0x40): first defined here
/usr/bin/ld: /tmp/cciHWp7J.o:(.rodata+0x8): multiple definition of `SpringMass::GRAVITY'; /tmp/ccicqdBO.o:(.rodata+0x8): first defined here
/usr/bin/ld: /tmp/cciHWp7J.o:(.rodata+0x10): multiple definition of `SpringMass::SPRING_CONST'; /tmp/ccicqdBO.o:(.rodata+0x10): first defined here
/usr/bin/ld: /tmp/cciHWp7J.o:(.rodata+0x18): multiple definition of `SpringMass::MASS'; /tmp/ccicqdBO.o:(.rodata+0x18): first defined here
/usr/bin/ld: /tmp/cciHWp7J.o:(.rodata+0x20): multiple definition of `SpringMass::x_0'; /tmp/ccicqdBO.o:(.rodata+0x20): first defined here
/usr/bin/ld: /tmp/cc92aQWL.o:(.bss+0x0): multiple definition of `vec'; /tmp/ccicqdBO.o:(.bss+0x0): first defined here
/usr/bin/ld: /tmp/cc92aQWL.o:(.bss+0x40): multiple definition of `tes'; /tmp/ccicqdBO.o:(.bss+0x40): first defined here
/usr/bin/ld: /tmp/cc92aQWL.o:(.bss+0x60): multiple definition of `vec_damp'; /tmp/cciHWp7J.o:(.bss+0x60): first defined here
/usr/bin/ld: /tmp/cc92aQWL.o:(.bss+0xa0): multiple definition of `time_damp'; /tmp/cciHWp7J.o:(.bss+0xa0): first defined here
/usr/bin/ld: /tmp/ccicqdBO.o: in function `SpringMass::SpringMass(double, double, double, double)':
SpringMass.cpp:(.text+0x23): undefined reference to `vtable for SpringMass'
/usr/bin/ld: /tmp/cciHWp7J.o: in function `SpringDamperMass::SpringDamperMass(double, double, double, double, double)':
SpringDamperMass.cpp:(.text+0x5c): undefined reference to `vtable for SpringDamperMass'
/usr/bin/ld: /tmp/cc92aQWL.o: in function `main':
main.cpp:(.text+0x222): undefined reference to `SpringMass::~SpringMass()'
/usr/bin/ld: main.cpp:(.text+0x478): undefined reference to `SpringDamperMass::~SpringDamperMass()'
/usr/bin/ld: main.cpp:(.text+0x4ed): undefined reference to `SpringMass::~SpringMass()'
/usr/bin/ld: main.cpp:(.text+0x532): undefined reference to `SpringDamperMass::~SpringDamperMass()'
collect2: error: ld returned 1 exit status

How can I solve this issue?

The idea is to simulate spring-mass system.

Why would non-inline namespaces not work for library versioning?

In this answer to this question What are inline namespaces for?, inline namespaces are referred to as a mechanism of library versioning.

I understand the overall approach mentioned in the answers using inline namespace, but one thing that is not clear is why could we not use the following approach for library versioning with non-inline namespaces?

In the first version, have a definition like the following.

#include <iostream>

namespace foo {
    template <typename T>
    void bar(T t) {
        std::cout << "bar v1 - " << t;
    }
}

And in the next version, place the older version in a nested namespace v1 and the newer version in its place.

#include <iostream>

namespace foo {
    namespace v1 {
        template <typename T>
        void bar(T t) {
            std::cout << "bar v1 - " << t;
        }
    }

    template <typename T>
    void bar(T t) {
        std::cout << "bar v2 - " << t;
    }

}

All correct usages of foo::bar() will automatically get upgraded to v2, and would work correctly against v2. For any users of foo::bar(), if they still want to link to v1 then they can change the code to foo::v1::bar(), just as is suggested in the linked answer to the question, where they have used inline namespaces for the solution.

What is wrong or missing or would not work, with the above approach that doesn't use inline-namespaces?

dimanche 22 octobre 2023

In the function template, char * arguments cannot match explicit specialization const char * parameters

IN the book C++ Primer Plus I see a form enter image description here

and when I write my code below

#include<iostream>
#include<cstring>
using namespace std;
template<typename T>
T maxn(T arr[],int n);

template<>
const char*  maxn<const char* >(const char*arr[] ,int n);

template<>
char*  maxn<char* >(char*arr[] ,int n);

int main()
{   
    int arr1[6]={1,2,3,4,5,6};
    double arr2[4]={1.1,2.2,3.3,4.4};
    char* arr3[5]={
        "a",
        "hijkl",
        "def",
        "bc",
        "lmno",
    };
    
    cout << maxn(arr3,4) << endl;
    cin.get();
    return 0;
}
template<typename T>            //template A  general template
T maxn(T arr[],int n)
{
    T max=0;
    for(int i=0;i<n;i++)
    max = max > arr[i]?max:arr[i];
    return max;
}

template<>             //template B   explicit specialization  with const
const char*  maxn<const char* >(const char* arr[] ,int n)  
{                                                      
    const char*  pm=arr[0];                           
                                                       
    for(int i=0;i<n;i++)
    {
        if(strlen(pm)<strlen(arr[i]))
        pm=arr[i];
    }
    return pm;
}

template<>      //Template C  explicit specialization  without const
char*  maxn<char* >(char* arr[] ,int n)
{   
    char*  pm=arr[0];
    for(int i=0;i<n;i++)
    {
        if(strlen(pm)<strlen(arr[i]))
        pm=arr[i];
    }
    return pm;
}

If template a and template c are removed, the actual parameter char * will not be assigned to the const char parameter of template b, and an error message will be reported: Undefined reference to 'char maxn<char *>(char * *, int)', I understand its meaning. It says that I did not define a template like 'char * maxn<char >(char * , int)', but does not the book say that type can be converted to const type? Why not convert the char here to const char?

I think template B should be used instead error.

boost regex_replace intermittent SIGARBT in boost::shared_ptr __cxa_pure_virtual [closed]

I use boost_174, jemalloc 5.2.1 The crash backtrace is

#0  0x00007f6f5d766387 in raise () from /lib64/libc.so.6
#1  0x00007f6f5d767a78 in abort () from /lib64/libc.so.6
#2  0x00007f6f5e076a95 in __gnu_cxx::__verbose_terminate_handler() () from /lib64/libstdc++.so.6
#3  0x00007f6f5e074a06 in ?? () from /lib64/libstdc++.so.6
#4  0x00007f6f5e074a33 in std::terminate() () from /lib64/libstdc++.so.6
#5  0x00007f6f5e07559f in __cxa_pure_virtual () from /lib64/libstdc++.so.6
#6  0x0000000001181c97 in boost::detail::sp_counted_base::release (this=0x7f6f534835c0) at /opt/boost/include/boost/smart_ptr/detail/sp_counted_base_gcc_atomic.hpp:120
#7  0x0000000001181d23 in boost::detail::shared_count::~shared_count (this=0x7f6f539941c0, __in_chrg=<optimized out>)
    at /opt/boost/include/boost/smart_ptr/detail/shared_count.hpp:432
#8  0x0000000001412ade in boost::shared_ptr<boost::re_detail_107400::named_subexpressions>::~shared_ptr (this=0x7f6f539941b8, __in_chrg=<optimized out>)
    at /opt/boost/include/boost/smart_ptr/shared_ptr.hpp:335
#9  0x0000000001412b6c in boost::match_results<__gnu_cxx::__normal_iterator<char const*, std::string>, std::allocator<boost::sub_match<__gnu_cxx::__normal_iterator<char const*, std::string> > > >::~match_results (this=0x7f6f53994180, __in_chrg=<optimized out>) at /opt/boost/include/boost/regex/v4/match_results.hpp:119
#10 0x000000000148c416 in boost::regex_iterator_implementation<__gnu_cxx::__normal_iterator<char const*, std::string>, char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::~regex_iterator_implementation (this=0x7f6f53994180, __in_chrg=<optimized out>) at /opt/boost/include/boost/regex/v4/regex_iterator.hpp:40
#11 0x000000000148c436 in boost::checked_delete<boost::regex_iterator_implementation<__gnu_cxx::__normal_iterator<char const*, std::string>, char, boost::regex_traits<char, boost::cpp_regex_traits<char> > > >
    (x=0x7f6f53994180) at /opt/boost/include/boost/core/checked_delete.hpp:36
#12 0x000000000148f152 in boost::detail::sp_counted_impl_p<boost::regex_iterator_implementation<__gnu_cxx::__normal_iterator<char const*, std::string>, char, boost::regex_traits<char, boost::cpp_regex_traits<char> > > >::dispose (this=0x7f6f53dccc40) at /opt/boost/include/boost/smart_ptr/detail/sp_counted_impl.hpp:89
#13 0x0000000001181c97 in boost::detail::sp_counted_base::release (this=0x7f6f53dccc40) at /opt/boost/include/boost/smart_ptr/detail/sp_counted_base_gcc_atomic.hpp:120
#14 0x0000000001181d23 in boost::detail::shared_count::~shared_count (this=0x7ffc4e5a06e8, __in_chrg=<optimized out>)
    at /opt/boost/include/boost/smart_ptr/detail/shared_count.hpp:432
#15 0x000000000148996c in boost::shared_ptr<boost::regex_iterator_implementation<__gnu_cxx::__normal_iterator<char const*, std::string>, char, boost::regex_traits<char, boost::cpp_regex_traits<char> > > >::~shared_ptr (this=0x7ffc4e5a06e0, __in_chrg=<optimized out>) at /opt/boost/include/boost/smart_ptr/shared_ptr.hpp:335
#16 0x000000000148b129 in boost::shared_ptr<boost::regex_iterator_implementation<__gnu_cxx::__normal_iterator<char const*, std::string>, char, boost::regex_traits<char, boost::cpp_regex_traits<char> > > >::reset (this=0x7ffc4e5a07b0) at /opt/boost/include/boost/smart_ptr/shared_ptr.hpp:687
#17 0x000000000148a20d in boost::regex_iterator<__gnu_cxx::__normal_iterator<char const*, std::string>, char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::regex_iterator (this=0x7ffc4e5a07b0, 
    a=47 '/', b=0 '\000', re=..., m=boost::regex_constants::format_first_only) at /opt/boost/include/boost/regex/v4/regex_iterator.hpp:111
#18 0x0000000001495666 in boost::regex_replace<boost::re_detail_107400::string_out_iterator<std::string>, __gnu_cxx::__normal_iterator<char const*, std::string>, boost::regex_traits<char, boost::cpp_regex_traits<char> >, char, std::string> (out=..., first=47 '/', last=0 '\000', e=..., fmt="/", flags=boost::regex_constants::format_first_only)
    at /opt/boost/include/boost/regex/v4/regex_replace.hpp:46
#19 0x0000000001494d31 in boost::regex_replace<boost::regex_traits<char, boost::cpp_regex_traits<char> >, char, std::string> (s="/si_er/frontend/dwr/table/init.action", e=..., fmt="/", 
    flags=boost::regex_constants::format_first_only) at /opt/boost/include/boost/regex/v4/regex_replace.hpp:80

frame info 
(gdb) frame 9
#9  0x0000000001412b6c in boost::match_results<__gnu_cxx::__normal_iterator<char const*, std::string>, std::allocator<boost::sub_match<__gnu_cxx::__normal_iterator<char const*, std::string> > > >::~match_results (this=0x7f6f53994180, __in_chrg=<optimized out>) at /opt/boost/include/boost/regex/v4/match_results.hpp:119
119    ~match_results(){}
(gdb) p *this
$25 = {m_subs = std::vector of length 3, capacity 3 = {
    {<std::pair<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >> = {first = 0 '\000', second = 0 '\000'}, matched = false}, 
    {<std::pair<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >> = {first = 47 '/', second = 46 '.'}, matched = true}, 
    {<std::pair<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >> = {first = 46 '.', second = 0 '\000'}, matched = false}}, m_base = 47 '/', 
  m_null = {<std::pair<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >> = {first = <error reading variable: Cannot access memory at address 0x0>, m_named_subs = {px = 0x7f6f5380cf80, pn = {pi_ = 0x7f6f534835c0}}, 
  m_last_closed_paren = 0, m_is_singular = true}
(gdb) down
#8  0x0000000001412ade in boost::shared_ptr<boost::re_detail_107400::named_subexpressions>::~shared_ptr (this=0x7f6f539941b8, __in_chrg=<optimized out>)
    at /opt/boost/include/boost/smart_ptr/shared_ptr.hpp:335
335 template<class T> class shared_ptr
(gdb) p this
$26 = (boost::shared_ptr<boost::re_detail_107400::named_subexpressions> * const) 0x7f6f539941b8
(gdb) p *this
$27 = {px = 0x7f6f5380cf80, pn = {pi_ = 0x7f6f534835c0}}
(gdb) down
#7  0x0000000001181d23 in boost::detail::shared_count::~shared_count (this=0x7f6f539941c0, __in_chrg=<optimized out>)
    at /opt/boost/include/boost/smart_ptr/detail/shared_count.hpp:432
432         if( pi_ != 0 ) pi_->release();
(gdb) p pi_
$28 = (boost::detail::sp_counted_base *) 0x7f6f534835c0
(gdb) p *pi_
$29 = {_vptr.sp_counted_base = 0x2099fb0 <vtable for boost::detail::sp_counted_base+16>, use_count_ = 0, weak_count_ = 0}
(gdb) p *this
$30 = {pi_ = 0x7f6f534835c0}
(gdb) down
#6  0x0000000001181c97 in boost::detail::sp_counted_base::release (this=0x7f6f534835c0) at /opt/boost/include/boost/smart_ptr/detail/sp_counted_base_gcc_atomic.hpp:120
120             dispose();
(gdb) p *this
$31 = {_vptr.sp_counted_base = 0x2099fb0 <vtable for boost::detail::sp_counted_base+16>, use_count_ = 0, weak_count_ = 0}

break code
release  m_named_subs pi_

boost/include/boost/smart_ptr/detail/sp_counted_base_gcc_atomic.hpp:120
    void release() // nothrow
    {
        if( atomic_decrement( &use_count_ ) == 0 )
        {
            dispose(); //c
            weak_release();
        }
    }

I have written a demo to reproduce the issue. In my demo, the m_named_subs will not be release because use_count_ > 0.

I want to know if 'm_named_subs' should not be released. Also, why does '__cxa_pure_virtual' occur during 'boost::detail::sp_counted_base::release'?

No matter what number I enter, it always comes up "Hang F". Help me

I assign the calculation to z but no matter what I enter it still prints "Hang F". I need help and don't know what to say more than 200 words. Please do not concern yourself with the following. Help me. I just learned programming. I find it a bit difficult but I will try harder.

VSIXTorch visualstudio 2022 install problems C++

I want to learn machine and deep learning using libtorch but I can't even install it on windows.

It says "This extension cannot be installed on any of the installed products". how I can fix this?

Also if you know a good libtorch tutorial, can you link it below?

thank you.

vendredi 20 octobre 2023

std::atomic

Can a std::atomic<T> that is verified to be lock free or a std::atomic_flag safely be used in an Interrupt Service Handler (ISR) to pass a message/flag/indicator from Interrupt Context to another thread or process?

I'm defining std::atomic<T> as lock free if std::atomic<T>::is_always_lock_free is true or if std::atomic<T>::is_lock_free is checked for each instance of std::atomic<T>.

The standard does not mention any usage of interrupts in the atomic documentation. This other answer compares volatile for interrupts and std::atomic for inter-thread communication.

Error in custom comparator for multimap stl c++11


I am trying to run the following code where I create the multimap structure with key and value as pair of two integer values.
I want the stucture to be sorted (without using explicit sorting technique) after each insertion in a way where string is in ascending order, descending order by value's first part and ascending by value's second part.
I wrote the code below for which compilation fails.
#include <iostream>
#include <map>
#include <string>

struct CustomComparator {
    bool operator()(const std::pair<std::string, std::pair<int, int>>& lhs, const std::pair<std::string, std::pair<int, int>>& rhs)  {
        if (lhs.first < rhs.first) {
            return true;  // Sort by key in ascending order
        }
        if (lhs.first > rhs.first) {
            return false; // Sort by key in descending order
        }
        // If keys are equal, sort by the value's first key in descending order
        if (lhs.second.first > rhs.second.first) {
            return true;
        }
        if (lhs.second.first < rhs.second.first) {
            return false;
        }
        // If both keys and the first value's key are equal, sort by the value's second value in ascending order
        return lhs.second.second < rhs.second.second;
    }
};

int main() {
    std::multimap<std::string, std::pair<int, int>, CustomComparator> keyValueMultimap;

    keyValueMultimap.insert({"Apple", {3, 5}});
    keyValueMultimap.insert({"Banana", {2, 4}});
    keyValueMultimap.insert({"Apple", {1, 2}});
    keyValueMultimap.insert({"Orange", {4, 6}});

    for (const auto& pair : keyValueMultimap) {
        std::cout << "Key: " << pair.first << ", Value: (" << pair.second.first << ", " << pair.second.second << ")" << std::endl;
    }

    return 0;
}


Looking out for help.
Thanks in advance.

Note: Trying to compile using C++11 version.

Resulted in following console log:

Compilation failed due to following error(s).
In file included from /usr/include/c++/11/map:60,
                 from main.cpp:2:
/usr/include/c++/11/bits/stl_tree.h: In instantiation of ‘std::pair<std::_Rb_tree_node_base*, std::_Rb_tree_node_base*> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_get_insert_equal_pos(const key_type&) [with _Key = std::__cxx11::basic_string<char>; _Val = std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >; _KeyOfValue = std::_Select1st<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >; _Compare = CustomComparator; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::key_type = std::__cxx11::basic_string<char>]’:
/usr/include/c++/11/bits/stl_tree.h:2151:4:   required from ‘std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_equal(_Arg&&) [with _Arg = std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >; _Key = std::__cxx11::basic_string<char>; _Val = std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >; _KeyOfValue = std::_Select1st<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >; _Compare = CustomComparator; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator = std::_Rb_tree<std::__cxx11::basic_string<char>, std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >, std::_Select1st<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >, CustomComparator, std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > > >::iterator]’
/usr/include/c++/11/bits/stl_multimap.h:547:36:   required from ‘std::multimap<_Key, _Tp, _Compare, _Alloc>::iterator std::multimap<_Key, _Tp, _Compare, _Alloc>::insert(std::multimap<_Key, _Tp, _Compare, _Alloc>::value_type&&) [with _Key = std::__cxx11::basic_string<char>; _Tp = std::pair<int, int>; _Compare = CustomComparator; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >; std::multimap<_Key, _Tp, _Compare, _Alloc>::iterator = std::_Rb_tree<std::__cxx11::basic_string<char>, std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >, std::_Select1st<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >, CustomComparator, std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > > >::iterator; std::multimap<_Key, _Tp, _Compare, _Alloc>::value_type = std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >]’
main.cpp:28:28:   required from here
/usr/include/c++/11/bits/stl_tree.h:2102:39: error: no match for call to ‘(CustomComparator) (const key_type&, const std::__cxx11::basic_string&)’
 2102 |           __x = _M_impl._M_key_compare(__k, _S_key(__x)) ?
      |                 ~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~
main.cpp:6:10: note: candidate: ‘bool CustomComparator::operator()(const std::pair, std::pair >&, const std::pair, std::pair >&)’
    6 |     bool operator()(const std::pair<std::string, std::pair<int, int>>& lhs, const std::pair<std::string, std::pair<int, int>>& rhs)  {
      |          ^~~~~~~~
main.cpp:6:72: note:   no known conversion for argument 1 from ‘const key_type’ {aka ‘const std::__cxx11::basic_string’} to ‘const std::pair, std::pair >&’
    6 |     bool operator()(const std::pair<std::string, std::pair<int, int>>& lhs, const std::pair<std::string, std::pair<int, int>>& rhs)  {
      |                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~
In file included from /usr/include/c++/11/map:60,
                 from main.cpp:2:
/usr/include/c++/11/bits/stl_tree.h: In instantiation of ‘std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_(std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Base_ptr, std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Base_ptr, _Arg&&, _NodeGen&) [with _Arg = std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >; _NodeGen = std::_Rb_tree<std::__cxx11::basic_string<char>, std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >, std::_Select1st<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >, CustomComparator, std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > > >::_Alloc_node; _Key = std::__cxx11::basic_string<char>; _Val = std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >; _KeyOfValue = std::_Select1st<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >; _Compare = CustomComparator; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator = std::_Rb_tree<std::__cxx11::basic_string<char>, std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >, std::_Select1st<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >, CustomComparator, std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > > >::iterator; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Base_ptr = std::_Rb_tree_node_base*]’:
/usr/include/c++/11/bits/stl_tree.h:2153:24:   required from ‘std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_equal(_Arg&&) [with _Arg = std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >; _Key = std::__cxx11::basic_string<char>; _Val = std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >; _KeyOfValue = std::_Select1st<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >; _Compare = CustomComparator; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator = std::_Rb_tree<std::__cxx11::basic_string<char>, std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >, std::_Select1st<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >, CustomComparator, std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > > >::iterator]’
/usr/include/c++/11/bits/stl_multimap.h:547:36:   required from ‘std::multimap<_Key, _Tp, _Compare, _Alloc>::iterator std::multimap<_Key, _Tp, _Compare, _Alloc>::insert(std::multimap<_Key, _Tp, _Compare, _Alloc>::value_type&&) [with _Key = std::__cxx11::basic_string<char>; _Tp = std::pair<int, int>; _Compare = CustomComparator; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >; std::multimap<_Key, _Tp, _Compare, _Alloc>::iterator = std::_Rb_tree<std::__cxx11::basic_string<char>, std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >, std::_Select1st<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >, CustomComparator, std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > > >::iterator; std::multimap<_Key, _Tp, _Compare, _Alloc>::value_type = std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >]’
main.cpp:28:28:   required from here
/usr/include/c++/11/bits/stl_tree.h:1781:56: error: no match for call to ‘(CustomComparator) (std::pair, std::pair >::first_type&, const std::__cxx11::basic_string&)’
 1781 |                               || _M_impl._M_key_compare(_KeyOfValue()(__v),
      |                                  ~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~
 1782 |                                                         _S_key(__p)));
      |                                                         ~~~~~~~~~~~~
main.cpp:6:10: note: candidate: ‘bool CustomComparator::operator()(const std::pair, std::pair >&, const std::pair, std::pair >&)’
    6 |     bool operator()(const std::pair<std::string, std::pair<int, int>>& lhs, const std::pair<std::string, std::pair<int, int>>& rhs)  {
      |          ^~~~~~~~
main.cpp:6:72: note:   no known conversion for argument 1 from ‘std::pair, std::pair >::first_type’ {aka ‘const std::__cxx11::basic_string’} to ‘const std::pair, std::pair >&’
    6 |     bool operator()(const std::pair<std::string, std::pair<int, int>>& lhs, const std::pair<std::string, std::pair<int, int>>& rhs)  {
      |                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~
In file included from /usr/include/c++/11/map:60,
                 from main.cpp:2:
/usr/include/c++/11/bits/stl_tree.h: In instantiation of ‘static const _Key& std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_S_key(std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Const_Link_type) [with _Key = std::__cxx11::basic_string<char>; _Val = std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >; _KeyOfValue = std::_Select1st<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >; _Compare = CustomComparator; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Const_Link_type = const std::_Rb_tree_node<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >*]’:
/usr/include/c++/11/bits/stl_tree.h:2102:44:   required from ‘std::pair<std::_Rb_tree_node_base*, std::_Rb_tree_node_base*> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_get_insert_equal_pos(const key_type&) [with _Key = std::__cxx11::basic_string<char>; _Val = std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >; _KeyOfValue = std::_Select1st<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >; _Compare = CustomComparator; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::key_type = std::__cxx11::basic_string<char>]’
/usr/include/c++/11/bits/stl_tree.h:2151:4:   required from ‘std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_equal(_Arg&&) [with _Arg = std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >; _Key = std::__cxx11::basic_string<char>; _Val = std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >; _KeyOfValue = std::_Select1st<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >; _Compare = CustomComparator; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator = std::_Rb_tree<std::__cxx11::basic_string<char>, std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >, std::_Select1st<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >, CustomComparator, std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > > >::iterator]’
/usr/include/c++/11/bits/stl_multimap.h:547:36:   required from ‘std::multimap<_Key, _Tp, _Compare, _Alloc>::iterator std::multimap<_Key, _Tp, _Compare, _Alloc>::insert(std::multimap<_Key, _Tp, _Compare, _Alloc>::value_type&&) [with _Key = std::__cxx11::basic_string<char>; _Tp = std::pair<int, int>; _Compare = CustomComparator; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >; std::multimap<_Key, _Tp, _Compare, _Alloc>::iterator = std::_Rb_tree<std::__cxx11::basic_string<char>, std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >, std::_Select1st<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > >, CustomComparator, std::allocator<std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> > > >::iterator; std::multimap<_Key, _Tp, _Compare, _Alloc>::value_type = std::pair<const std::__cxx11::basic_string<char>, std::pair<int, int> >]’
main.cpp:28:28:   required from here
/usr/include/c++/11/bits/stl_tree.h:762:23: error: static assertion failed: comparison object must be invocable with two arguments of key type
  762 |         static_assert(__is_invocable<_Compare&, const _Key&, const _Key&>{},
      |                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/c++/11/bits/stl_tree.h:762:23: note: ‘std::__is_invocable, std::allocator >&, const std::__cxx11::basic_string, std::allocator >&>{}’ evaluates to false

jeudi 19 octobre 2023

Problem with linking library in c++ to create exe

I have some problems with compiling the code in c++ using Makefile in a linux server (ubuntu). I use some different classes and in SaaS_Problem.cpp I use gurobi optimization library to solve the problem and it seems that I cannot link the library into my code while apparently everything is set appropriately. SaaS_Problem.cpp is briefly as follows (I didn't bring whole the code because it is too long):

#include "SaaS_Problem.hpp"
#include "SaaS.hpp"
#include "application.hpp"
#include "WS.hpp"
#include "/home/Library/gurobi911/linux64/include/gurobi_c++.h"
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
#include <memory>

std::vector<std::pair<double, double>> SaaS_Problem::set_param_B ( WS & w, application& app)
{
  std::vector <std::pair<double, double>> result; // we will return a vector of paris, we will have as pair.first the nominal value B_bar_a_w_l and as pair.second B_dev
  double A_a_w = w.get_R_bar_a_w() - w.get_D_a_w(); // first compute A_a_w (application a, web service w)
  std::vector<double> B;
  double B_dev = 0.0;
  for( unsigned l = 0; l < app.get_size(); l++) //cycle among all the web services of the application
  {
    auto web_service_l = app.get_web_services()[l];
    double B_a_x_l_bar = A_a_w*w.get_mu_a_w()/((1-A_a_w*w.get_mu_a_w())*web_service_l.get_mu_a_w());
    B_dev = compute_B_dev( w, web_service_l, B_a_x_l_bar );


    //std::cout << "B_bar = "<< B_a_x_l_bar << '\n'; // debugging
    //std::cout << "B_dev = "<< B_dev << '\n'; //debugging


    result.push_back(std::make_pair( B_a_x_l_bar ,  B_dev));
  }
  return result;
}

void SaaS_Problem::solve(void)
{
  try
  {
    rejected_requests = 0;
    rejected_requests_vec.resize(0);
    GRBEnv env = GRBEnv(); // create a gurobi environment

    GRBModel model = GRBModel(env); //create an empty model

    GRBLinExpr obj = 0.0; // create a linear expression to construct my objective function

    // Create variables

    GRBLinExpr total_on_flat = 0;   // create a linear expression which will be the sum of all on_flat VMs
    GRBLinExpr total_VM = 0;        // create a linear expression which will be the sum of all VMs
    std::vector<GRBVar> x_v;        // here we store the variables X_a_w because we need them for the computation of the parameters B

    std::vector<GRBVar> alpha_v;    // here we store all the values of alpha, we need it just for debugging
    std::vector<GRBVar> beta_v;     // here we store all the values of beta, we need it just for debugging
    std::vector<GRBVar> y_v;        // here we store the variables the number of rejacted requests

    //std::vector<GRBLinExpr> bx; // for debugging

    double total_on_spot = 0.0;

    // setting the variables and the objective function
    for(unsigned i = 0; i < s -> get_size(); i++)                                      // cicle over all the applications of the SaaS
    {

      auto app = s -> get_applications()[i];                                           // ith application

      total_on_spot += s -> get_on_spot(app);

      std::string r_a = "r" + std::to_string(i);                                       // create the name for the variables
      std::string d_a = "d" + std::to_string(i);

      GRBVar r  = model.addVar(0.0, GRB_INFINITY, 0.0  , GRB_CONTINUOUS, r_a);         // creating r_a
      GRBVar d  = model.addVar(0.0, GRB_INFINITY, 0.0  , GRB_CONTINUOUS, d_a);         // creating d_a

      obj += rho * r;                                                                  // adding r_a to the objecting funcion
      obj += delta * d;                                                                // adding d_a to the objecting funcion

      total_on_flat += r;                                                              // updating the sum of all the on flat VMs
      total_VM += ( r + d );                                                           // updating the sum of all the VMs


     for(unsigned j = 0; j < app.get_size(); j++)                                                  // cicle over all the WSs of the application i
      {

        auto web_service = app.get_web_services()[j];                                               // j-th WS of the i-th application

        GRBVar y = model.addVar(0.0, GRB_INFINITY, 0.0, GRB_CONTINUOUS);                            // creating y_a_w

        obj += (T * web_service.get_nu_a_w() * y);                                                  // adding it to the objecting funcion

        GRBVar x = model.addVar(0.0, GRB_INFINITY, 0.0  , GRB_CONTINUOUS);                          // creating X_a_w

        model.addConstr( x >= web_service.get_lambda_a_w());                                       // X_a_w >= lambda_a_w
        model.addConstr( y + x >= web_service.get_LAMBDA_a_w() );                                   // X_a_w + y_a_w >= LAMBDA_a_w


        y_v.push_back(y);                                                                           // store y_a_w in y_v
        x_v.push_back(x);                                                                           // store X_a_w in x_v

      }

      .

Makefile is as follows:

CXXFLAGS += -Wall -std=c++11 -I/home/Library/gurobi911/linux64/include -L/home/Library/gurobi911/linux64/lib  -lgurobi_c++ -lgurobi91

EXE = exe

OBJS = main.o Game.o Set_System.o SaaS_Problem.o SaaS.o application.o WS.o IaaS.o IaaS_Problem.o

.DEFAULT_GOAL = all

main.o Game.o Set_System.o SaaS_Problem.o SaaS.o application.o WS.o : WS.hpp
main.o Game.o Set_System.o SaaS_Problem.o SaaS.o application.o : application.hpp
main.o Glpthreadame.o Set_System.o SaaS_Problem.o SaaS.o : SaaS.hpp
main.o Game.o Set_System.o SaaS_Problem.o : SaaS_Problem.hpp
main.o Game.o Set_System.o IaaS_Problem.o IaaS.o: IaaS.hpp
main.o Game.o Set_System.o IaaS_Problem.o: IaaS_Problem.hpp
main.o Game.o Set_System.o : Set_System.hpp
main.o Game.o : Game.hpp

all : build

.PHONY : all build clean distclean

build : $(EXE)

$(EXE) : $(OBJS)
    $(CXX) $(CXXFLAGS) $(LDFLAGS) $(LDLIBS) $^ $(OUTPUT_OPTION) -I/home/Library/gurobi911/linux64/include -L/home/Library/gurobi911/linux64/lib -lgurobi_c++ -lgurobi91

clean:
    $(RM) *.o

distclean: clean
    $(RM)$(EXE)
    $(RM)*~

and .bashrc file is:

export GUROBI_HOME="/home/Library/gurobi911/linux64"
export PATH="${PATH}:${GUROBI_HOME}/bin"
export LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${GUROBI_HOME}/lib"
export GRB_LICENSE_FILE="/home/Library/gurobi.lic"
export PATH="${PATH}:${GUROBI_HOME}/include"

when I use make to create exe file I get following error:

g++ -Wall -std=c++11 -I/home/Library/gurobi911/linux64/include -L/home/Library/gurobi911/linux64/lib -lgurobi_c++ -lgurobi91   main.o Game.o Set_System.o SaaS_Problem.o SaaS.o application.o WS.o IaaS.o IaaS_Problem.o -o exe -I/home/Library/gurobi911/linux64/include -L/home/Library/gurobi911/linux64/lib -lgurobi_c++ -lgurobi91
SaaS_Problem.o: In function `SaaS_Problem::solve()':
SaaS_Problem.cpp:(.text+0x1523): undefined reference to `GRBModel::addVar(double, double, double, char, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
SaaS_Problem.cpp:(.text+0x157e): undefined reference to `GRBModel::addVar(double, double, double, char, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
SaaS_Problem.cpp:(.text+0x17c2): undefined reference to `GRBModel::addVar(double, double, double, char, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
SaaS_Problem.cpp:(.text+0x18e1): undefined reference to `GRBModel::addVar(double, double, double, char, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
SaaS_Problem.cpp:(.text+0x19af): undefined reference to `GRBModel::addConstr(GRBTempConstr const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
SaaS_Problem.cpp:(.text+0x1abb): undefined reference to `GRBModel::addConstr(GRBTempConstr const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
SaaS_Problem.cpp:(.text+0x1c71): undefined reference to `GRBModel::addVar(double, double, double, char, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
SaaS_Problem.cpp:(.text+0x1d48): undefined reference to `GRBModel::addVar(double, double, double, char, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
SaaS_Problem.cpp:(.text+0x1ee3): undefined reference to `GRBModel::addConstr(GRBTempConstr const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
SaaS_Problem.cpp:(.text+0x21a5): undefined reference to `GRBModel::addConstr(GRBTempConstr const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
SaaS_Problem.cpp:(.text+0x23c3): undefined reference to `GRBModel::addConstr(GRBTempConstr const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
SaaS_Problem.cpp:(.text+0x2505): undefined reference to `GRBModel::addConstr(GRBTempConstr const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
SaaS_Problem.cpp:(.text+0x28bb): undefined reference to `GRBModel::getVarByName(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
SaaS_Problem.cpp:(.text+0x2920): undefined reference to `GRBModel::getVarByName(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
SaaS_Problem.cpp:(.text+0x33fc): undefined reference to `GRBException::getMessage[abi:cxx11]() const'
collect2: error: ld returned 1 exit status
Makefile:26: recipe for target 'exe' failed
make: *** [exe] Error 1

How can I solve this problem?

How to get KeyPress and mouseclick to work with non Player Class

I am trying to get a non player class to respond to a key press for testing purposes and i got a working player character. I want to try and setup a MassProcessor that can take mouseclick and get position in 3D space.

But i am still new a C++ so i am unsure of i would procced.

Bellow is my current code which compiles, and i would want to execute the function UMassTestProcessor::GetCursorPosition when i leftclick on the mouse.

.CCP file

UMassTestProcessor::UMassTestProcessor()
{
    bAutoRegisterWithProcessingPhases = true;
    ExecutionFlags = (int32)EProcessorExecutionFlags::All;
    ExecutionOrder.ExecuteBefore.Add(UE::Mass::ProcessorGroupNames::Avoidance);

    MousePosition = FVector(0,0,0);
    /*
    if (UEnhancedInputComponent* EnhancedInputComponent = CastChecked<UEnhancedInputComponent>(PlayerInputComponent))
    {
        PlayerInputComponent->BindAction("LeftMouseButton", IE_Pressed, this, GetCursorPosition());


    }
    */
}

void UMassTestProcessor::ConfigureQueries()
{
    EntityQuery.AddRequirement<FTransformFragment>(EMassFragmentAccess::ReadOnly);
    EntityQuery.AddRequirement<FMassMoveTargetFragment>(EMassFragmentAccess::ReadWrite);


    EntityQuery.AddTagRequirement<FMyTag>(EMassFragmentPresence::All);

}

void UMassTestProcessor::Execute(FMassEntityManager& EntityManager, FMassExecutionContext& Context)
{


    EntityQuery.ForEachEntityChunk(EntityManager, Context, 
        ([this](FMassExecutionContext& Context)
        {
                
            const TArrayView<FTransformFragment> TransformsList = Context.GetMutableFragmentView<FTransformFragment>();
            const TArrayView<FMassMoveTargetFragment> TargetList = Context.GetMutableFragmentView<FMassMoveTargetFragment>();
            //const float WorldDeltaTime = Context.GetDeltaTimeSeconds();

            for (int32 EntityIndex = 0; EntityIndex < Context.GetNumEntities(); EntityIndex++)
            {
                FTransform& Transform = TransformsList[EntityIndex].GetMutableTransform();
                FMassMoveTargetFragment& Target = TargetList[EntityIndex];

                Target.Center = FVector(100.f, 100.f, 0.f);

                Target.Forward = (Target.Center - Transform.GetLocation()).GetSafeNormal();
                Transform.SetRotation(FQuat::FindBetweenVectors(FVector::ForwardVector,Target.Forward));

            }

        }));

}

void UMassTestProcessor::GetCursorPosition()
{
    FHitResult Hit;
    bool bHitSuccessful = false;

    if (PlayerInputComponent)
    {
        APlayerController PlayerController;
        bHitSuccessful = PlayerController.GetHitResultUnderCursor(ECollisionChannel::ECC_Visibility, true, Hit);
        UE_LOG(LogTemp, Warning, TEXT("Position is: %s"), *Hit.Location.ToString());
        MousePosition = Hit.Location;
    }



}

.H file

UCLASS()
class PROJECTMASS_API UMassTestProcessor : public UMassProcessor
{
    GENERATED_BODY()

public:
    UMassTestProcessor();

    UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = WorldPositionFromMouse)
    FVector MousePosition;

    UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Input, meta = (AllowPrivateAccess = "true"))
    class UInputAction* PlayerInputComponent;

    //virtual void ACharacter::ACharacter SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;

protected:
    virtual void ConfigureQueries() override;
    virtual void Execute(FMassEntityManager& EntityManager, FMassExecutionContext& Context) override;

    void GetCursorPosition();

private:
    FMassEntityQuery EntityQuery;
};

I would like some simple code example, that way its a lot easier for me to understand, but i would be thankful for any suggestions.

Install C++ json boost on RHEL machine

I am trying to install json boost (boost_json) library on my linux RHEL machine. I got the latest tar file from boost.org i.e. boost_1_83_0.tar.gz. After untaring the file I ran the following commands.

./bootstrap.sh --with-libraries=json --prefix=/usr/local

sudo ./b2 install

I running the above commands, I did not face any error but boost_json library did not get installed. Requesting you to kindly assist me with installing the boost_json library

Note : I even tried to install boost library with yum but no change

sudo yum install boost boost-devel

Also, I can use the following line and skip the installation but I want to try with the installed library

#include <boost/json/src.hpp>

mardi 17 octobre 2023

How may I use the send and recv functions from an external source file? [closed]

I have an application that uses WindowsSockets to make connections and send data between server and client. I want to make those send and recv functions come from another source file in the project.   I want the send function to send what ever I tell it to send, and the recv function to return into a variable what the other pc send to me.

This is my server code:

#undef UNICODE

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>

#include <iostream>

#include "../headers_externos/conection.h"
#include "../headers_externos/data_module.h"

// Need to link with Ws2_32.lib
#pragma comment (lib, "Ws2_32.lib")
// #pragma comment (lib, "Mswsock.lib")

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "8080"

int conectar()
{
    WSADATA wsaData;
    int iResult;

    SOCKET ListenSocket = INVALID_SOCKET;
    SOCKET ClientSocket = INVALID_SOCKET;

    struct addrinfo *result = NULL;
    struct addrinfo hints;

    int iSendResult;
    char recvbuf[DEFAULT_BUFLEN];
    int recvbuflen = DEFAULT_BUFLEN;


    std::cout << "Inicializando a biblioteca de Winsock" << std::endl;
    // Inicializando a biblioteca de Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        std::cout << "WSASturtup falhou! Erro: " << iResult << std::endl;
        return 1;
    }
    std::cout << "Biblioteca inicializada com sucesso" << std::endl;

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    std::cout << "Resolvendo endereco e porta do servidor..." << std::endl;
    // Resolvendo o endereco e porta do servidor
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if ( iResult != 0 ) {
        std::cout << "getaddrinfo failed with error: %d\n" << iResult << std::endl;
        WSACleanup();
        return 1;
    }std::cout << " Sucesso!\n" << std::endl;


    std::cout << "Criando SOCKET para conexao..." << std::endl;
    // Criando Socket
    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (ListenSocket == INVALID_SOCKET) {
        std::cout << "Socket falhou! Erro: %ld\n\n" << WSAGetLastError() << std::endl;
        freeaddrinfo(result);
        WSACleanup();
        return 1;
    }
    std::cout << " Socket criado com sucesso!\n" << std::endl;

    std::cout << " Setando TCP listening socket...\n\n" << std::endl;
    std::cout << " bind()..." << std::endl;
    // Setup TCP listening socket
    iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
            std::cout << " bind() falhou! Erro: %d\n\n" << WSAGetLastError() << std::endl;
            freeaddrinfo(result);
            closesocket(ListenSocket);
            WSACleanup();
            return 1;
    }
    std::cout << " Sucesso!\n" << std::endl;

    freeaddrinfo(result);

    std::cout << " listen()..." << std::endl;
    iResult = listen(ListenSocket, SOMAXCONN);
    if (iResult == SOCKET_ERROR) {
           std::cout << " listen() falhou! Erro: %d\n\n" << WSAGetLastError()<< std::endl;
            closesocket(ListenSocket);
            WSACleanup();
            return 1;
    }
    std::cout << " Sucesso!\n" << std::endl;

    std::cout << " Aguardando conexoes! accept()..." << std::endl;
    // Aceitando um cliente socket
    ClientSocket = accept(ListenSocket, NULL, NULL);
    if (ClientSocket == INVALID_SOCKET) {
           std::cout << " accept() falhou! Erro: %d\n\n"<< WSAGetLastError() << std::endl;
            closesocket(ListenSocket);
            WSACleanup();
            return 1;
    }
    std::cout << " Sucesso!\n" << std::endl;

    closesocket(ListenSocket);

   std::cout << " Servidor pronto para receber dados!!!" << std::endl;
    // Recebe ate o cliente encerrar a conexao
    do {

        std::cout << " Aguardando..." << std::endl;

        
        /*
        RECIVE FUNCTION:
        */
          
        char *recvbuf = receber(ClientSocket);
        //--------------------------------------------

        if (iResult > 0) {
           std::cout << " Bytes recebidos: " << iResult << std::endl;
            std::cout << " Enviando um eco ao cliente..." << std::endl;
            // Echo the buffer back to the sender
            
            
            
           /*
            SEND FUNCTION:
            */
            iSendResult = enviar(ClientSocket, recvbuf);
            //-----------------------------------------
            
            
            
            
            if (iSendResult == SOCKET_ERROR) {
               std::cout << " send() falhou! Erro: " << WSAGetLastError() << std::endl;
                closesocket(ClientSocket);
                WSACleanup();
                return 1;
            }
            std::cout << " Sucesso! Bytes enviados: " << iSendResult << std::endl;
        }
        else if (iResult == 0)
            std::cout << " Conexao fexada pelo cliente!" << std::endl;
        else  {
           std::cout << " recv() falhou! Erro: " << WSAGetLastError()  << std::endl;
            closesocket(ClientSocket);
            WSACleanup();
            return 1;
        }

    } while (iResult > 0);

    std::cout << " Encerrando..." << std::endl;
    // Fexando a conexao quando terminarmos
    iResult = shutdown(ClientSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
            std::cout << "shutdown() falhou! Erro:" << WSAGetLastError() << std::endl;
            closesocket(ClientSocket);
            WSACleanup();
            return 1;
    }
    std::cout << " Encerrado!\n" << std::endl;
    // cleanup
    closesocket(ClientSocket);
    WSACleanup();

    return 0;

}

The functions send and recv should come from this script:

#include <winsock2.h>
#include "../headers_externos/data_module.h"

#define DEFAULT_BUFLEN 512


int enviar(SOCKET sock, const char* data)
{

send( sock, data, 0, 0 );

return 0;
}

char *receber(SOCKET socket)

{
    int recvbuflen = DEFAULT_BUFLEN;
    char *recvbuf = (char*)malloc(recvbuflen);

    recv(socket, recvbuf, recvbuflen, 0);

     return recvbuf;

     free(recvbuf);
}

The original cone is taken from here: https://pt.stackoverflow.com/questions/22719/cliente-servidor-windows-com-sockets-em-c