mardi 31 août 2021

Is it good to use int_fastN_t to replace intN_t

I just read this link: The difference of int8_t, int_least8_t and int_fast8_t? and now I know that int8_t is exactly 8 bits whereas int_fast8_t is the fastest int type that has at least 8 bits.

I'm a developer who develops backend processes with c++11 on Linux. Most of time I don't need to worry about the size of my processes. But I need always care about the sizes of integers in my project. For example, if I want to use an int to store the ID of user or to store a millisecond-timepoint, I can't simply use int because it may cause overflow, I must use int32_t or int64_t.

So I'm thinking if it's good to use int_fast8_t everywhere and stop using int8_t (same as int_fast32_t, int_fast64_t, uint_fast8_t etc).

Well, using int_fastN_t may change nothing because my program is always deployed on X86 or Arm64. But I still want to know if there is any drawback if I change all of intN_t into int_fastN_t. If there isn't any drawback, I think I would start to use int_fastN_t and stop using intN_t.

Why unlocking not locked std::mutex is UB?

Unlocking std::mutex that wasn't locked is UB. Why is it so? Why isn't it just have no effect, as mutex isn't locked yet, or was already unlocked, so what's the harm of calling unlock again?

istream_iterator behavior misunderstanding

The goal is to read 16 bit signed integers from a binary file. First, I open the file as an ifstream, then I would like to copy each numbers into a vector using istream_iterator and the copy algorithm. I dont' understand what's wrong with this snippet:

int main(int argc, char *argv[]) {
    std::string filename("test.bin");

    std::ifstream is(filename);
    if (!is) {
        std::cerr << "Error while opening input file\n";
        return EXIT_FAILURE;
    }
    
    std::noskipws(is);
    std::vector<int16_t> v;
    std::copy(
        std::istream_iterator<int16_t>(is),
        std::istream_iterator<int16_t>(),
        std::back_inserter(v)
    );

    //v is still empty
}

This code produces no error but the vector remains empty after the call to std::copy. Since I'm opening the file in the standard input mode ("textual" mode), I was expecting istream_iterator to work even if the file is binary. Of course there's something I'm missing about the behavior of this class.

Argument type in templated function forced to a given type?

The following runs fine:

#include <iostream>
#include <string>

/**
 * Simply print the value of the argument and adapt the 
 * statement based on its type. 
 */
template<typename T>
int function(T value){

    if(std::is_same<T,double>() || std::is_same<T,float>()){
        std::cout << value << ", type is float" << std::endl; 
        return 0; 
    }
    else if(std::is_same<T,std::string>()){
        std::cout << value << ", type is string" << std::endl; 
        return 0; 
    }
    else if(std::is_same<T,char*>() || std::is_same<T,const char*>()){
        std::cout << value << ", type is char*" << std::endl; 
        return 0; 
    }
    else{
        std::cout << "Unsupported data type" << std::endl; 
        return -1; 
    }
}

int main(){
    function<double>(1.2345); 
    function<std::string>("Hello World");
    const char* sentence = "Hello World"; function<const char*>(sentence);
    return 0; 
}

Since this runs without any issue, I tried changing the following line:

std::cout << value << ", type is string" << std::endl;

to

std::cout << value.c_str() << ", type is string" << std::endl;

However this does not compile. It is like if the type of value was defined when compiling the .c_str() call. However, I would have expected the type of the value argument to only depend on the template argument T. Why isn't it compiling in this case?

Following error is generated:

In instantiation of ‘int function(T) [with T = double]’:
.cpp:321:25:   required from here
error: request for member ‘c_str’ in ‘value’, which is of non-class type ‘double’
   std::cout << value.c_str() << ", type is string" << std::endl;
                ~~~~~~^~~~~
In instantiation of ‘int function(T) [with T = const char*]’:
.cpp:323:70:   required from here
.cpp:306:22: error: request for member ‘c_str’ in ‘value’, which is of non-class type ‘const char*’

Does the use of {} in a class member variable std::array result in initializing the array elements? [duplicate]

I have a class X with an std::array member variable:

class X
{
   public:
     //some code here

   private:
     std::size_t var1_;
     std::array<std::uint8_t, 100> var2_; //this is the class member variable
}

I want to ensure that var1_ and var2_ are always initialized even if I do not explicitly initialize them in the constructor. If I do something like this:

  class X
    {
       public:
         //some code here
    
       private:
         std::size_t var1_{0};
         std::array<std::uint8_t, 100> var2_{}; //this is the class member variable
    }

it will initialize var1_ to zero. Does the use of {} for var2_ guarantee that all the uint8_t array elements will be initialized to zero? Also if the use of {} ensures that all the array elements are initialized to zero, is there a way to initialize them to some value other than 0, at the line where var2_ is defined? (i.e., without doing it explicitly in the constructor). I am using C++11. Thanks

Class Templates and Friendship in C++

I am trying to understand how templates and friendship works in C++. So looking/trying out some examples by myself. One such example that i am unable to understand is given below:

VERSION 1

#include <iostream>

using namespace std;


//template<typename T> void func4();
//template<typename T> class NAME;
//   template<typename T> std::ostream& operator<< (std::ostream&, NAME<T> const&);
template<typename T>
class NAME {
   

    friend void func4<T>();
    friend std::ostream& operator<< <T> (std::ostream&, NAME<T> const&);
};
int main()
{
   cout << "Hello World" << endl; 
 
   return 0;
}

The above version 1 gives the following error:

prog.cc:13:17: error: variable or field 'func4' declared void
   13 |     friend void func4<T>();
      |                 ^~~~~
prog.cc:13:17: error: expected ';' at end of member declaration
   13 |     friend void func4<T>();
      |                 ^~~~~
      |                      ;
prog.cc:13:22: error: expected unqualified-id before '<' token
   13 |     friend void func4<T>();
      |                      ^

My first question is that even though i have commented the forward declarations for both func4 and operator<< template function, then how can i only get error only for func4? That is why is there no error for operator<<.

Note that i know we need forward declarations if we want to befriend a specific instantiation of a template. That is for

friend void func4<T>();

to work we need to comment out the statement

template<typename T> void func4();

and similarly for

friend std::ostream& operator<< <T> (std::ostream&, NAME<T> const&);

to work we need to comment out corresponding forward declaration at the starting of the program. But when i comment out only template<typename T> void func4(); statement, the program works and and there is no error for operator<<. Again why aren't we getting the error for operator<< even though i have not comment out the corresponding forward declarations.

My second question is that is the statement

friend void func4<T>();

same as

friend void func4<>();

Similarly, is the statement

friend std::ostream& operator<< <T> (std::ostream&, NAME<T> const&);

same as

friend std::ostream& operator<< <> (std::ostream&, NAME<T> const&);

My thinking is that the statement friend void func4<>(); is a specialization of the function template declared using the statement template <typename T> void func4();. Meanwhile when we write friend void func4<T>(); we are explicitly passing T so in this case when we write/call func4<int>(); the function template func4<int> will be intantiated and then occupy memory. On the other hand the specialised template function will already take up some memory since we have to provide its definition before we can call it. So can someone explain whether there is a difference when we use <T> and when we use <>. In summary, it seems to me that in case of <> a user supplied specialization will be used while in case of <T> a new intiantion will be created when we call func4(). So there is a difference because in case of <> we have to supply a definition which will already take some space(memory) while in the case of <T> func4 will only take space(memory) when we use/call it. Is this the correct conclusion?

My third question is that i have read that:

There is no way to explicitly specify template arguments to overloaded operators, conversion functions, and constructors, because they are called without the use of the function name.

According to the above quoted statement we cannot explicitly specify template arguments to overloaded operators, but then how can write friend std::ostream& operator<< <T> (std::ostream&, NAME<T> const&); as it overload operator << .

C++11 type-trait to determine whether sizeof() makes sense

Is there a C++11 (only) type trait to determine whether it is sensible to call sizeof? My code is

void f_(const void* data, size_t sz);

template <typename T>
void f(const T& t)
{
   static_assert(std::is_pod<T>::value, "Can't call sizeof() on T."); // TODO ???
   f_(&t, sizeof(T));
}

std::is_pod looks pretty close; but not only is that depreciated in C++20, it's not clear to me that std::is_trivial and std::is_standard_layout are sufficient.

I want a call like f("abc"); to fail (the call should be f_("abc", strlen("abc")) not sizeof("abc")), while f(123) is OK. Also, I think

struct Foo final {int i; double d; };
// ...
Foo foo;
f(foo);

should also be OK, but probably not something "complicated."

OpenGl does not render Mesh

I have tried to abtract my OpenGl code into classes, which has worked fine so far. It would always render until I recently build a Game class which is a derived class of the Window2 class (which I have also only recently created). I am pretty sure that the bug is not to be found in the Mesh, Shader, PointLight or the Material class (as they have worked properly in the past). The window does appear and has the correct background color. The render function is also called in the game loop so I am not sure what the problem is. Here is the code...

Game.h

#ifndef GAME_H
#define GAME_H


#include <iostream>
#include <stdio.h>
#include <vector>
#include <glm.hpp>
#include <gtc/matrix_transform.hpp>

#include "GameBlock.h"
#include "blocks/NormalGameBlock.h"
#include <PointLight.h>
#include <Window2.h>
#include <memory>
#include <Renderer.h>
#include <Mesh.h>
#include <Shader.h>
#include <Material.h>
#include <Utils.h>

class Game : private Window2 {
private:


    Mesh* mesh;
    Shader* shader;
    Material* material;

    PointLight* pointLight;

    glm::mat4 projection;
    glm::vec3 viewPosition;
    glm::mat4 view;

public:
    Game();
    ~Game();
    void initialize();
    void start();
    void stop();

    // override the functions provided by base class Window2
    void input(Keys k) override;
    void update() override;
    void render() override;
};

#endif

Game.cpp

#include "Game.h"

Game::Game()
    :
    Window2((int)(1080 * 0.7f), (int)(1920 * 0.7f), "Game", false)
{
    PRINT_FUNC;
    pointLight = new PointLight
    (
        glm::vec3(0.0, 0.0, 1.0),
        glm::vec3(1.0, 1.0, 1.0) * 0.0f,
        glm::vec3(1.0, 1.0, 1.0) * 0.3f,
        glm::vec3(1.0, 1.0, 1.0) * 1.0f,
        1.0f,
        0.01f,
        0.01f
    );

    material = new Material
    (
        glm::vec3(0.0f, 0.0f, 1.0f) * 1.0f,
        glm::vec3(0.0f, 0.0f, 1.0f) * 1.0f,
        glm::vec3(0.0f, 0.0f, 1.0f) * 1.0f,
        1.0f,
        256.0f,
        1.0f
    );
}

Game::~Game() {
    PRINT_FUNC;
    delete mesh;
    delete shader;
    delete material;
    delete pointLight;
}

void Game::initialize() {
    PRINT_FUNC;

    Window2::intitialize2();

    mesh = new Mesh(Mesh::loadVertices("assets/box2.obj", false));
    shader = new Shader("shaders/vertex_shader copy.glsl", "shaders/fragment_shader copy.glsl");

    projection = glm::perspective(glm::radians(35.0f), 9.0f / 16.0f, 0.1f, 1000.0f);
    viewPosition = glm::vec3(0, 1, 0);
    view = glm::lookAt(
        viewPosition,          // Camera is at (4,3,3), in World Space
        glm::vec3(0, 0, 0),    // and looks at the origin
        glm::vec3(0, 1, 0)     // Head is up (set to 0,-1,0 to look upside-down)
    );

    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

}

void Game::start() {
    run();
}

void Game::stop() {
    close();
}

void Game::input(Keys k) {

}

void Game::update() {

}

void Game::render() {

    shader->activate();
    shader->setMat4("P", projection);
    shader->setMat4("V", view);
    shader->setVec3("viewPos", viewPosition);

    Renderer::render(mesh, shader, material, pointLight);

}

Window2.h

#ifndef WINDOW_2_H
#define WINDOW_2_H

#define GLEW_STATIC

#include <GL/glew.h> // include GLEW and new version of GL on Windows
#include <glfw3.h>   // GLFW helper library

#include <iostream>

struct Keys {
    bool W, A, S, D;
    bool Left, Right, Up, Down;
    bool N0, N1, N2, N3, N4, N5, N6, N7, N8, N9;
    bool Space, Esc;
    bool Shift;
};

class Window2 {
private:

    GLFWmonitor* m_monitor;

    unsigned int m_width;
    unsigned int m_height;
    int m_posX;
    int m_posY;
    const char* m_title;
    const bool m_fullscreen;

    float aspectRatio;

public:

    GLFWwindow* m_window;

    Window2(unsigned int width, unsigned int height, const char* title, const bool fullscreen);
    ~Window2();

    void intitialize2();

    void run();

    void close();

    // override functions
    virtual void input(Keys k);

    virtual void update();

    virtual void render();

    void setResizeCallback(void(*ptr)(GLFWwindow*, int, int));

    void setSize(int width, int height);

    float getAspectRatio();

    void makeCurrent() const;

    // clear window
    void clear(float r, float g, float b);

    // swap
    void swap();

    // poll events
    void poll();

    // get time in milliseconds
    static unsigned int getTimeMS();
};

#endif

Window2.cpp

#include "Window2.h"

#include <iostream>
#include <chrono>
#include <Utils.h>

Window2::Window2
(
    unsigned int width,
    unsigned int height,
    const char* title,
    const bool fullscreen
)
    :
    m_width(width),
    m_height(height),
    m_title(title),
    m_fullscreen(fullscreen)
{
    PRINT_FUNC;
}

Window2::~Window2() {
    PRINT_FUNC;
    glfwDestroyWindow(m_window);
}

void Window2::intitialize2() {
    PRINT_FUNC;
    if (!glfwInit())
    {
        fprintf(stderr, "ERROR: could not start GLFW3\n");
        return;
    }

    const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
    m_width = m_fullscreen ? mode->width : m_width;
    m_height = m_fullscreen ? mode->height : m_height;
    aspectRatio = (float)m_width / (float)m_height;
    m_window = glfwCreateWindow(m_width, m_height, m_title, m_fullscreen ? glfwGetPrimaryMonitor() : NULL, NULL);
    if (!m_window) {
        fprintf(stderr, "ERROR: could not open Window2 with GLFW3\n");
        glfwTerminate();
        return;
    }
    glfwMakeContextCurrent(m_window);

    // start GLEW extension handler
    glewExperimental = GL_TRUE;
    glewInit();

    //setSize(m_width, m_height);

    // get version info
    const GLubyte* renderer = glGetString(GL_RENDERER);
    const GLubyte* version = glGetString(GL_VERSION);
    printf("Renderer: %s\n", renderer);
    printf("OpenGL version supported %s\n\n", version);
}

void Window2::run() {

    PRINT_FUNC;

    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    unsigned int previous = getTimeMS();
    unsigned int lag = 0;
    const unsigned int msPerUpdate = 1000 / 60;

    while (!glfwWindowShouldClose(m_window)) {

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glClearColor(0.8, 0.8, 0.8, 1);

        unsigned int current = getTimeMS();
        unsigned int elapsed = current - previous;
        previous = current;
        lag += elapsed;

        const Keys k{
            glfwGetKey(m_window, GLFW_KEY_W) == GLFW_PRESS,
            glfwGetKey(m_window, GLFW_KEY_A) == GLFW_PRESS,
            glfwGetKey(m_window, GLFW_KEY_S) == GLFW_PRESS,
            glfwGetKey(m_window, GLFW_KEY_D) == GLFW_PRESS,

            glfwGetKey(m_window, GLFW_KEY_LEFT) == GLFW_PRESS,
            glfwGetKey(m_window, GLFW_KEY_RIGHT) == GLFW_PRESS,
            glfwGetKey(m_window, GLFW_KEY_UP) == GLFW_PRESS,
            glfwGetKey(m_window, GLFW_KEY_DOWN) == GLFW_PRESS,

            glfwGetKey(m_window, GLFW_KEY_0) == GLFW_PRESS,
            glfwGetKey(m_window, GLFW_KEY_1) == GLFW_PRESS,
            glfwGetKey(m_window, GLFW_KEY_2) == GLFW_PRESS,
            glfwGetKey(m_window, GLFW_KEY_3) == GLFW_PRESS,
            glfwGetKey(m_window, GLFW_KEY_4) == GLFW_PRESS,
            glfwGetKey(m_window, GLFW_KEY_5) == GLFW_PRESS,
            glfwGetKey(m_window, GLFW_KEY_6) == GLFW_PRESS,
            glfwGetKey(m_window, GLFW_KEY_7) == GLFW_PRESS,
            glfwGetKey(m_window, GLFW_KEY_8) == GLFW_PRESS,
            glfwGetKey(m_window, GLFW_KEY_9) == GLFW_PRESS,

            glfwGetKey(m_window, GLFW_KEY_SPACE) == GLFW_PRESS,
            glfwGetKey(m_window, GLFW_KEY_ESCAPE) == GLFW_PRESS,

            glfwGetKey(m_window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS
        };

        //input
        input(k);

        while (lag >= msPerUpdate)
        {
            // update
            update();

            lag -= msPerUpdate;
        }

        // render
        render();

        glfwSwapBuffers(m_window);
        glfwPollEvents();
    }
}

void Window2::input(Keys k) {

}

void Window2::update() {

}

void Window2::render() {

}

void Window2::close() {
    glfwSetWindowShouldClose(m_window, GLFW_TRUE);
}

void Window2::setSize(int width, int height) {
    m_width = width;
    m_height = height;
    aspectRatio = (float)m_width / (float)m_height;
    glViewport(0, 0, width, height);
}

void Window2::setResizeCallback(void(*ptr)(GLFWwindow*, int, int)) {
    glfwSetWindowSizeCallback(m_window, ptr);
}

void Window2::makeCurrent() const {
    glfwMakeContextCurrent(m_window);
}

float Window2::getAspectRatio() {
    return aspectRatio;
}

unsigned int Window2::getTimeMS() {
    std::chrono::milliseconds mt = std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::system_clock::now().time_since_epoch());
    return mt.count();
}

This is how the class is created in Main.cpp:

int main(int argc, char* argv[])
{

  Game game;
  game.initialize();
  game.start();

  glfwTerminate();
  return 0;
}

I don't understand this behavior with move constructors [duplicate]

I'm new with C++11. I wrote this class to help me to well understand move behavior in the classes.

class MoveChecker
{
    private:
        bool wasMoved;
        int something;
    public:
        MoveChecker() : wasMoved(false), something(0) {}
        MoveChecker(int data) : wasMoved(false), something(data) {}
        MoveChecker(MoveChecker const& m) : wasMoved(false), something(m.something) {}
        MoveChecker(MoveChecker&& m) noexcept : wasMoved(true), something(m.something) {}
        ~MoveChecker() noexcept {} 
        void swap(MoveChecker& m) noexcept
        {
            std::swap(this->wasMoved, m.wasMoved);
            std::swap(this->something, m.something);
        }
        MoveChecker& operator=(MoveChecker const& m)
        {
            MoveChecker(m).swap(*this);
            return *this;
        }
        MoveChecker& operator=(MoveChecker&& m) noexcept
        {
            MoveChecker(std::move(m)).swap(*this);
            return *this;
        }
        bool moved() const noexcept { return this->wasMoved; }
        int value() const noexcept { return this->something; }
};
void swap(MoveChecker& m1, MoveChecker& m2) noexcept { m1.swap(m2); }

Then, I play with a template container, and I check it with my MoveChecker class. Here is a simplified version.

template <typename T>
class Container
{
    private:
        T data;
    public:
        Container() : data() {}
        Container(T const& data_) : data(data_) {}
        Container(T&& data_) noexcept : data(std::move(data_)) {}
        Container(Container<T> const& c) : data(c.data) {}
        Container(Container<T>&& c) noexcept : data(std::move(c.data)) {}
        ~Container() noexcept {}
        void swap(Container<T>& c) noexcept
        {
            using std::swap;
            swap(this->data, c.data);
        }
        Container<T>& operator=(Container<T> const& c)
        {
            Container<T>(c).swap(*this);
            return *this;
        }
        Container<T>& operator=(Container<T>&& c) noexcept
        {
            Container<T>(std::move(c)).swap(*this);
            return *this;
        }
        T const& getData() const noexcept { return this->data; }
};

When I use this container, I have a behavior I can't explain. See the following main code:

int main()
{
    MoveChecker mc(123);

    Container<MoveChecker> c1_(mc);
    Container<MoveChecker> c1(std::move(c1_));
    std::cout << "c1.getData().moved() = " << c1.getData().moved() << std::endl;

    Container<MoveChecker> c2 = Container<MoveChecker>(mc);
    std::cout << "c2.getData().moved() = " << c2.getData().moved() << std::endl;
    
    Container<MoveChecker> c3 = std::move(Container<MoveChecker>(mc));
    std::cout << "c3.getData().moved() = " << c3.getData().moved() << std::endl;

    return 0;
}

The output of execution of this code is the following:

c1.getData().moved() = 1
c2.getData().moved() = 0
c3.getData().moved() = 1

In my opinion, it means that Container<MoveChecker>(mc) given to build c2 is not considered as a temporary variable. Why ? Did I something wrong or is it the expected behavior ?

System: openSUSE (Linux)

Compiler used: gcc 4.8.5

Compilation command: g++ move.cpp -o move.exe -std=c++11

Error while trying to overload << operator

I can't get the below code to compile while trying to overload the << operator. Can anyone point whats going wrong?

#include <iostream>

std::ostream& operator<<(std::ostream& i, int n)
{
    return i;
}

int main()
{
    std::cout << 5 << std::endl;
    std::cin.get();
    return 0;
}

g++ compiler gives me errors with -std=c++11 flag, but it compiles fine with -std=gnu++11. what does this mean?

I'm maintaining an old server at work, which is running on CentOS6(gcc (GCC) 4.4.7, C++98) and I was trying to migrate it to CentOS7(gcc (GCC) 4.8.5) with C++11.

At first, I tried to compile with a flag, -std=c++11 but it gaved me a lot of error like below.

`In file included from /usr/lib/gcc/x86_64-redhat-linux/4.8.5/include/x86intrin.h:30:0,
                 from /usr/include/c++/4.8.2/x86_64-redhat-linux/bits/opt_random.h:33,
                 ...
/usr/lib/gcc/x86_64-redhat-linux/4.8.5/include/mmintrin.h: In function ‘__m64_mm_cvtsi32_si64(int)’:
/usr/lib/gcc/x86_64-redhat-linux/4.8.5/include/mmintrin.h:61:54: error: can’t convert between vector values of different size
   return (__m64) __builtin_ia32_vec_init_v2si (__i, 0);
                                                      ^
/usr/lib/gcc/x86_64-redhat-linux/4.8.5/include/mmintrin.h: In function ‘int _mm_cvtsi64_si32(__m64)’:
/usr/lib/gcc/x86_64-redhat-linux/4.8.5/include/mmintrin.h:104:53: error: cannot convert ‘__m64 {aka int}’ to ‘__vector(2) int’ for argument ‘1’ to ‘int __builtin_ia32_vec_ext_v2si(__vector(2) int, int)’
   return __builtin_ia32_vec_ext_v2si ((__v2si)__i, 0);`

Somehow, I encountered about using a flag, -std=gnu++11 and it worked fine.

What can I assume with this? Does this mean that the old server code is somehow using gnu extension or whatever?

lundi 30 août 2021

C++ delete function compile error occurs from difference between gcc 4.8.2 and 4.9.4

I tried to compile my source code using gcc-linaro-aarch64-linux-gnu-4.8-2013.09-01_linux(gcc 4.8.2)

the error occurred like below

../compiler/llvm/lib/Target/Bifrost/BifrostInstrInfo.h:58:47: error: use of deleted function 'llvm::MachineInstr::~MachineInstr()'

In file included from ../compiler/llvm/lib/Target/Bifrost/MCTargetDesc/BifrostMCInstOpdMap.h:18:0,

                 from ../compiler/llvm/lib/Target/Bifrost/MCTargetDesc/BifrostMCInst.h:14,

                 from ../compiler/llvm/lib/Target/Bifrost/BifrostRegisterInfo.h:13,

                 from ../compiler/llvm/lib/Target/Bifrost/BifrostMachineFunctionInfo.h:13,

                 from ../compiler/llvm/lib/Target/Bifrost/BifrostClause.h:13,

                 from ../compiler/llvm/lib/Target/Bifrost/BifrostAsmPrinter.cpp:10:

../compiler/llvm/include/llvm/CodeGen/MachineInstr.h:276:3: error: declared here

   ~MachineInstr() = delete;

So, I changed toolchain to gcc-linaro-4.9-2016.02-x86_64_aarch64-linux-gnu(gcc4.9.4)

and I tried again. build was success.

Build was successful and I read the gcc release note

But i don't know what the difference is.

I want to know cause clearly.

Could you explain the difference? or let me know the solution this issue in gcc4.8(ex compile option... etc)

Possible to use a variadic functions/templates in this way?

I was wondering whether given the below constraints, it is possible to use variadic functions/templates in order to pass a variable number of parameters (which are themselves a return value of a function) into a variadic function.

Constraints:

  1. No STL/Boost/other libraries.
  2. No loops/recursion.
  3. C++17 or earlier compliant (nothing beyond C++17).

Brief example:

using fn = F(...);
fn* func = (fn*) addr;
value = (*func)(pop_t(outputstack,o_stackidx,o_stacksize)...);
push_t(outputstack,o_stackidx,o_stacksize, value);

fn* is a function pointer (converted from a known user-defined memory address of a function) which takes in a variable number of pop_t arguments (values poped from a stack), these values (outputstack,o_stackidx,o_stacksize) are static and do not need to be variadic themselves. Essentially I was wondering whether it's possible to have the pop_t function repeat a variable number of times either A.) by depending on the appropriate number of arguments fn is capable of taking in or B.) using a user-defined integer specifying the number of repeats.

As an example say the user were to input a sin or atan2 function, these two functions take different numbers of parameters respectively being sin(x) and atan(y,x). For these two respective functions the function call expressions would look like the following:

sin -> (*func)(pop_t(outputstack,o_stackidx,o_stacksize)); 

atan2 -> (*func)(pop_t(outputstack,o_stackidx,o_stacksize),pop_t(outputstack,o_stackidx,o_stacksize)); 

Functions with N arguments pop N values from the stack by calling pop_t N times.

Reproducible example:

template<class U, class I>
U pop_t(U* stack, I &stackidx, I &stacksize) {
    if(stacksize>0) {
        stacksize--;
        stackidx = stackidx--;
        return stack[stackidx];
    }
    else {
        return stack[stackidx];
    }
}

int main() {
    float outputstack[2] = {3.141/2,1};
    o_stackidx = 2;
    o_stacksize = 2;
    long addr = (long)&atan2;
    using fn = F(...);
    fn* func = (fn*) addr;
    // Unknown variadic function pointer
    value = (*func)(pop_t(outputstack,o_stackidx,o_stacksize,nt)...);

    return 0;

}

Filling up a file of a specific size - How would I be able to accomplish that

I am attempting to create a file using SetFilePointerExto simply set the size of the file. Now I would like to populate that entire file from start to end with the number 1 or any other number. I am not sure how I would accomplish that. Is there a way that I can use to fill up that entire file with a number.

This is the code that I have come up with so far. I now have handle to a file hFile but I am not sure how I can populate it now till the available limit?

  HANDLE hFile = CreateFileA(
        Filename,
        GENERIC_WRITE,
        (FILE_SHARE_READ | FILE_SHARE_WRITE),
        nullptr, 
        OPEN_ALWAYS,
        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED ,  
        nullptr);  

    if (INVALID_HANDLE_VALUE == hFile)
    {
        std::cout << "Could not create the file";
        return false;
    }
    
    //Set a fixed size
     LARGE_INTEGER li;
     li.QuadPart = uFileSize;

    LARGE_INTEGER liNewFilePointer;

    if (!SetFilePointerEx(hFile, li, &liNewFilePointer, FILE_BEGIN))
    {
        //Could not create the file
        CloseHandle(hFile);
        return false;
    }
    if (liNewFilePointer.QuadPart != li.QuadPart)
    {
        //Error occured
        CloseHandle(hFile);
        return false;
    }

    if (!SetEndOfFile(hFile))
    {
        //Error use GetLastError()
        CloseHandle(hFile);
        return false;
    }

    //We now have a file of a specific size

C++ perform action when command line argument is empty [duplicate]

I've been working on a program recently, and got a bit stuck on a step. When the program is run from the shell, it performs an action when there are no parameters passed. Perhaps someone could assist me, or point me in a proper direction?

int main(int argc, char* argv[])
{
    string paramPassed = argv[1];
    if(paramPassed == "")
        cout << UseDriver();
    
    else if(paramPassed == memMap)
        cout << UseMemMap();
    
    else{
        if(paramPassed == help)
            cout << PrintProgramHelp();
        
        else if(paramPassed == helpMin)
            cout << PrintProgramHelp();
        
        else
            cout << "Wrong selection. Input --help or -h for more options." << endl;
    }
    cout << "Press any key to continue." << endl;   
    cin.get();
    return (0);
}

Above code on no input gives me:

terminate called after throwing an instance of 'std::logic_error'
what():  basic_string::_M_construct null not valid

What can I do? If I don't provide any parameter on program start, it gives me a segmentation fault.

Is there something I'm missing here?

How to call a polymorphic function in a thread object

struct Base {
    virtual void do_work()=0;
};

struct Derived_A : Base{
    void do_work() override {
        //work A
    }
};

struct Derived_B : Base{
    void do_work() override {
        //work B
    }
};

int main() {
    std::vector<std::unique_ptr<Base>> workers;
    workers.emplace_back(std::unique_ptr<Base>(new Derived_A()));
    workers.emplace_back(std::unique_ptr<Base>(new Derived_B()));
    
    std::vector<std::thread> threads;
    for (const auto& worker : workers) {
            //Compile error
            //expecting Derived_A and Derived_B do_work functions to be called respectively
            threads.emplace_back(&Base::do_work, worker);
    }
    
}

From the code snippet above, what is the right way to call the do_work function in the thread? It's a straightforward question but Stackoverflow requires me to add more text to my question so I'm writing this.

Issue with a Makefile where one subdirectory isn't getting compiled

I find that in this Makefile, the EventProducers subdirectory is just not getting compiled although it is similiar in every respect with the other subdirectories. It was added newly. Any reason why the Makefile wouldn't compile this specific folder. Make clean and make has been tried already.

include $(ROOTDIR)/$(PROJECT)/abc/defines.mk
include $(ROOTDIR)/$(PROJECT)/def/xyz/delta/defines.mk

local = alpha/Services/Recording

subdirs = Factory EventProducers Search Control Control Serial

INCLUDE_DIRS += -I$(ALPHA_HOME)/Services/Recording

LOCAL_OBXS = \
        $(addprefix $(localobx)/, \
        RecordingBase.o \
        )

LIBS := $(libdir)/libalpha_recording.a
$(LIBS): $(LOCAL_OBXS)

include $(ROOTDIR)/$(PROJECT)/Build/rules.mk     

Configuring C++11/14 in Mac Terminal by default

I want to use c++11/14 features like range-based loops, but get a warning while doing g++ program.cpp. If done with compiler flag g++ -std=c++11 program.cpp the warning goes away. Is there a way to use c++11/14 by default on the g++ command (i.e without passing compiler flag every time).

Please explain to someone with limited knowledge of compilers and only need the c++11/14 features for competitive programming problems (even if it's a bad idea in general, maybe due to backward compatibility?)

cant debug with c++, exits pre-maturely with status [1] + Done

I am new to programming c++ debugging is not working i am using vs code

code and exit

here is

launch.json

and here is task.json

it exits without me being about to see anything it altho prints out output and it is parrot os default install

parallel push_back for vector of vector

I have a large text file around 13G which the content is an edge list of a graph. Each line has two integers uandv represent the endpoint of an edge. I want to read it to a vector of vector as an adjency vector of the graph.

Then It comes to folowing code.

const int N = 3328557;
vector<vector<int> >adj{N};

int main() {
    FILE * pFile;
    pFile = fopen("path/to/edge/list", "r");

    int u, v;
    while (fscanf(pFile, "%d%d", &u, &v) == 2) {
        adj[u].push_back(v);
        adj[v].push_back(u);
    }
    
    fclose(pFile);
}

It consumes about 7min. After some analysis, I find adj[u].push_back(v) and adj[v].push_back(u) consumes most time because of random address.

Then I use a two dimension array as cache. Once it's filled, I copy all the value to vector and clear it.

const int N = 3328557;
const int threshold = 100;

vector<vector<int> >adj{N};
int ln[N];
int cache[N][threshold];

void write2vec(int node) {
    for (int i = 0; i < ln[node]; i++)
        adj[node].push_back(cache[node][i]);
    ln[node] = 0;
}

int main() {
    FILE * pFile;
    pFile = fopen("path/to/edge/list", "r");

    int u, v;
    while (fscanf(pFile, "%d%d", &u, &v) == 2) {
        cache[u][ln[u]++] = v;
        if (ln[u] == threshold)
            write2vec(u);
        cache[v][ln[v]++] = u;
        if (ln[v] == threshold)
            write2vec(v);
    }
    
    fclose(pFile);
}

This time it consumes 5.5 min. It's still too long. Then I think the two push_back in the first code can be parallelized. But I don't know how to do. And does anyone has other idea?

Thanks.

Why does std::initializer_list in ctor not behave as expected?

#include <vector>

int main()
{
    auto v = std::vector{std::vector<int>{}};
    return v.front().empty(); // error
}

See online demo

However, according to Scott Meyers' Effective Modern C++ (emphasis in original):

If, however, one or more constructors declare a parameter of type std::initializer_list, calls using the braced initialization syntax strongly prefer the overloads taking std::initializer_lists. Strongly. If there's any way for compilers to construe a call using a braced initializer to be a constructor taking a std::initializer_list, compilers will employ that interpretation.

So, I think std::vector{std::vector<int>{}}; should produce an object of std::vector<std::vector<int>> rather than std::vector<int>.

Who is wrong? and why?

dimanche 29 août 2021

problem with operator[] when trying to access a vector of shared_ptr

I have the following class :

class Character
{
     /unimportant code
}
class Fighter : public Character
{
     /unimportant code
}
class Healer: public Character
{
     /unimportant code
}


class Game
{
public:
    void move(const GridPoint & src_coordinates,  const GridPoint & dst_coordinates);
    //there are more things here ,but they're not important for the sake of this question. 
private:
    int height;
    int width;
    std::vector<std::shared_ptr<Character>> gameboard;
};


void move(const GridPoint & src_coordinates,  const GridPoint & dst_coordinates)
{
    for (std::vector<std::shared_ptr<Character>>::iterator i = gameboard.begin(); i != 
                                                                  gameboard.end() ; i++ )
    {
        if ( (*gameboard[i]).coordinates == src_coordinates)
        {
            //do I need to implement my own [] operator?
        }
           
        
    }
        
}

Im trying to iterate over my gameboard and move the character from src_coordinates to dst_coordinates. Character is also a class that's inherited by a few more :

I get the following error when I try to access the elements of gameboard[i] :

no match for 'operator[] (operand types are 'std::vector<std::shared_ptr<Character> >' and 'std::vector<std::shared_ptr<Character> >::iterator' {aka '__gnu_cxx::__normal_iterator<std::shared_ptr<Character>*, std::vector<std::shared_ptr<Character> > >'}

does that mean that I have to implement my own operator[] and operator* because Character is a class of my own? and how can I solve my ptoblem?

Why shoudl I resize a std::vector passed to SOCI for bulk fetching?

In the SOCI manual it mandates that the vector bound to the statement to populate data should be resized at every bulk fetch iteration. I guess this is analogous to a DB statement that cannot be read multiple times. By the time we finish reading the bound vector its size has become 0. My question is, since we are binding an std::vector to SOCI (a data structure capable of multiple reads in desired directions), does this have to be? Is SOCI trying to mimic the database statement behavior, or is this a technical requirement?

My question stems form the angle, if we could use this vector for processing the data we fetch, it will reduce one copy operation from the bound vector to program data structures. Since we are already talking about bulk operations, if this is a possibility, it will be a massive saving.

Convert Little Endian to Big Endian - Not getting expected result

I have a very small code where I am trying to convert a 16 bit number from little endian to big endian format.

The value of number is 0x8000 and after conversion I am expecting it to be as 0x0080 - but I am getting some different value as mentioned below:

#include <iostream>
int main()
{
        int num = 0x8000;
        int swap = (num>>8) | (num<<8);
        std::cout << swap << std::endl;
        return 0;
}

The program outputs 8388736 as value which in hex is 0x800080 - I am not sure what wrong am I doing?

making vectors of an object independent of each other

I have a question regarding vectors,shared_ptr, andcopy c'tors in c++

class Character 
{
     int health;//and more stuff that aren't important for the sake of this question
     //more code...
}
class Game 
{
     int size;
     vector<shared_ptr<character>> board;
}

now my question is: When I do :

Game game1 = (53,...)//say that I gave proper values for gaame1 to be constructed.
Game game2 = game1;

what would be the vector that's in game2? meaninng does the vector in game2 have the same address as the vector in game1? or is it a vector with a different address but the same contents?

Moreover: if the answer to my question is that they're the same vector (meaning they have the same address), how can I make them independent of each other? {what I want is for both vectors to have the same contents but different addresses!}

//if anyone is confused by what I mean with contents : it's the shared_ptrs inside the vector

Is it possible to implement a 'clone( )' function using boost::context?

I'm playing around with boost::context a bit, making a little task scheduler. A minimal proof of concept.

After being able to create tasks and have them run according to the scheduler, it occurred to me to add the clone( ) functionality, using setjmp( ). However, when I try to run the cloned task, I get a nice 'SIGSEGV` error:

#include <boost/context/continuation.hpp>

#include <csetjmp>
#include <iostream>

namespace ctx = boost::context;

enum CoroState {
    Finish = 0,
    Ready
};

using EntryPoint = void (*)( );

struct Coro {
    ~Coro( ) {
        if( next != this ) {
            prev->next = next;
            next->prev = prev;
        }
    }
    Coro( EntryPoint ep ) :
        state( CoroState::Ready ),
        entryPoint( ep ),
        clone( false ),
        next( this ),
        prev( this ) {
    }
    Coro( EntryPoint ep, Coro *curr ) :
        state( CoroState::Ready ),
        entryPoint( ep ),
        clone( false )
    {
        next = curr;
        prev = curr->prev;
        curr->prev = this;
        prev->next = this;
    }
    Coro( Coro *origin ) :
        Coro( origin->entryPoint, origin )
    {
        clone = true;
    }


    CoroState state;
    EntryPoint entryPoint;
    bool clone;
    Coro *next;
    Coro *prev;
    std::string name;
    jmp_buf jmpBuf;
    ctx::continuation continuation;
};

static Coro *ActiveCoro = nullptr;

static ctx::continuation wrapper( ctx::continuation &&sink ) {
    ActiveCoro->continuation = std::move( sink );

    if( ActiveCoro->clone ) {
        std::longjmp( ActiveCoro->jmpBuf, 1 );
    } else {
        ActiveCoro->entryPoint( );
    }

    ActiveCoro->state = CoroState::Finish;

    return std::move( ActiveCoro->continuation );
}

static void yield( ) {
    ActiveCoro->continuation = ActiveCoro->continuation.resume( );
}

static Coro &createCoro( EntryPoint ep ) {
    Coro *result;

    if( !ActiveCoro ) {
        ActiveCoro = new Coro( ep );
        result = ActiveCoro;
    } else {
        result = new Coro( ep, ActiveCoro );
    }

    return *result;
}

bool clone( ) {
    auto newCoro = new Coro( ActiveCoro );

    return setjmp( newCoro->jmpBuf );
}

void runLoop( ) {
    while( ActiveCoro ) {
        if( ActiveCoro->continuation ) {
            ActiveCoro->continuation = ActiveCoro->continuation.resume( );
        } else {
            ActiveCoro->continuation = ctx::callcc( wrapper );
        }

        if( ActiveCoro->state == CoroState::Finish ) {
            if( ActiveCoro->next == ActiveCoro ) {
                delete ActiveCoro;
                break;
            } else {
                auto toDelete = ActiveCoro;
                ActiveCoro = ActiveCoro->next;
                toDelete->prev->next = toDelete->next;
                toDelete->next->prev = toDelete->prev;
                delete toDelete;
            }
        }

        ActiveCoro = ActiveCoro->next;
    }
}

static void Worker( ) {
    for( int idx = 0; idx < 5; ++idx ) {
        std::cout << ActiveCoro->name << ", idx " << idx << std::endl;
        yield( );
    }

    std::cout << ActiveCoro->name << " terminado.\n";
}

static void Master( ) {
    std::cout << "Entrando en Master.\n";

    createCoro( Worker ).name = "Worker 1";
    createCoro( Worker ).name = "Worker 2";
    createCoro( Worker ).name = "Worker 3";

    std::cout << "Master ha creado los hijos. Esperando.\n";

    if( clone( ) ) {
        std::cout << "Clon de Master terminado\n";
    } else {
        std::cout << "Master terminado.\n";
    }
}

int main( ) {
    std::ios::sync_with_stdio( false );

    createCoro( Master ).name = "Master";

    runLoop( );

    std::cout << std::endl;

    return 0;
}

The problem is unique to the clone( ) functionality. If I comment this part:

/*
if( clone( ) ) {
    std::cout << "Clon de Master terminado\n";
} else {
    std::cout << "Master terminado.\n";
}
*/

everything works fine again.

  • Is it possible to get the clone( ) functionality in this way ?
  • How to it ?

Is unique_ptr faster than raw pointer? C++

I was experimenting with the benchmarking here and found weird results.
Apparently creating and deleting raw pointer is slower (according to my measurements of course) than creating unique_ptr, how is this possible?

struct deleter 
{
    template<typename T>
    void operator()(T* ptr) 
    {
        delete ptr;
    }
};

void BM_rawPtr(benchmark::State& state)
{
    deleter d;
    for (auto _ : state)
    {
        int* p = new int(0);
        d(p);
    }
    state.SetItemsProcessed(state.iterations());
}


void BM_uniquePtr(benchmark::State& state)
{
    deleter d;
    for (auto _ : state)
    {
        std::unique_ptr<int, deleter> ptr(new int(0), d);
    }
    state.SetItemsProcessed(state.iterations());
}

BENCHMARK(BM_rawPtr);
BENCHMARK(BM_uniquePtr);
BENCHMARK_MAIN();

This gave me weird results:

enter image description here

I don't want to claim nonsense like "unique_ptr is faster than raw pointer".
Clearly I have missed some point here, does this ring a bell to anyone?

Thanks in advance.

Why type checking is not happening for std::function?

#include <functional>

void toggleOk(bool& b) { b = !b; }
void toggleBroken(bool b) { b = !b; }
void toggleInt(int i) { i = !i; }
void tooManyParams(bool b, int i) { i = !b; }

int main()
{
    typedef std::function<void(bool&)> CallbackType;
    typedef std::function<void(bool)> WrongCallbackType;

    CallbackType cb1 = [](bool b) { b = !b; }; // Should throw error - missing reference
    CallbackType cb2 = toggleOk; // Ok

    CallbackType cb3 = toggleBroken; // Should throw error - missing reference
    CallbackType cb4 = toggleInt; // Should throw error - integer instead of bool

    WrongCallbackType cb5 = toggleBroken; // Ok

    CallbackType cb6 = cb5; // Type checking not even applying between std::functions

    CallbackType cb7 = tooManyParams; // Only this statement throws error

    return 0;
}

Consider the above example, which is creating a bunch of callbacks that have reference to bool as a parameter. Except the very last callback cb7, this code can compile and run just fine, even though most of the functions stored in the callback objects mismatch the reference or type of the parameter.

I've encountered this behavior with VS19/C++20 with the lambda stored in the std::function, however I've tried this example with two distinct G++ compilers for Windows, with extra diagnostics enabled and with C++17/C++2a and none reported even a warning.

My question is - is this an expected behavior or is it a bug? Why?

samedi 28 août 2021

Why the char in C++ Occupies 7 bits when the length is 1byte i.e is 8 bits

I seen that the char data type is taking only 7 bits of memory to store the character, but in general every where I studied that char occupies 1 byte of memory i.e is 8 bits.

Single character requires 8 bits or 7 bits? if it requires 8 bits means what will be stored in other bit?

#include <iostream>
using namespace std;

int main()
{
    char ch = 'a';
    int val = ch;
    
    while (val > 0)
    {
        (val % 2)? cout<<1<<" " : cout<<0<<" ";
        val /= 2;
    }
    return 0;
}

OP: 1 0 0 0 0 1 1

How is std::mutex's constexpr constructor implemented?

While looking at the C++ Reference for std::mutex, I noticed that the constructor for std::mutex is marked constexpr.

This is surprising at first, since we usually have to make a system call (either pthread_mutex_init() (POSIX) or CreateMutex() (Windows) to initialize a mutex. However, on closer inspection, for POSIX, one can use the constant PTHREAD_MUTEX_INITIALIZER to statically initialize the mutex (perhaps as a global variable), though I can find no equivalent for Windows.

However, even if this static initialization for POSIX was the reason behind the constexpr constructor, there're still various issues with an implementation:

  1. On Windows (and perhaps other non-POSIX systems), there may not be a way to statically initialize mutexes.
  2. It was impossible to have different code paths depending on whether the constructor is being called at compilation time until C++20's std::is_constant_evaluated() was added, so we don't have a way to determine if PTHREAD_MUTEX_INITIALIZER or pthread_mutex_init() should be used.

So, how does one implement the constexpr constructor for std::mutex?

Struggling with error message undefined reference to `Fish::Fish(std::string)'

I have this UML Diagram and I have written the code below but I am struggling with an error message

enter image description here

However, while compiling and linking, I got an error

/tmp/cc9oQaPX.o: In function `main':
main.cpp:(.text+0x8c): undefined reference to `Fish::Fish(std::string)'
main.cpp:(.text+0xe5): undefined reference to `Cat::Cat(std::string)'
main.cpp:(.text+0x116): undefined reference to `Fish::Fish()'
main.cpp:(.text+0x158): undefined reference to `Cat::Cat()'
collect2: error: ld returned 1 exit status
#include <iostream>
using namespace std;
class Animal  // define base class 
{
protected:
    int legs;        // base class properties
public:
    Animal(int legNumbers)    // set values of leg
    {
        legNumbers = legs;   // set values of leg 
    }
    virtual void eat() = 0;  // method of base class
    virtual void walk() {}; // method of base class


};
class Pet      // define the pet class 
{
protected:
    string name;       // set properties of pet class 
public: 
    virtual string getName();       // define method
    virtual string setName(string name);    // set name values 
    virtual void play()          // define play method 
    {
        cout << " garfield is playing now." << endl;  // out values 
    }
};
class Spider :public Animal   //child class inherit base class
{
public:
    Spider() :Animal(8)   // spider class inherit animal class
    {
        cout << "animals with " << legs << " legs is walking. " << endl;
    }
    virtual void eat()   // define virtual method
    {
        cout << "spider is eating now. " << endl;
    }
};
class Cat :public Pet, public Animal  // cat inherit two classes 
{
public:
    Cat(string name);   // set name method
    Cat();       
    virtual void play()   // define method
    { 
        cout << name << " is playing now. " << endl;
    }
    virtual void eat();     // define method here

};
class Fish : public  Pet, public Animal  // fish inherit two method
{
public:        // define public members
    Fish(string name);
    Fish();
    virtual void play()
    {
        cout << name << " is playing now. " << endl;
    }
    virtual void eat();   // method here 
    void walk() 
    {
        cout << " Fish cannot walk " << endl;  // output the values 
    }
};

string Pet::getName()   // get name value from parent class
{
    return string();
}

string Pet::setName(string name)
{
    return string();
}
int main(int argc, char* argv[])   // define main method 
{
    Fish* f = new Fish("Jaws");
    Cat* c = new Cat("Tenkir");
    Animal *a = new Fish();
    Animal* e = new Spider();
    Pet* p = new Cat();
    f->play();
    c->play();
    e->eat();
    e->walk();
    a->walk();
    p->play();
    return 0;
}

Why std::unique_ptr is not compatible with assignement operator?

For example:-

std::unique_ptr<int> int_ptr=new int(10); // error: conversion from ‘int*’ to non-scalar type ‘std::unique_ptr’ requested.

std::unique_ptr<int> pointer(new int(10)); // this work fine.

problem with [] operator when using a vector

I'm trying to make a copy constructor for Game. throughout the copy constructor I have to copy the elements of one game into another. However when I try to access the inner elemnts of the game I want to copy I get an error saying :

no operator "[]" matches these operands -- operand types are: mtm::Game [ std::_Vector_const_iterator<std::_Vector_val<std::conditional_t<true, std::_Simple_types<std::vector<char, std::allocator>>, std::_Vec_iter_types<std::vector<char, std::allocator>, size_t, ptrdiff_t, std::vector<char, std::allocator> *, const std::vector<char, std::allocator> *, std::vector<char, std::allocator> &, const std::vector<char, std::allocator> &>>>> ]C/C++(349)

I'd appreciate any help with explaining why the [] operator doesn't work, here's the piece of code I wrote :

Game::Game(const Game& other)
{
    Game game(other.height, other.width);

    for (vector<vector<char>>::const_iterator row = other.game.begin(); row != 
                                                              other.game.end(); row++)
    {
        for(vector<char>::const_iterator col = row->begin(); col != row->end(); col++)
        {                
            game[row][col] = other[row][col];  ///////???
        }
    }

In addition to that, I'd like to ask if it's better to allocate a game using "new" or just declare it like I did in my code segment above.

Can anyone help me to solve this problem in C++ I want to do this exercise with "virtual function"?

I want to solve this problem in c++ using virtual function please if anyone have solution of this exercise please submit here

vendredi 27 août 2021

Is it safe to delete a nullptr twice in C++?

I have watched a talk in CPPCon which is back to basic: class layout and the link is this. At 54:20, he said it's undefined bahavior to delete the nullptr twice. As far as I know, C++ standard guarantee deleting a nullptr does nothing but why deleting a nullptr twice is undefined bahavior?

And I was told before that there is no need to check if ptr is null in destructor because deleting a null pointer is valid. But if delete a null pointer twice is undefined, does that mean I still need to check if it's nullptr to prevent double-deleting happen?

This is a transcription of the author from his video:

[...] ignore the standard and then got later problems. A common example I see is it's ok to delete a null pointer, that's fine, but you can't delete it twice without resetting the value to some valid pointer value. If I delete the same pointer twice if it's not null you'll get probably a segfault, if it is null it typically just happens to work, but it's not guaranteed to work and there was actually one compiler in the 1980s where it wouldn't work because when you deleted a pointer a new value was overwritten in the deleted pointer. So again, do follow the standard.

C++11: Possible to mix std::string and std::__cxx11::string in the same file?

It has become a nuisance to be forced to compile our whole software project with _GLIBCXX_USE_CXX11_ABI set to 0, just so that we can link to one closed-source library whose vendor insists on backward ABI compatibility without offering a version compiled with the C++11 ABI.

This forces us to recompile several other libraries that are readily available as system packages, just because the default mode of compilation of the whole system has switched to C++11 ABI as the default (specifically, rhel8 clones).

My question is thus, is it possible to mix the two ABIs in a single object file, by, for example, referring to the old string as std::string and the new string as std::__cxx11::string explicitly -- or through some aliases -- then copying the raw data from c++11-abi string into the old-abi string on the way into the problematic library, and then copying the raw string data from the old-abi string back into a c++11- abi string on the way back from the library?

To the best of my understanding of libstdc++ source code, the inline namespace __cxx11 is never declared if _GLIBCXX_USE_CXX11_ABI is 0; and if it is 1, the old-abi std::string and basic_string etc. cannot be accessed in any way.

So far I've only been able to create a const char * wrapper for the old-abi library and use that wrapper from the c++11-abi library. It works:

$ nm --demangle a.out | ack ~basic_string
             U std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()
             U std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()

But I find it very ugly. Is this the only way or is there something better?

Self static referential class

I have been given a task of compiling the C++ legacy code on a new platform. In the process of compiling, I came across the following code...

class GLOBALS
{
public:
    static GLOBALS _global;
};
GLOBALS GLOBALS::_global;

class DEF
{
public:
    GLOBALS::GLOBALS _global;
};

When I am trying to compile this code, I am getting following error...

error: ‘GLOBALS::GLOBALS’ names the constructor, not the type
GLOBALS::GLOBALS _global;

I am not getting what this code is trying to achieve here.. Can anyone enlighten me on this? And how they were able to compile the code previously?

How can we solve this problem in O(logn) and which is the best algo to solve these kind of questions?

1Please help me out to solve this problem

overriding the what function in std::exception in c++

I'm trying to override the what function in order to print customized error messages of my own.

all messages have the same beginning and therefore I thought that it would be best if I could do the following :

class Exception : public std::exception
{
    public:
    virtual const char* what() const throw() noexcept
    {
        return ("A game related error has occurred: " +  "class name");
        //note : "class name" above is the error message I want to print 
        //depending on the situation, which can vary a lot(we have 8 different messages)
    }
};


//examples of "class name" /otherwise known by us as error messages:

class IllegalArgument : public Exception {};

class IllegalCell  : public Exception {};

my problem is the following :

I couldn't quite figure out how I can print a varying message depending on which error I receive without making a special what function in each error class - meaning I had to add a what function to IllegalArgument,IllegalCell and every other error class, which is bad in my eyes because it's too many functions to uphold and keep updating overtime. is there anyway I can avoid that, and just be able to print a varying message in the main class - Exception?

jeudi 26 août 2021

copy record set in local _RecordsetPtr in C++

kindly provide suggestion, I am have getResults function and executing a query in C++.

int ABC::getResult(char *query)
{
    _CommandPtr     pCom;
    _bstr_t         lv_query;
    lv_query        = (_bstr_t) sqlQuery;

    try
    {
        pCom.CreateInstance(__uuidof(Command));
        pCom->ActiveConnection = pConn;
        pCom->CommandType = adCmdText;
        pCom->CommandText = lv_query;
        pCom->CommandTimeout = 60;
        RecordSet = pCom->Execute(NULL, NULL, adCmdText);       
    
    }
    catch(_com_error &e)
    {
        _bstr_t bstrSource(e.Source());
        _bstr_t bstrDescription(e.Description());
        sprintf_s(errStr,sizeof(errStr), "Exception:Failed to get detail from database.");
        
        return ERR_EXCEPPTION;
    }

now I have to copy the _RecordsetPtr RecordSet of this funtion which is a public member of ABD class.

I am doing like below:

ABC class will make the connection to Database.

    ABC mConnect;
    
    mConnect.getResults(query);
    
    _RecordsetPtr lv_set = std::move(mConnect.RecordSet);

    mConnect.CloseConnection();

Above std::move is not working , and I get lv_set as null; I want to achieve that once I take recordset in local copy , I want to close the DB connection and proceed with local recordset to fetch the results Is there any way to achieve it.

My program is breaking before completing all execution

I am trying to find the Multiplication of Matrix with its transpose using Vectors. While Running program is not executing after printing my inputted matrix and breaking without doing any loops and athematic operations. Why does my program ended after 2nd for loop? Where I am wrong?

//  Multiplication of Matrix by its Transpose
#include<bits/stdc++.h>
using namespace std;
 
 int main()
 {
 int row,col;
 cout<<"ENTER ROWS:";
 cin>>row;
 cout<<"ENTER COLS:";
 cin>>col;

 vector<vector<int>> vec(row, vector<int> (row,col));
  vector<vector<int>>  tran(row, vector<int> (row,col));

 vector<vector<int>>  ans(row, vector<int> (row,col));

    for(int i=0;i<row;i++)
    {
     for(int j=0;j<col;j++)
     {
          int t;
       cin>>t;
         vec[i][j]=t;
     }
       
    } 
    cout<<"\n"<<"Orignal Matrix:"<<endl;
    for(int i=0;i<row;i++)
    {
       for(int j=0;j<col;j++)
       {
          cout<<vec[i][j]<<" ";
       }
       cout<<"\n";
    }

  for(int i=0;i<row;i++) // transpose
  {
      for(int j=0;j<col;j++)
      {
          tran[i][j]=vec[j][i];
      }
  }


  
cout<<"\n\nTranspose Matrix: \n\n";

  for(int i=0;i<col;i++)
  {
      for(int j=0;j<row;j++)
      {
        cout<<tran[i][j]<<" ";
      }
      cout<<endl;
     
  }

 for(int i=0;i<row;i++) // multiplication
 {
     for(int j=0;j<col;j++)
     {
         ans[i][0]=vec[i][0]*tran[0][j];
         ans[0][j]=vec[0][j]*tran[i][0];


     }
 }
 cout<<"\n\nMultiplied Matrix: \n\n";

  for(int i=0;i<row;i++)
 {
     for(int j=0;j<col;j++)
     {
         cout<<ans[i][j]<<" ";
     }
     cout<<endl;
 }



 } 

Output I am getting:

ENTER ROWS:3
ENTER COLS:5
2 4 5 5 6 
4 6 7 9 0
1 2 3 5 8

Orignal Matrix:
2 4 5 5 6
4 6 7 9 0
1 2 3 5 8 
 

Expected Output:

ENTER ROWS:3
ENTER COLS:5
2 4 5 5 6 
4 6 7 9 0
1 2 3 5 8

Orignal Matrix:
2 4 5 5 6
4 6 7 9 0
1 2 3 5 8 

Transpose Matrix:
2 4 1
4 6 2
5 7 3
6 9 5
6 0 8

Multiplied Matrix: 
106 112 98
112 182 82
98  82  103

How to convert std::string to raw string?

I have this string:

std::string str = "t\tt\\";

Can I convert str to raw string so it will be equal no to "t. t \" but to "t\t\\"(like I write R"t\t\\")?

I.e. if I do not use R-literal my symbols like \t \n \ will be replaced to tab symbol, new line character or . And I want convert string var in which this symbols are replaced to raw string in which they are not replaced. So can I convert string with escaping to string without escaping?

Return std::tuple containing const-reference in C++11

I have something like this (C++11)

std::tuple<const MyType&, bool>> func()
{
   return std::make_tuple(some_internal_reference, true);
}

the problem is that in the caller I cannot declare:

const MyType& obj; // this does not compile of course
bool b;

std::tie(obj, b) = func();

An idea is to return the boolean as an output param and drop the tuple, but is there a better solution?

for(char d:s) what does it mean? [duplicate]

I watched how williamlin solving cses problemset. In third problem he had this code:

`int main(){
string s;
cin>>s;
int ans=1,c=0;
char l='A';
for(char d:s){ // I don't understand this
    if(d==1){
        ++c;
        ans = max(c,ans);
    }
    else{
        l=d;
        c=1;
    }
}
cout << ans;

}`

I don't understand what does it mean for(char d:s) Pleas describe (.

How to run my thread in parallel of while loop

Here is some code which increments several chronometers in parallel:

main.cpp
using namespace std;
 
#include <stdio.h>
#include <time.h>
#include <iostream>
#include <math.h>
#include <cstdlib>
#include <unistd.h>
 
#include <iostream>
#include <sstream>
#include <thread>
#include <vector>
#include <future>
 
#include "mychrono.hpp"

 
int main()
 
{
     
    std::vector<Chronometer*> car_crono;
    Chronometer chrono, output_chrono;
    std::vector<std::thread> threads;
    std::vector<std::future<Chronometer&>> futures;
 
    std::thread th;
    //future<Chronometer> ft;

    
    for(int i = 0; i < 2; i++)
    {
        car_crono.push_back(new Chronometer);
    }
    

 
 
    while (1) {
        
 
        for(int i = 0; i<2; i++)
            {
//
//                    //threads.push_back(std::thread(&Chronometer::start_chrono, car_crono[i], std::ref(chrono)));
//                    auto ft = std::async(std::launch::async, &Chronometer::start_chrono, car_crono[i], std::ref(chrono));
//
//                std::cout << "Hello-world" << std::endl;
                futures.emplace_back(std::async(std::launch::async, &Chronometer::start_chrono, car_crono[i], std::ref(chrono)));
                

            }
        
    
        std::cout << "hello-world" << std::endl;
        
        
        
        //auto ft = std::async(std::launch::async, &Chronometer::start_chrono, car_crono[0], std::ref(chrono));
        //std::cout << "Hello-world-2" << std::endl;
        
        for(auto&& f: futures){
                std::cout << f.get() << '\n';
        }
    }
    
    car_crono.clear();
    
}
mychrono.cpp
#include "mychrono.hpp"
 
#include <time.h>
#include <iostream>
#include <cstdlib>
#include <unistd.h>
 
#include <sstream>
#include <thread>
 
 
//int Chronometer::hour(0), min(0), sec(0);
 
Chronometer::Chronometer() : hour(0), min(0), sec(0)
{
 
}
 
Chronometer& Chronometer::start_chrono(Chronometer& chrono)
{
  
  // if(chrono.hour == 0 && chrono.min == 0 && chrono.sec == 0)
  // {
    bool condition = true;
    while(condition) {
      sleep(1);
      chrono.sec++;
 
      if(chrono.sec > 59) {
        chrono.min++;
        chrono.sec = 0;
 
      }
 
      if(chrono.min > 59) {
        chrono.hour++;
        chrono.sec = 0;
        chrono.min = 0;
      }
//      if(chrono.sec == 10)
//      {
//        condition = false;
//      }
        
 
      std::cout << "chrono: " << chrono << std::endl;
 
   }
    
    return chrono;
 
  //}
 
  
}
 
 
Chronometer& Chronometer::finish_chrono(Chronometer& chrono)
{
    chrono.hour = 0;
    chrono.sec = 0;
    chrono.min = 0;
 
    return chrono;
}
 
 
std::ostream& operator<<(std::ostream& flux, Chronometer t)
{
    flux << t.hour << ":" << t.min << ":" << t.sec;
    return flux;
}
 
Chronometer& Chronometer::operator=(const Chronometer& other)
{
    // Guard self assignment
    //if (this == &other)
    return *this;
}
 
Chronometer::~Chronometer(){}

mychrono.hpp
#include <time.h>
#include <iostream>
#include <sstream>
 
#ifndef mychrono_hpp
#define mychrono_hpp
 
class Chronometer
{
    private:
        int hour, min, sec;
        //std::stringstream ss;
        //Chronometer chrono;
 
    public:
        
 
        Chronometer();
        Chronometer& start_chrono(Chronometer& chrono);
        Chronometer& finish_chrono(Chronometer& chrono);
        friend std::ostream& operator<<(std::ostream& flux, Chronometer t);
        Chronometer& operator=(const Chronometer& other);
        ~Chronometer();
 
};
 
 
#endif

My program runs well my two chronometers in parallel each other but still dependant of my while loop. For example here I will print "hello-world" once but need to wait my threads stop to print a second "hello-world" message in my while loop.

My question is how to make my threads runs in parallel an be completely independant of others instructions in my while loop ?

How to inherit an implementation of an interface from another base class not related to the interface [duplicate]

Is it possible to inherit a pure virtual function implementation from another class like the following, without having to define a wrapper around Base::foo() in Derived ?

class Interface
{
public:
    virtual void foo() = 0;
};

class Base
{
public:
    void foo() {};
};

class Derived
    : public Interface
    , public Base
{
};

int main()
{
    Derived derived;
    derived.foo();
}

The above gives the following errors:

 In function 'int main()':
21:13: error: cannot declare variable 'derived' to be of abstract type 'Derived'
13:7: note:   because the following virtual functions are pure within 'Derived':
4:18: note:     virtual void Interface::foo()
22:13: error: request for member 'foo' is ambiguous
10:10: note: candidates are: void Base::foo()
4:18: note:                 virtual void Interface::foo()

I would like to avoid defining a wrapper like the following, especially when multiple methods are concerned:

class Derived
{
public:
    void foo() override
    {
        Base::foo();
    }
};

I tried adding using Base::foo; in Derived body, but it only removes the error about ambiguous call, not the one stating that Derived is an abstract class.

mercredi 25 août 2021

How to define a multidimensional array in C++ with 'n' rows and 'm' columns and iterate values using For Loop?

I want a program that asks the number of rows and columns of the multidimensional array and then using For loop iterate values in the array.

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n, m, x;
    int a[n][m];
    cin>>n>>m;
    for(int i; i<n ; i++)
    {
        for(int j;  j<m ; j++)
        {
            cout<<"Enter the values";
            cin>>x;
            a[i][j] = x;
        }
    }
    return 0;
}

here it gets error:

main.cpp|6|warning: 'm' is used uninitialized in this function [-Wuninitialized]|
main.cpp|6|warning: 'n' is used uninitialized in this function [-Wuninitialized]|

Initialisation of Templates

Please see the following code:

// templateClassTemplate.cpp

#include <iostream>

class Account{
public:
  explicit Account(double amount=0.0): balance(amount){}

  void deposit(double amount){
    balance+= amount;
  }

  void withdraw(double amount){
    balance-= amount;
  }
  
  double getBalance() const{
    return balance;
  }

private:
  double balance;
};

template <typename T, int N>
class Array{

public:
  Array()= default;
  int getSize() const;

private:
  T elem[N];
};

template <typename T, int N>
int Array<T,N>::getSize() const {
  return N;
}

int main(){

  std::cout << std::endl;

  Array<double,10> doubleArray;
  std::cout << "doubleArray.getSize(): " << doubleArray.getSize() << std::endl;

  Array<Account,1000> accountArray;
  std::cout << "accountArray.getSize(): " << accountArray.getSize() << std::endl;

  std::cout << std::endl;
}

This code is taken from a learning course on template initialisation.

I have two questions:

  1. How is the object Array<double,10> doubleArray> initialised? There is a default constructor that takes no arguments. How is the object intialised?

  2. How is the object Array<Account,1000> accountArray initialised? I can imagine that the first template parameter instantiates an Account object, but how is it constructed?

Thanks!

Overloading std::array << operator

I'm having trouble trying to overload operator << for std::array. I tried doing it casual way as for all other collections:

std::ostream& operator<<(std::ostream& os, std::array<int> const& v1)
{
    for_each(begin(v1), end(v1), [&os](int val) {os << val << " "; });
    return os;
}

But the compiler expects me to add information about the array's size, which would not make it a general solution for any integer array. I know that if I wanted to make it for genaral type I would have to use templates, but for now I just want to make it for array of integers.

Static assert that a function returns a weakly ordered type

Minimal example:

template <typename TFunc>    
void func(TFunc f)
{
    //Do something like:
    double x{1}, y{2};
    bool z = f(x) < f(y);    //Do comparison somewhere
}

I would like to add a static_assert to the function that checks that f(x) returns a type where std::less computes. In other words I would like f(x) < f(y) to compile. I am currently doing something like this:

static_assert((decltype(f(0)){} < decltype(f(0)){}) == false, "Function f must return a weakly ordered type.");

But here I assume that the function returns a type that can be default initialized. Is there a better way to check this?

mardi 24 août 2021

Split string into vector with substring [duplicate]

How can i split a string into vector in substring? My code:

#include <iostream>
#include <vector>
using namespace std;
vector<string> split(string str, string delim)
{
   //How can I do it here?
}

int main()
{
    string str = "Hello\n_SPLITING_\nWorld!\n_SPLITING_\nHappy Coding!";
    vector<string> output = split(str, "\n_SPLITING_\n");
    for(int i = 0; i != output.size(); i++)
    {
        cout << output[i] << ";" << endl;
    }
}

and i want the output be:

Hello;
World!;
Happy Coding!;

User defined conversion assigned to const ref variable via temporary object

The code below is a simplified version of the actual problem I am facing.

Assume I do not have permission to modify class A (as it is external library), and its already widely used in my existing code base.

The const & assignment from a temporary object (direct constructor) which also return a const & member variable via implicit conversion is not valid in this case.

How do I prevent or make it legal in this case so that the caller gets the correct A value?

class A 
{
public:
    A() {  }
    A(int _r, int _g, int _b)
        : r(_r), g(_g), b(_b)
    {
    }

    ~A(){ }

    int GetR() const {  return r; }
    int GetG() const { return g; }
    int GetB() const { return b; }

private:
    int r = 0;
    int g = 0;
    int b = 0;
};

class Foo
{
public:
    Foo() : Foo(A()) {}
    Foo(int _r, int _g, int _b) : a(A(_r, _g, _b)) {}
    explicit Foo(const A& _a) : a(_a) {}

    Foo& operator=(const A& a)
    {
        *this = Foo(a);
        return *this;
    }

    operator A() const { return a; }
    operator const A&() const {  return a; }

private:
    A a;
};

int main()
{
    const A& a = Foo(200, 100, 300); 
    std::cout << a.GetR() << a.GetG() << a.GetB() << endl; // I may not get 200 100 300 here as Foo is already out of scope 

    return 0;
}

Motivation

Some background on why I am implementing a class as above. The actual purpose of class Foo is to contain 2 different objects, which actually has the same purpose, just different way of storing data internally. For example, let's say class A and class B, which stores RGB value of color in int and floating (normalized) respectively. And as mentioned above, I do not have permission to modify class A, and its already widely used in my code base.

There are tons of function in my code base which takes in const A& and const B& as a function param. So I am trying to unify this 2 classes for a particular case, where I can just pass in Foo in those places and it will work as expected.

Window for OpenVR with Vulkan needed?

When using vulkan and OpenVR for a game, do I need to create and open a window to make it work or can i just Submit the image to OpenVR?

Issue with condition variables in C++

We have implemented TaskRunner whose functions will be called by different threads to start, stop and post tasks. TaskRunner will internally create a thread and if the queue is not empty, it will pop the task from queue and executes it. Start() will check if the thread is running. If not creates a new thread. Stop() will join the thread. The code is as below.

bool TaskRunnerImpl::PostTask(Task* task) {
  tasks_queue_.push_back(task);
  return true;
}

void TaskRunnerImpl::Start() {
  std::lock_guard<std::mutex> lock(is_running_mutex_);
  if(is_running_) {
    return;
  }
  is_running_ = true;

  runner_thread_ = std::thread(&TaskRunnerImpl::Run, this);
}

void TaskRunnerImpl::Run() {
  while(is_running_) {
    if(tasks_queue_.empty()) {
      continue;
    }
    Task* task_to_run = tasks_queue_.front();
    task_to_run->Run();
    tasks_queue_.pop_front();

    delete task_to_run;
  }
}

void TaskRunnerImpl::Stop() {
  std::lock_guard<std::mutex> lock(is_running_mutex_);
  is_running_ = false;
  if(runner_thread_.joinable()) {
    runner_thread_.join();
  }
}

This code is working fine. Continuously tasks are getting pushed and thread is executing those tasks. We want to use conditional variables now otherwise the thread will be continuously checking whether the task queue is empty or not. We implemented as below.

  • Thread function (Run()) will wait on condition variable.
  • PostTask() will signal if some one posts a task.
  • Stop() will signal if some one calls stop.

Implemented code as below.

bool TaskRunnerImpl::PostTask(Task* task, uint64_t delay_milliseconds) {
    std::lock_guard<std::mutex> taskGuard(m_task_mutex);
    tasks_queue_.push_back(task);
    m_task_cond_var.notify_one();
    INFO("{} : {} : {}", __FUNCTION__, delay_milliseconds, tasks_queue_.size());
    return true;
}

void TaskRunnerImpl::Start() {
    INFO("{}", __FUNCTION__);
    std::lock_guard<std::mutex> taskGuard(m_task_mutex);

    if(!is_running_) {
        is_running_ = true;
        runner_thread_ = std::thread(&TaskRunnerImpl::Run, this);
    }
}

void TaskRunnerImpl::Run() {
    while(true) {
        INFO("{} : {}", __FUNCTION__, 1);

        {
            std::unique_lock<std::mutex> mlock(m_task_mutex);
            INFO("{} : Locked Mutex", __FUNCTION__);
            m_task_cond_var.wait(mlock, [this]() {
                INFO("{} : Checking Condition", __FUNCTION__);
                return !(is_running_ && tasks_queue_.empty());
            });


                INFO("{} : Came out of wait", __FUNCTION__);
            if(!is_running_) {
                return;
            }

           INFO("{} : Escaped if cond", __FUNCTION__);
            if(!tasks_queue_.empty()) {
                INFO("{} : {} : {}", __FUNCTION__, 2, tasks_queue_.size());    // NO LOGS AFTER THIS GETTING PRINTED
                Task* task_to_run = tasks_queue_.front();
                task_to_run->Run();
                INFO("{} : Deleting Task", __FUNCTION__);
                tasks_queue_.pop_front();
                INFO("{} : After Deletion : {}", __FUNCTION__, tasks_queue_.size());
                delete task_to_run;
            }
        INFO("{} : Out of scope", __FUNCTION__);
        }

        INFO("{} : End of iteration", __FUNCTION__);
    }

    INFO("{} : returning", __FUNCTION__);
}

void TaskRunnerImpl::Stop() {
    {
        std::lock_guard<std::mutex> taskGuard(m_task_mutex);
        is_running_ = false;
        INFO("{} : Signalling STOP", __FUNCTION__);
        m_task_cond_var.notify_one();
    }

    INFO("{} : {}", __FUNCTION__, 1);

    if(runner_thread_.joinable()) {
        runner_thread_.join();
    }
}

Not sure what is wrong with the code. I am getting following output.

TaskRunnerImpl.cpp:34:INFO: Start
TaskRunnerImpl.cpp:45:INFO: Run : 1
TaskRunnerImpl.cpp:49:INFO: Run : Locked Mutex
TaskRunnerImpl.cpp:51:INFO: operator() : Checking Condition
TaskRunnerImpl.cpp:29:INFO: PostTask : 0 : 1
TaskRunnerImpl.cpp:29:INFO: PostTask : 0 : 2
TaskRunnerImpl.cpp:51:INFO: operator() : Checking Condition
TaskRunnerImpl.cpp:56:INFO: Run : Came out of wait
TaskRunnerImpl.cpp:61:INFO: Run : Escaped if cond
TaskRunnerImpl.cpp:63:INFO: Run : 2 : 2

That means the log is getting printed before executing the task and after that no logs. Usually PostTask() will be called continuously to post the tasks to queue. But with the new code no logs after task run. So I am assuming the thread function is holding the mutex and PostTask() is not able to push the tasks to queue. But unable to understand why there are no logs after executing the task. If I revert back to original code, the code is working as expected. Can anyone please let me know if there is any issue with the code.

What's the difference between =delete for templates and just using explicit?

I was reading Explicitly defaulted and deleted special member functions, and saw that in order to call only the function f with double and avoid an implicit conversion, one could write this (from the same page):

struct OnlyDouble
{
    void f(double d);
    template<class T> void f(T) = delete;
};

Is there a reason why one would write the code above instead of this code below?

struct OnlyDouble
{
    explicit void f(double d);
};

Any difference, or is there some extra behavior that I don't know of?

How does std::bind Results in calling the Copy Constructor Several Times

I have been trying to understand how std::bind works. So working up with different examples. Below is the sample program whose output i am unable to understand.

VERSION 1

class NAME
{
  public:
    void f()
    {
        std::cout<<"f"<<std::endl;
    }
    NAME()
    {
        std::cout<<"default constructor"<<std::endl;
    }
    NAME(const NAME&)
    {
        std::cout<<"copy constructor"<<std::endl;
    }
};
int main()
{
   std::cout << "Hello World" << std::endl; 
   NAME n;
   std::function<void ()> callable = std::bind(&NAME::f, n);
   
   
   return 0;
}

The output of the above version 1 is as follows:

Hello World
default constructor
copy constructor
copy constructor

I know that the argument passed will be copied, so the copy constructor should be called only one time but in the output above the copy constructor is called twice. Why/how is this happening? Is it because the new callable that is created using std::bind will be used to initialize another callable using std::function on the lhs?

VERSION 2

int main()
{
   std::cout << "Hello World" << std::endl; 
   NAME n;
   std::function<void ()> callable = std::move(std::bind(&NAME::f, n));
   return 0;
}

The output of VERSION 2 is as follows:

Hello World
default constructor
copy constructor
copy constructor
copy constructor

In the output above(for version 2) when i use std::move, why/how is the copy constructor called thrice?

VERSION 3

int main()
{
   std::cout << "Hello World" << std::endl; 
   NAME n;
   auto callable = std::bind(&NAME::f, n);
   return 0;
}

The output of version 3 is as follows:

Hello World
default constructor
copy constructor

In this case(version 3) why/how is the copy constructor called only once?

VERSION 4

int main()
{
   std::cout << "Hello World" << std::endl; 
   NAME n;
   auto callable = std::move(std::bind(&NAME::f, n));
   return 0;
}

The output of version 4 is as follows:

Hello World
default constructor
copy constructor
copy constructor

What happens in this case(version 4) when we use auto and std::move(), why/how is the copy constructor called twice.

PS: The program is executed on an online compiler: Online compiler Used

How can I define a function that takes a lambda with capture as parameter?

I have this function that returns true if any of the elements in the list match the given predicate

bool _any(bool (*predicate)(MyStructure), list<MyStructure> arr)
{
    for (int i = 0; i < arr.size(); i++)
    {
        if (predicate(arr.front()))
            return true;
        arr.pop_front();
    }
    return false;
}

This works for very simple lambdas, but if the given lambda needs to capture this then I have an error which I can't figure out how to fix.

Assert::IsTrue(_any(
    [this](MyStructure t)
    {
        return t._name == "NAME_SEARCHED" &&
            t._type == "TYPE_SEARCHED" &&
            _any([](OtherStruct o) { return o._name == "SEARCHED_2"; }, t._children);
    },
    myList));

Error:

cannot convert argument 1 from 'UTests::<lambda_e8bda0383e9f0c2ae44be631a7424852>' 
to 'bool (__cdecl *)(MyNameSpace::MyStructure)'

(N.B. : _any that takes an OtherStruct is defined as well).

Using c++ 11 on macOS using makefile

On macOS Big Sur while compiling using makefile, seeing the error: fatal error 'mutex' file not found. since this is related to C++ have already compiled with -std=c++11. Still seeing the error.

any idea as to how to solve this error.

Why this code outputs garbage value after swapping the values?

Take two numbers as input and swap them and print the swapped values.You do not need to print anything, it has already been taken care of. Just implement the given function.And the functions looks like this.

 pair < int, int > swap(pair < int, int > swapValues) {
         int c;
         c=swapValues.first; 
         swapValues.first=swapValues.second;
         swapValues.second=c;
         cout<<swapValues.first<<" "<<swapValues.second<<"\n";
    
         }

What is the point of using both malloc and calloc if their work is the same? [duplicate]

If both malloc and calloc allocate memory contiguously then why two functions were made? We could work with only one. I understand their might be slight differences and pros and cons for each function but still, why both were made? We could do the work with malloc only instead of calloc.

Is it possible for a visitor to operate over multiple projects?

I'm trying to add a visitor to an existing library. The visitor must be able to visit some classes from separate projects.

Let's say my solution have the following projects: ProjectA, ProjectB and they contain 1 class each respectively: ClassA, ClassB. Since the visitor is only an implementation of a class member outside of the class, I think its dependency won't allow it to be placed at another project. So if I want to create a visitor which can visit both ClassA and ClassB objects, I can't use a simple visitor.

Is this assessment correct?

I was thinking about a couple of solutions to overcome this.

  1. Move one the classes to the other projectand implement visitor there (this isnot a feasible solution).
  2. Add an extra indirection. Create a class for the visitor implementation for each project. And create a "head visitor" which would use these implementation objects.

Am I missing something? Is there a better way to do this?

lundi 23 août 2021

SFINAE for true_type and false_type in std::conditional

What's the best way to make this compile?

// Precondition: Dims is either a pointer or std::map.

using T = std::conditional_t<std::is_pointer_v<Dims>,
    std::remove_pointer_t<Dims>,
    typename Dims::mapped_type>;

When Dims is a pointer, I am getting:

error: template argument 3 is invalid

How do I make it work in SFINAE manner, when condition is true?

In C++, Is there a way to define template behavior based on whether the input class is abstract?

Background: I've inherited a large system that makes use of templates to store meta data about classes, that may have colored some of the assumptions inherent in this question.

I'm making use of a template registration system that is partially based on an answer found here: Is there a way to instantiate objects from a string holding their class name? . Macros are a no go in my system, as is the use of boost (or really any third party API).

Question: Can I have templates that behave differently based on whether the input type is abstract versus concrete?

I'm looking for something like this (Code used here directly copied from the accepted answer in the linked question):

struct BaseFactory {
    typedef std::map<std::string, Base*(*)()> map_type;

    static Base * createInstance(std::string const& s) {
        map_type::iterator it = getMap()->find(s);
        if(it == getMap()->end())
            return 0;
        return it->second();
    }
protected:
    static map_type * getMap() {
        // never delete'ed. (exist until program termination)
        // because we can't guarantee correct destruction order 
        if(!map) { map = new map_type; } 
        return map; 
    }

private:
    static map_type * map;
};

template<typename T>
struct DerivedRegister : BaseFactory { 
    DerivedRegister(std::string const& s) { 
        getMap()->insert(std::make_pair(s, &createT<T>));
    }
};

// in derivedb.hpp
class DerivedB {
    ...;
private:
    static DerivedRegister<DerivedB> reg;
};

// in derivedb.cpp:
DerivedRegister<DerivedB> DerivedB::reg("DerivedB");

Except that I would like DerivedRegister to behave differently based on whether T is abstract versus concrete. In the case where T is abstract, I would expect DerivedRegister to not register the type with the map.

As I mentioned in the background, I've already inherited an existing system which already exists on the class hierarchy (abstract or concrete). It was trivial to modify this existing system to add the map registration; however, the abstract classes are causing problems since calling new on them isn't valid.

Adding additional layers of inheritance and templating between BaseFactory and DerivedRegister wouldn't be a problem; however, DerivedRegister already exists on every class and I can't change that.

I recognize that I could just add a unique registration system independent of the existing template classes and only add it to the concrete classes. I'm specifically asking if there is a solution where I can avoid that in C++11 without using third party libraries (lots of restrictions I know...).

C++ Conditional typedef with more than two type

I am trying to do something like this .

if (flow1)
  {
     typedef template_class<user_defined_type1> x;
  }
else if (flow2)
  {
     typedef template_class<user_defined_type2> x;
  }
else if (flow3)
  {
     typedef template_class<user_defined_type3> x;
  }
else 
  {
     typedef template_class<user_defined_type4> x;
  }

I checked the answers for this question How to make a conditional typedef in C++ but I'm not sure how I can use std::conditional if I have more than 1 type ? Is it even possible to do something like this ?

Including a Boost C++ header causes dlopen() to return error: _ZTVN10__cxxabiv117__class_type_infoE

Building a C HelloWorld.so (shared object) below with a C++ myatomic library Boost header

myatomic.cpp

...
#include <boost/system/error_code.hpp>
...

Loading HelloWorld.so with dlopen() returns error: _ZTVN10__cxxabiv117__class_type_infoE

If that Boost header is commented-out, then dlopen() succeeds?

HelloWorld.yaml

...    
Common:
  Sources:
    - Folder: src
      Files:
        - HelloWorld.h
        - HelloWorld.c
  ConanLibs:
     - CONAN_PKG::myatomic
Linux:
  CompilerOptions:
    - -fPIC
    - -fmax-errors=50
    - -Wno-main
    - -Wno-unused-variable
    - -Wno-pointer-to-int-cast
    - -Wno-implicit-function-declaration
    - -Wno-int-conversion
  LinkerOptions:
    - -ldl
    - -lpthread
    - -lrt
    - -lstdc++
  

Does Boost C++ under linux need to built with specific options? Maybe gcc vs g++ issues?
Added -lstdc++ to HelloWorld linker options but to no avail. :(

c++ network client\server programm, some steps

I'm study the c++ language, write my final work for the university. The whole program is almost ready but there are network problems. Can you tell me code examples or articles where i can get answers to the next steps that i am missing? (in simple language for dummies).

Steps:

  1. Server: Sent Broadcast (ex. lan network 192.168.1.0), packet on port 12345

  2. Clinet (maybe two or more): Receive on port 12345 packet and answer to server "i'm here my ip 192.168.1.x", and wrote server ip to self memory.

  3. Client send variable data (text) to server ip (from step 2) and listen answer from server (true or false) and working self funcitons.

  4. Server from step 3, listen variable data, working with it, and send to sender answer (true or false).

Better w\o libraries if possible.

Karatsuba Multiplication with Strings C++

I am struggling to get the correct output for my Karatsuba multiplication using strings. I am inputting numbers in the format: int1 int2 base, where int1 and int2 are the numbers to be multiplied, and base is the numerical base.

My output is in the format add mult, where add represents the "School Method Addition" of int1 and int2 and mult represents the Karatsuba multiplication.

For INPUT:

1231000323012031333233201313312322110321130022201222133322033312000313333113222010300133031211311 10203302031023112301210030203002033323 4

I should get the OUTPUT:

1231000323012031333233201313312322110321130022201222133322110121303011022232123220331002033311300 
490306232475117580392628428529303475424922697851904379576867313243824589283681700912220831308362948505562812188832489817917769878090

I am unsure what's going wrong, any help would be appreciated.

Below is my code:

// The main function that adds two bit sequences and returns the addition

string add_strings(string a, string b){

    string result ;  // To store the sum bits
 
    // make the lengths same before adding
    int length = max(a.length(), b.length()) ;
    while (a.length() < length) a.insert(0, "0") ;
    while (b.length() < length) b.insert(0, "0") ;

    // Initialize carry
    int carry = 0 ;
 
    // Add all bits one by one
    for (int i = length - 1 ; i > -1 ; i--)
    {
        int aBit = a[i] - '0' ;
        int bBit = b[i] - '0' ;
 
        // Boolean expression for sum of 3 bits
        int sum = aBit + bBit + carry ;

        // Update carry
        carry = sum / 10 ;

        // Update sum for string insertion
        sum = sum % 10 ;
 
        // Update sum result
        result.insert(0, to_string(sum)) ;
    }
 
    // if overflow, then add the carry
    if (carry)  result.insert(0, to_string(carry)) ;

    return result.erase(0, min(result.find_first_not_of('0'), result.size() - 1)) ;
}

// Function for find difference of larger numbers

string sub_strings(string a, string b) {

    // make the lengths same before subtracting
    int length = max(a.length(), b.length()) ;
    while (a.length() < length) a.insert(0, "0") ;
    while (b.length() < length) b.insert(0, "0") ;
 
    // Initialise result string
    string result = "";
    int diff ;
 
    int carry = 0;
 
    // Subtraction
    for (int i = length - 1; i > -1; i--) {
 
        // Find difference of each digit
        diff = (a[i] - '0') - (b[i] - '0') - carry ;

        if (diff >= 0) result.insert(0, to_string(diff)) ;
            
        else {
            int j = i - 1 ;
            while (j >= 0) {
                a[j] = ((a[j] - '0') - 1) % 10 + '0' ;
                if (a[j] != '9') break ;
                else j-- ;   
            }
            result.insert(0, to_string(diff + 10)) ;
        }
 
     }
 
    // reverse resultant string
    reverse(result.begin(), result.end());
 
    return result.erase(0, min(result.find_first_not_of('0'), result.size() - 1)) ; 
}

// Need this function for strings greater than 3 in length

string Karatsuba(string a, string b, int base){

    // Pad out each recursive call to ensure they are the same size
    int length = max(a.length(), b.length());
    while (a.length() < length) a.insert(0, "0") ;
    while (b.length() < length) b.insert(0, "0") ;

    // Initialise strings
    string return_karat = "" ;
 
    // Base cases
    if (length == 0) return 0 ;
    if (length == 1) return to_string((a[0] - '0')*(b[0] - '0')) ;

    // Split a into (a0, a1) and b into (b0, b1)
    int k = floor(length / 2) ;
    int upper = ceil(length / 2) ;

    // convert the above vectors to strings for multiplication
    // need separate for loops to prevent out of range errors
    string a0 = a.substr(0, k) ;
    string a1 = a.substr(k, upper) ;
    string b0 = b.substr(0, k) ;
    string b1 = b.substr(k, upper) ;

    // Compute the three products
    // p0 = a0b0, p1 = (a1+a0)*(b1+b0), p2 = a1b1
    string p0 = Karatsuba(a0, b0, base) ;
    string p1 = Karatsuba(add_strings(a1, a0), add_strings(b1, b0), base) ;
    string p2 = Karatsuba(a1, b1, base) ;

    //ab = p2 * (pow(base, 2*k)) + (p1 - (p2 + p0)) * pow(base, k) + p0
    // string term1 = p2 * (pow(base, 2*k))
    string term2 = sub_strings(add_strings(p0, p2), p1) ;
    // string term3 = p0

    for (int i = 0; i < 2 * (length - k); i++) p0.append("0") ;
    for (int i = 0; i < length - k; i++) term2.append("0") ;
        
    string result = add_strings(add_strings(p2, p0), term2) ;

    return result.erase(0, min(result.find_first_not_of('0'), result.size() - 1));
}