mardi 30 juin 2020

Why in C++11 we move from one function in vector::resize to 2 version?

I'm asking this because im developing a class library. (As i can see in cplusplus.com) in C++98 we had only one version from the resize funcion:

void resize (size_type n, value_type val = value_type());

this way the function works if you want to specify the second argument or not. But in C++11 they change it to 2 different version:

void resize (size_type n);
void resize (size_type n, const value_type& val);

Is any special reason for this?

How do I tell the element count of array declared as: std::unique_ptr

I have this variable declaration:

std::unique_ptr<uint8_t[]> data;

How do I tell the element count if this array is given to me?

Debug-Compiled Server crashes on Database opening

quick background...
have been running AC for WoW 3.3.5 on my server for almost 3 years.(previously TrinityCore)
running older version on an older system.
went to update with latest commits last week and found dependency updates.
reverted back to previous version i was running, which runs fine on main server.
installed on dev server to do some updates and testing config settings using 'Release' build.
client hangs on "Connecting" or "Getting Character List", which i will post about separately. (is not instance reset queries, ~11 threads on "thread_wait")

built server in debug mode to try to track down whats going on.
started in debug mode, crashed on "Opening DatabasePool 'acore_world'.".

bt shows this is in "request = (SQLOperation*)(m_queue->dequeue());" found at 'src/common/Database/DatabaseWorker.cpp:29'.

bt full
#0 0x00007ffff74129ef in ACE_Activation_Queue::dequeue (this=0x7ffff4c7f120, tv=0x0) at ../../ace/Activation_Queue.cpp:89
mb = 0x0
#1 0x00000000020b1874 in DatabaseWorker::svc (this=0x7ffff4cc61e0) at /backups/local/src/azerothcore/src/common/Database/DatabaseWorker.cpp:29
request = 0x0
#2 0x00007ffff74b7ccd in ACE_Task_Base::svc_run (args=0x7ffff4cc61e0) at ../../ace/Task.cpp:271
t = 0x7ffff4cc61e0
status = <optimized out>
thr_mgr_ptr = <optimized out>
#3 0x00007ffff74b9446 in ACE_Thread_Adapter::invoke_i (this=0x7ffff4ca0070) at ../../ace/Thread_Adapter.cpp:161
hook = <optimized out>
func = 0x7ffff74b7c60 <ACE_Task_Base::svc_run(void*)>
arg = 0x7ffff4cc61e0
cancel_flags = 4259842
status = 0x0
#4 0x00007ffff74b94fb in ACE_Thread_Adapter::invoke (this=0x7ffff4ca0070) at ../../ace/Thread_Adapter.cpp:96
exit_hook_instance = <optimized out>
exit_hook_maybe = {instance_ = 0x0}
exit_hook_ptr = 0x7ffff3a69000
exit_hook = @0x7ffff3a69000: {thread_control_ = {tm_ = 0x7ffff4cda140, status_ = 0x0}}
#5 0x00007ffff628f5bd in start_thread () from /lib64/libpthread.so.0
No symbol table info available.
#6 0x00007ffff559e59d in clone () from /lib64/libc.so.6
No symbol table info available.

i am running mageia 5, gcc 4.9.2, cmake 3.0.2, glibc 2.20.27, libACE 6.0.3

i am thinking this is a DB problem, as i have a lot of "MYSQL server has gone away" msgs, and server will hang on shutdown. (cant debug that far, so dont know where or why)

thanks for looking.

Initialization of a struct defined in a templated parent class

I have defined a struct within the protected section of a parent class, which I would like to use in an inherited class.

This works as expected if the parent/child classes aren't templated classes. But does not compile as-is below.

Specifically, the compiler (clang 8.0.1) reports:

inheritance_example.cpp:33:26: error: unknown type name 'Node'
        this->head = new Node(toAdd);

From what I have read, I am guessing that the template type specification isn't being assigned to Node, and is thus not being found by the inherited class, but trying the fixes I have found in that vein (i.e. add something along the lines of using Parent<T>::Node, or add a type specifier to the call to the Node constructor), have not worked for me.

Any ideas on how to fix this issue?

#include<iostream>

template <class T>
class Parent 
{
protected:
   struct Node
   {
      Node(int value) 
      {
         this->data = value;
         this->next = nullptr;
      };

      ~Node() {};
      Node* next;
      int data;
   };

   Node* head;

public:
   Parent() {};
   ~Parent() {};
};

template <class T>
class Child : Parent<T>
{
public:

   Child() 
   {
      this->head = nullptr;
   };

   ~Child()
   {
      delete this->head;
      this->head = nullptr;
   };

   void dummyAdd(T toAdd) {
      this->head = new Node(toAdd);
   };

   void dummyPrint() 
   {
      std::cout << this->head->data << std::endl;
   };
};

int main() 
{
   Child<int> t;
   t.dummyAdd(5);
   t.dummyPrint();
   return 0;
}

Why am I getting the wrong output for this C++ code? (one of the problem of hackerrank)

This is the program for printing out sum of array elements. It is showing run time error. The output is coming out to be 0 instead of printing out the sum of the elements.

#include<iostream.h>
using namespace std;
void simpleArraySum()   
{
    int ar[100],n,i,sum=0;

    for(i=0;i<n;i++)
    {
        sum=sum + ar[i];
    }

    cout<<sum;
}
int main()
{
    int ar[100],n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>ar[i];
    }

    simpleArraySum();
    return 0;
}

c++ class using a lambda in constructor

Using c++11 I want to create a class that uses a lambda as part of a calculation.

//contrived sample of potential usage
void random_class::some_function(void)
{
 auto an_object = new my_custom_object(5, [this](){ return random_class_member * 5; });
 an_object.do_some_processing();
 random_class_member++;
 an_object.do_some_processing();
}

I am not quite sure how to go about declaring and defining my_custom_object.

class my_custom_object
{
public:
 template <typename Proc>
 my_custom_object(int a, Proc p)
 {
  privatea = a;
  privatep = p;
 }
 void do_some_processing()
 {
  privatea += privatep();
 }
private:
 int privatea;
 Proc privatep;
}

unknown type name 'Proc'

How do I remove element pointed to by iterator in a C++ list?

How do I remove element pointed to by iterator in a C++ list? why does not this work?

int main()
{
    list<int> l;
    l.push_back(5);
    l.push_back(6);

    
    for(auto &it: l)
    {
        l.erase(*it);
    }

    return 0;
}

How to record a specific window in any position using ffmpeg? [duplicate]

I know that already exists an question like this (How to record a specific window using ffmpeg?), but this answer don't work for me.

I want to record a specific window using FFmpeg in any position and when I move the window too.

How can I do this?

Force a C++ class to have aligned attributes

Consider this class:

class C3
{
public:
    uint16_t p1;
    uint16_t p2;
    uint8_t p3;
};

sizeof(C3) is 6. Is there any compiler routine to bypass alignment and force it's size to be 5? I tried to use alignas without success...

invalid type 'float*[float]' for array subscript

I want to display the range of x and f(x) and keep f(x) in array but i always get this error:

invalid type 'float*[float]' for array subscript

can someone help me? I'm still stuck.

Here's the code:

#include <iostream>
#include <cmath>
#include <math.h>
using std::cin;
using std::cout;

using namespace std;
void displayValue(float funx[], float j, float x);

int main()
{
    float num9[]={};
    float a, r;
    displayValue(num9, a, r);

    return 0;
}
void displayValue(float funx[], float j, float x)
{
    float i;
    cout << "Please enter range of x: " << endl;
    for (i=0; i<1; i++)
    {
        cin >> x >> j;
    }
    for (float i=1; i<=160.5; i++)
    {
        x+=0.5;
        funx[i]=1/sin(x)+1/tan(x);
         //1.2 Display f(x) and x within the range
    }cout << x << " = " << funx[i] << "\n";

}

How to get the lowest number of one column in a two dimensional array in C++?

I have a simple program to get from the user the lowest & highest temperature, then I must make the program get the average of the lowest & highest temperature of the day. I should put the 7days,low,high in a two dimensional arrays name temp `temp[7][2]={0};. so I made the program and it's work well and this is the code;

    //declare arr & varaibles 
    int temp[7][2]={0}; // temperature array 
    double totalHigh=0,totalLow=0; //total low temp days & total high temp days
    int high=temp[0][0],low=temp[0][0];// assign the first row & column in array to get the highest & lowest number
    
    for(int row=0;row<7;row+=1){ // for loop to get through every row 
        cout << "Day " << row+1 << endl; 
        cout << "Low: "; cin >> temp[row][0]; // first column is for low temp days
        totalLow += temp[row][0] ; // get the total low days from the user
        cout << "High: "; cin >> temp[row][1]; // second column is for high temp days
        totalHigh += temp[row][1]; // get the total high days from the user
    }

    for(int j=0;j<7;j+=1){ // go through first column to get the high number of it
        if(high < temp[j][0]){
            high = temp[j][0];
        }
    }

    for(int j=0;j<7;j+=1){ // go though second column to get the low number of it
        if(low > temp[j][1]){
            low = temp[j][1];
        }
    }

    //display on screen 
    cout << fixed<< setprecision(2);
    cout << "Low: "<< totalLow/7 << endl; //get the average of low
    cout << "High: " <<totalHigh/7 << endl;// get the average of high
    cout << "Lowest Of High column: " << low << endl;
    cout << "Highst Of Low column: " << high << endl;

but I should also get the highest number of low column & the lowest number of high column. i get the lowest number of high column, but when I make the loop to get the lowest number it doesn't work. this is the code of the two loops that go through every column and get them;

    for(int j=0;j<7;j+=1){ // go through first column to get the high number of it
        if(high < temp[j][0]){
            high = temp[j][0];
        }
    }

    for(int j=0;j<7;j+=1){ // go though second column to get the low number of it
        if(low > temp[j][1]){
            low = temp[j][1];
        }
    }

but second loop is not working while the first loop is working, can anyone tell me why the second loop is not working?

Will the old value be updated after the 'do-while'loop and before 'while' loop?

In 《c++ concurrency in action》page 217, enter image description here

Will the old value be updated after the 'do-while'loop and before 'while' loop? Then the hazard pointer is set to the wrong old_head?

Why is moving assignment operator called?

In the following code:

#include <bits/stdc++.h>

using namespace std;

class A {
public:
    A(const A& a) noexcept { cout << "copy constructor" << endl; }
    A& operator=(const A& a) noexcept { cout << "copy assignment operator" << endl; return *this;}
    A(A&& a) noexcept { cout << "move constructor" << endl; }
    A& operator=(A&& a) noexcept { cout << "move assignment operator" << endl; return *this;}

    A() { cout << "default constructor" << endl; }
    A(int val) { cout << "value constructor" << endl; }

private:
    int value;
};

A operator"" fo(unsigned long long value)
{
    return A(static_cast<int>(value));
}

int main()
{
    A a;       // default constructor
    A b = a;   // copy constructor
    b = a;     // copy assignment operator
    a = 123fo; // value constructor, move assignment operator
    return 0;
}

In the expression a = 123fo, value constructor is called because of A(static_cast<int>(value)); Please tell me why move assignment operator is called? Is it because A tempObj; tempObj = A(static_cast<int>(value)); I can't figure it out what exactly happened in the return expression.

How to encapsulate a function so that it can be called by only one other function within the same class?

There is a function that we would like only one other function to be the sole caller of:

void bar(){

}

void foo(){

}

void baz(){

}

All three functions are located within the same class. We would like foo() to be able to call bar(), but not allow baz() to call bar().

So far, this answer seems to suggest the solution is to either have a lambda function within a function, or to create an struct / anonymous struct within a function.

Can we have functions inside functions in C++?

Is there a way we can achieve our goal, without having to move bar() within foo() ie - without having to create a lambda or struct within foo ?

This is just a technical experiment to explore whether it is possible or not - it is not about what we "should" be doing, but rather to simply see if it is possible.

lundi 29 juin 2020

How can I record a window using ffmpeg by id?

I want to get the id of the window by name using c++ or qml and record the specific screen using this id in ffmpeg.

ffmpeg -f x11grab -wid 0x6200012 -s 1920x1052 -r 30 -i :0.0+0,0

How can I do this?

it's not necessary to be the id, can be the offset-x and offset-y, I just want to record the window in any position.

C++: What is the order of destructor call with methods?

I got this code:

Edit: The full code:

#include <iostream>
using namespace std;

class A {
    public:
    A() {}
    A(const A& a) {
         cout << "A copy ctor" << endl;
    }
    virtual ~A() {
         cout << "A dtor" << endl; 

    }
    virtual void type() const { 
        cout << "This is A" << endl; 

    }
};

class B: public A {
    public:
    B(){}
    virtual ~B() {
         cout << "B dtor" << endl; 
    }
    void type() const override {
         cout << "This is B" << endl; 
    }
};

A f(A a) {
    a.type();
    return a;
}

const A& g(const A& a) {
    a.type();
    return a;
}

int main() {
    A* pa = new B();
    cout << "applying function f:" << endl;
    f(*pa).type();
    cout << "applying function g:" << endl;
    g(*pa).type();
    delete pa;
    return 0;
}

I noticed when debugging the code that after making and passing a copy of *pa to f and ending the function the destructor of the copy (*pa) that was passed to f is not called. Only when type() ended (the same line) both the copies (I assume) were erased by the destructors

I was sure that when ending the function a destructor will be called and erase the current copy which did not happened in this case. I would like to get an explanation to the order in which the constructors and desturctors are being called in the code (I am not very knowledgeable about the order when methods are involved and I could not find much about it online).

thank you.

What happens when std::move() is called without assignment [duplicate]

What happens when I just use std::move without any assignment?

std::string s = "Moving";
std::move(s);  //What happens on this line to s?
//is s still valid here?

Were all implementations of std::vector non-portable before std::launder?

When emplace_back() is called on std::vector instance, an object is created in a previously allocated storage. This can be easily achieved with placement-new, which is perfectly portable. But now, we need to access the emplaced element without invoking undefined behavior.

From this SO post I learned that there are two ways of doing this

  1. use the pointer returned by placement-new: auto *elemPtr = new (bufferPtr) MyType();

  2. or, since C++17, std::launder the pointer casted from bufferPtr
    auto *elemPtr2 = std::launder(reinterpret_cast<MyType*>(bufferPtr));

The second approach can be easily generalized to the case, where we have a lot of objects emplaced in adjacent memory locations, as in std::vector. But what people did before C++17? One solution would be to store pointers returned by placement-new in a separate dynamic array. While this is certainly legal, I don't think it really implements std::vector [besides, it's a crazy idea to separately store all the addresses that we know already]. The other solution is to store lastEmplacedElemPtr inside std::vector, and remove an appropriate integer from it -- but since we don't really have an array of MyType objects this is probably also undefined. In fact, an example from this cppreference page claims that if we have two pointers of the same type that compare equal, and one of them can be dereferenced safely, dereferencing the other can be still undefined.

So, was there a way to implement std::vector in a portable way before C++17? Or maybe std::launder is indeed a crucial piece of C++ when it comes to placement-new, that was missing since C++98?

I'm aware that this question is superficially similar to a lot of other questions on SO, but as far as I can tell none of them explains how to legally iterate over objects constructed by placement-new. In fact, this is all a bit confusing. For instance comments in the example form cppreference documentation of std::aligned_storage seem to suggest that there has been some change between C++11 and C++17, and a simple aliasing-violating reinterpret_cast was legal before C++17 [without the need for std::launder]. Similarly, in the example from documentation of std::malloc they simply do a pointer arithmetic on a pointer returned by std::malloc (after static_cast to the correct type).

By contrast, according to the answer to this SO question when it comes to placement-new and reinterpret_cast:

There have been some significant rule clarifications since C++11 (particularly [basic.life]). But the intent behind the rules hasn't changed.

C++: Need help understanding operator-overloading error

I got this code:

1 #include <iostream>
2 using namespace std;
3
4 class B {
5 private:
6      int n;
7 public:
8      B(int x) : n(x) {}
9      B operator +(B& b) {
10         return B(n+b.n);
11     }
12     friend ostream& operator <<(ostream &out, const B& b) {
13         out << "B: " << b.n;
14         return out;
15     }
16     bool operator <(const B& rhs) const{
17         return n < rhs.n;
18     }
19 };
20
21 B smaller (const B& b1, const B& b2) {
22     if(b1 < b2)
23         return b1;
24     else
25         return b2;
26 }
27
28 int main() {
29     B b1(1), b2(2), b3(3);
30     const B b4 = b1 + (b2 + b3);
31     cout << smaller(b1,b2) << endl;
32     return 0;
33 }

I was asked to point out the errors (explain them) and supply a fix, after finding two and fixing them I got the above code.

When trying to compile it on Visual Code I noticed that line 30 is giving out an error without me understanding why. The error I got was :

no match for 'operator+' (operand types are 'B' and 'B')

and

cannot bind non-const lvalue reference of type 'B&' to an rvalue of type 'B'

After searching on google and finding nothing I tried varius things including adding a const to the parameter in line 9 (operator +) which fixed the problem. I still dont understand what was the problem and I would like to get an explanation.

thank you.

dynamic_cast<> question using Stroustrup example

I'm testing a dynamic_cast<> example in Stroustrup C++ 4th Ed Page 642 and it does not compile. I'm using the following picture directly from the book trying to learn how it works. Does anyone know if this is Eratta (its not in his published errata doc) or I have misread something?

Stroustrup Graphic, dashed line represents protected: Page 642 graphic

#include <iostream>
using namespace std;

// H = Ival_box
class H {
};

// G = Ival_slider
class G : public H {
};

// I = BBwindow
class I {
};

// F = BB_slider
class F : public I {
};

// X = BB_ival_slider
class X : public G, protected F {
};


int main(int argc, char *argv[])
{
    // works
    X xx{};
    if (auto p = dynamic_cast<G*>(&xx))
        cout << "X*...G*" << endl;

    // works
    G gg{};
    if (auto p = dynamic_cast<H*>(&gg))
        cout << "G*...H*" << endl;

    // compilation error, 'I' is not polymorphic
    I ii{};
    if (auto p = dynamic_cast<H*>(&ii))
        cout << "I*...H*" << endl;

    return 0;
}

Compilation and results:

clang++ -std=c++11 -pedantic -Wall test164.cc && ./a.out
test164.cc:31:18: error: 'I' is not polymorphic
    if (auto p = dynamic_cast<H*>(&ii))
                 ^                ~~~
1 error generated.

Compilation and results with error commented out:

clang++ -std=c++11 -pedantic -Wall test164.cc && ./a.out
X*...G*
G*...H*

Creating shopping cart

for my class were creating a mini store, and I have the three main functions that work, main.cpp, items.cpp, items.h. but the shoppingcart.cpp and the shoppinfcart.h keeps giving me issues, because I'm trying to pass the parameters from main.cpp, for example (sc1.add(&a) to the functions in shoppingcart.h and shopping cart.cpp.

I have attached copy of my code. any help will be appreciated.

Item.h

#ifndef Items_hpp
#define Items_hpp
#include <string>
#include <iostream>
using namespace std;

class Items {
  private: 
  
  string ItemName;
  float ItemPrice;
  int ItemQuant;
  
  public:
  
  Items();
  
  Items(string in, float ip, int iq);
  
  void Name(string in);
  string entername();
  void CalcPrice( float ip);
  float enterprice();
  void CalcQuant(int iq);
  int enterquant();
  
};
#endif

Items.cpp

#include "Items.h"

Items::Items()
:ItemName("")
,ItemPrice(0)
,ItemQuant(0)
{
}


Items::Items(string in, float ip, int iq)
:ItemName(in)
,ItemPrice(ip)
,ItemQuant(iq)
{
}

void Items:: CalcPrice(float ip)
{
  ItemPrice = ip;
}

void Items::CalcQuant(int iq)
{
  ItemQuant = iq;
}

void Items:: Name(std::string in)
{
  ItemName = in;
}

float Items:: enterprice()
{
  return ItemPrice;
}

int Items:: enterquant()
{
  return ItemQuant;
}

string Items:: entername()
{
  return ItemName;
}

a snippet of the code for adding items to vector ShoppingCart.cpp

#include "ShoppingCart.h" 
#include <vector>

void ShoppingCart ::add(&its)
{
shopitems.push_back(&its);
}

ShoppingCart.h

#ifndef ShoppingCart_hpp
#define ShoppingCart_hpp
#include <iostream>
#include <string>
#include <vector>
#include "Items.h"
using namespace std;


class ShoppingCart
{
  private:
  vector <const char its> shopitems;
  string cname; //customers name
  string cdate; // todays date

  public:
  ShoppingCart();
  ShoppingCart(string cname);
  void add( char *its);
};


#endif

an example of main main.cpp

#include <iostream>
#include <string>
#include <vector>
#include "Items.h" 
#include "ShoppingCart.h"
using namespace std;

int main() {
  char choice;
  int itemsbuy;
  float org = .75;
  float appl = .25;
  float pear = 1.00;
  float bana = .85;
  float grape = 6.00;
  float oatmlk = 5.00;
  float almmlk = 6.00;
  float cashmlk= 5.00;
  float soymlk = 4.00;
  float cocomlk = 3.00;
  float twopermlk = 3.00;
  float vitdmlk = 4.00;
  float fatmlk = 4.00;
  float goatmlk = 6.00;
  float rasinbran = 4.00;
  float granola = 5.00;
  float honeybunches = 6.00;
  float twix = 4.00;
  float honey = 5.00;
  float yogurt = 1.50;
  float cashyog = 2.00;
  float eggs = 1.80;
  float vegeggs = 3.00;
  float cheese = 2.00;
  float alcheese = 3.00;
  int itemop;
  int itemno;
  int productcounter = 0;
  int productsum= 0;//might need.
  
  

  cout << "Welcome to J&S Breakfast Grocery store!"<<endl;
  cout << "--------------------------------------"<<endl;
  cout << "How many items will you be purchasing today?"<<endl;
  cout << endl;
  cin >> itemsbuy;
  ShoppingCart sc1;                        //**intializing "shoppingcart.h"**//
  for (int i = 0; i < itemsbuy; i++) {
    cout << "Menu:"<<endl;
    cout << "---------------------------"<<endl;
    cout << "A. Fruits"<<endl;
    cout << "B. Non-Diary"<<endl;
    cout << "C. Diary" <<endl;
    cout << "D. Cereal" <<endl;
    cout << "E. Other"<<endl;
    cout << "Please select your type of items to add to cart"<<endl;
    cin >> choice;
    cout << endl;
    switch (choice) {
      case 'A':
      case 'a':
        cout << "Menu:" <<endl;
        cout << "---------------------------"<<endl;
        cout << "1.Oranges -$ "<< org<<endl;
        cout << "2.Apples -$ "<< appl << endl;
        cout << "3.Pears - $"<<pear<<endl;
        cout << "4.Bananas - $" << bana << endl;
        cout << "5.Grapes - $" << grape << endl;
        cout << endl;
        cout << "Chooose option"<<endl;
        cin >> itemop;
        cout << "How Many?"<<endl;
        cin >> itemno;
        if (itemno > itemsbuy) {
          cout << "Error, cannot add more than youre planning to buy. Please start over."<<endl;
          break;
        }
        else {
        if (itemop ==1) {
          Items a("Oranges" , org, itemno);
          productcounter++;
          sc1.add(&a);                       //**trying to pass parameter here**//
          if (productcounter == itemsbuy) {
           cout<< "Error. You are attempting to buy more than you planned. Please Start over. Thank you."<<endl;
          }
        }
        

Boost, get UTC time in minutes precision

I want the UTC time in minutes and I don't want seconds. I am doing...

auto timeUTC = boost::posix_time::second_clock::universal_time();
std::cout << to_iso_extended_string(timeUTC) << std::endl;

This will print the time as 2020-06-29T23:06:30

I want the seconds part to be removed form the ptime object, example 2020-06-29T23:06:00. How do I do this...?

Thanks in advance...

C++ quickly check if a string contains an integer, a double or just text

I'm writing a telegram bot in c++ and I need to check, for every incoming message, if it contains a number, if it's an integer number or not, or if it doesn't contain any number so I need to do other checks as text.

I was hoping I could use some regular expressions, but I'm unable to find a good answer for my specific situation.

I could run through the characters of the message and check if there is a dot around digits, or even if there is no digit at all, but this check will have to be done for each received message, and I think such a long procedure will really slow down the bot (which already deals with other potentially slow stuff).

I'm using C++11, without the boost library. Is there any faster solution?

move boost::interprocess::string in shared memory

I wanted to implement, some queue of messages (based on vector) to handling in some way data from the network and to do this I used shared memory to save messages and I encountered an issue related to it, the thing is that my code works well when I run it first time, when I want to run it once again I get segfaut when I want to assign a new value to string in my queue in shared memory, actually in my case when I want to move it (the same problem exists when I want to copy it). The problem doesn't exist when SSO is working, so when I have small string enough. What did I wrong ?

#include <atomic>
#include <exception>
#include <iostream>
#include <memory>
#include <string>
#include <vector>

#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>

namespace bip = boost::interprocess;

struct BadSharedMemoryAccess final : public std::exception
{
    BadSharedMemoryAccess(std::string&& msg):
        msg_{std::move(msg)}
{}

virtual const char* what() const noexcept
{
    return msg_.c_str();
}

private:
    std::string msg_;
};

struct Message
{
    bip::string message_;
};

template<typename Alloc>
class MyCustomData final
{
public:
    using allocator_type = typename Alloc::template rebind<Message>::other;

    MyCustomData(std::size_t number_of_messages, Alloc alloc = {}) :
        init_add_index_{0},
        init_handle_index_{-1},
        messages_{number_of_messages, alloc}
    {}

public:
    uint_fast64_t init_add_index_;
    int_fast64_t init_handle_index_;
    std::vector<Message, Alloc> messages_;
//    bip::vector<data::Message, Alloc> messages_;
};

template<typename DataType, typename DataAllocator>
class SharedMemory
{
public:
    template<typename... Args>
    SharedMemory(std::string const& shm_segment_name, std::size_t const segment_size,
        std::string const& shm_object_name, Args&&... args) :
            shm_object_name_{shm_object_name}
    {
        std::cout << "attempt to allocate space for shared memory segment " << shm_segment_name
              << ", size: ." << segment_size << std::endl;
        setSharedMemorySize(shm_segment_name, segment_size);

        DataAllocator const allocInstance{shm_.get_segment_manager()};
        data_ = shm_.find_or_construct<DataType>(shm_object_name.c_str())(std::forward<Args>(args)..., allocInstance);
        if (data_)
            std::cout << "shared memory segment has been allocated" << std::endl;
        else
            std::cout << "shared memory has not been constructed or founded" << std::endl;
    }

    virtual ~SharedMemory()
    {
        std::cout << "shared memory segment will be closed." << std::endl;
    }

    void setSharedMemorySize(std::string const& shm_segment_name, std::size_t const segment_size)
    {
        auto page_size = bip::mapped_region::get_page_size();
        auto const page_increase_rate{2};
        while (page_size < segment_size)
        {
            page_size *= page_increase_rate;
        }

        std::cout <<"seting page size: " << page_size << std::endl;
        shm_ = bip::managed_shared_memory{bip::open_or_create, shm_segment_name.c_str(), page_size};
        std::cout << "space for shared memory has been successfully allocated." << std::endl;
    }

    DataType& getData()
    {
        if (not data_)
            throw BadSharedMemoryAccess{"cannot access " + shm_object_name_};
        return *data_;
    }

protected:
    DataType* data_;

private:
    std::string const shm_object_name_;
    bip::managed_shared_memory shm_;
};

namespace sharable
{
    using DataAllocator = bip::allocator<Message, bip::managed_shared_memory::segment_manager>;
    template<typename Alloc>
    using DataType = MyCustomData<Alloc>;
}

int main()
{
    std::size_t const max_number_of_elements_in_container{1000000};
    auto shmem_data = std::make_shared<SharedMemory<MyCustomData<sharable::DataAllocator>, sharable::DataAllocator>>(
        "SHM_SEGMENT", sizeof(MyCustomData<sharable::DataAllocator>) +
            (max_number_of_elements_in_container * sizeof(Message) * 2),
        "SHM_CONTAINER", max_number_of_elements_in_container);

    std::vector<bip::string> feed{max_number_of_elements_in_container};
    for (std::size_t i = 0; i < max_number_of_elements_in_container; ++i)
    {
        std::string s{"blablabla11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" + std::to_string(i)};
        feed[i] = s.c_str();
    }

    auto& data = shmem_data->getData();
    auto& shmem_vec = data.messages_;
    std::cout << "addr: " << shmem_vec.data() << std::endl;
    for (std::size_t i = 0; i < max_number_of_elements_in_container; ++i)
    {
//        if (i == 0)
//            std::cout << "msg: " << shmem_vec[i].message_ << std::endl;
        auto msg = feed[i];
        shmem_vec[i].message_ = std::move(msg);
    }
    return 0;
}

Memory leak when using fortify static code analyser for unique_ptr

Using std::unique_ptr in c++11 in fortify Static Code Analyser is giving me a memory leak.

void *httpServerThread(void *arg)
{
  
    std::unique_ptr <int> i(new int(1));
    return NULL;
}

Meanwhile, the below code shows no memory leak.

void *httpServerThread(void *arg)
{
  
    int * i  = new int(1);
    delete i;
    return NULL;
}

Since there is no std::make_unique, there is no way to create std::unique_ptr without new. I am using the 19.2.0 version of fortify -> Fortify_SCA_and_Apps_19.2.0. Any suggestion would be welcome.

what happen between after notify_all() and before wait() get the lock?

I test the std::condition_variable using the below code:

class CondWait{
public:
    std::condition_variable cv;
    std::mutex mu;
    int i=0;
public:
    void mainTask(){
        std::unique_lock<std::mutex> lk(mu);
        cv.wait(lk);
        i++;
        std::cout<<"main task, "<<i<<std::endl;
    }
    void notifyTask(){

        std::unique_lock<std::mutex> lk(mu);
        i = 0;
        std::cout<<"notify task, "<<i<<std::endl;
        cv.notify_one();
        std::cout<<"notify task, sleep 5 sec"<<std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(5));
    }
};
int main()
{
    CondWait condwait;
    std::thread t1(&CondWait::mainTask,&condwait);
    std::thread t2(&CondWait::notifyTask,&condwait);
    t1.join();
    t2.join();

    return 0;
}

Sometimes, the output is below and the program is blocked:

notify task, 0
notify task, sleep 5 sec

Sometimes, the program will run well,i.e. after 5 seconds of sleep, it will output main task, 1, the complete output is:

notify task, 0
notify task, sleep 5 sec
main task, 1

In my opinion, int the notifyTask thread, the mutex is still used after notify_one, so the wait in the mainTask cannot lock the mutex. But I don't know what will happen next, why the example will have an ambiguity performance. Could you please provide some advice? Thanks a lot!

Why i am not able to create the Unique pointer

I get c2664 error when i try to create a unique pointer

i did write the copy constructor as well as assignment operator but still i keep getting the 2664 error

class UndoCopyPaste : public UndoRedo
    {
    private:
        Container containerValue;
        bool valid;
    public:
        UndoCopyPaste() = default;
        UndoCopyPaste(Container* cont, std::string type);
        UndoCopyPaste(Container trans, Container* cont, std::string type);
        
    };
    
    class UndoRedo
    {
    private:
        std::string type;
    protected:
        Container* container;
    public:
        UndoRedo() = default;
        UndoRedo(Container* cont, std::string undoType);
    };
    
    std::unique_ptr<UndoCopyPaste> undoCopyPastePointer = std::make_unique<UndoCopyPaste>(new UndoCopyPaste()); // error C2664: 'UndoCopyPaste::UndoCopyPaste(UndoCopyPaste &&)': cannot convert argument 1 from '_Ty' to 'const UndoCopyPaste &'

Why is copy constructor called rather than move constructor?

I have the following code:

#include <bits/stdc++.h>

using namespace std;

class A {
public:
    A(const A& a) noexcept { cout << "copy constructor" << endl; }
    A& operator=(const A& a) noexcept { cout << "copy assignment operator" << endl; }
    A(A&& a) noexcept { cout << "move constructor" << endl; }
    A& operator=(A&& a) noexcept { cout << "move assignment operator" << endl; }
    A() { cout << "default constructor" << endl; }
};

vector<A> aList;

void AddData(const A&& a)
{
    aList.push_back(std::move(a));
}

int main()
{
    AddData(A());
    return 0;
}

The output is default constructor copy constructor. please tell me is the rvalue reference push_back(T&&)called? And when is copy constructor called?

Removing code duplication in inheritance?

I have wrote the following code:

std::shared_ptr<mtm::Character>
Game::makeCharacter(CharacterType type, Team team, units_t health, units_t ammo, units_t range, units_t power) {
    if (health <= 0 || ammo < 0 || range < 0 || power < 0)
    {
        throw mtm::IllegalArgument();
    }
    std::shared_ptr<Character> out = nullptr;
    if (type == SOLDIER)
    {
        out = std::shared_ptr<Character>(new mtm::Soldier(team, health, ammo, range, power));
    }
    if (type == MEDIC)
    {
        out = std::shared_ptr<Character>(new mtm::Medic(team, health, ammo, range, power));
    }
    if (type == SNIPER)
    {
        out = std::shared_ptr<Character>(new mtm::Sniper(team, health, ammo, range, power));
    }
    return out;
}

As you can see I have some kind of code duplication, what if there are 100 types... I would have to write 100 if statements which doesn't sound the perfect way to do it.

Any suggestions?

Calling C++ functions from Python without changing C++ files

What is best way to call C++ functions from Python script/code. C++ functions are already defined, all I want to call those function from python. I'm not allow to make any changes in c++ files so please tell me how to call those C++ functions from python.

dimanche 28 juin 2020

Can std::move move a built-in types or c pointer or array

1.can std::move move a built-in type

int a = 10;
int b = std::move(a);

will a be a invalid value?

  1. can std::move move a pointer
    int *a = new int[10];
    int *b = std::move(a);

will a become a invalid pointer or nullptr?

  1. can std::move move an c array
int a[10];
int b[10];
b = std::move(a);

will a become an invalid array?

How to store input for an unknown number of iterations?

I am writing a problem for school project on loops.

The program is a do-while loop where the user will feed the program sales figures, then expense figures for three separate districts. Then the user will be prompted to enter Y to enter the figures for another month, or anything else to terminate the loop.

After terminating the loop the program will then take the input figures for however many months the user has decided to evaluate and average them and compare them.

How do I store data for additional months and still keep the data for the first month?

C++: function calling order (inheritnce and methods)

I was asked to write the output of this code:

#include <iostream>
using namespace std;

class A {
    public:
    A() {}
    A(const A& a) {
         cout << "A copy ctor" << endl;
    }
    virtual ~A() {
         cout << "A dtor" << endl; 

    }
    virtual void type() const { 
        cout << "This is A" << endl; 

    }
};

class B: public A {
    public:
    virtual ~B() {
         cout << "B dtor" << endl; 
    }
    void type() const override {
         cout << "This is B" << endl; 
    }
};

A f(A a) {
    a.type();
    A a1();
    return a;
}

const A& g(const A& a) {
    a.type();
    return a;
}

int main() {
    A* pa = new B();
    cout << "applying function f:" << endl;
    f(*pa).type();
    cout << "applying function g:" << endl;
    g(*pa).type();
    delete pa;
    return 0;
}

I noticed something strange, on the third line in main() I expected to enter f(A a) by calling the copy C'tor, end the function, recive a copy of a (class A) (+) call the D'tor (class A) for the copy I passed to f(A a) and then return to the third line in main(), call type() (class A) and when I am done with the third line to call the D'tor (class A) again to earse the copy I got from f(A a).

What actually happend when I run the code was what I expected until (+) from there type() was immediately called and only then the D'tor was called for the copy that was passed and then for the copy recived.

It confused me and made me realise that I may not understand well the order of calls, I would like to recive an explanation (I tried searching for it online but could not find anything with methods involved).

thank you.

Am tired of console applications

I am really tired of console applications in c++ because i always build them in visual studios i don't see any improve in my skills ...Like for real i don't know how to master c++ basics thought i try my targeted project, i just get confused and don know what to put next after the ...Ok Look am starting my project then i start with the login and sign up forms then don't know what to do next am stuck and i get tired and loss interest. Then I don't know those who already know c++ managed to learn it ..i want to build an android app but am just confused ...

Guys my mind is blowing up help me .

Why am I getting this single output wrong?

I'm new to competitive programming and I participated in Codeforce #653 in which I spent the whole time solving these problems and did not submit any code because of exceeded time limits or wrong answer for test cases. Anyway, it was awesome. I wanted to solve this problem https://codeforces.com/contest/1374/problem/A and wrote this following code.

#include <stdio.h>

int main(){
    int i,t,j,k=0;
    int x[60000],y[60000],n[60000],prev[60000];
    scanf("%d",&t);
    for(i=0; i<t; i++){
        scanf("%d %d %d",&x[i],&y[i],&n[i]);
    }

    for(i=0; i<t; i++){
    for(j=0, k=0; j<n[i]; j++ , k++){
        if(j%x[i]==y[i]){
            prev[i]=k;
        }
    }
}
    for(i=0; i<t; i++){
    printf("%d",prev[i]);
    printf("\n");
}

return 0;
}

Everything was working fine but for some test cases I'm getting different answers. This was the expected output

12339
0
15
54306
999999995
185
999999998

and my output was this,

12339
0
5
54306
999999995
185
999999998

I did not understand why I got 5 instead of 15 keeping all the other outputs correct and also could anyone please help me to optimize the code, its taking too long to compile for large inputs.

C++11: template function call of a template method doesn't compile? [duplicate]

The following program, if compiled as shown, outputs size: 1 align: 1.

However, trying to make the same method-template call from a templatized function doesn't work.

If I change #if 0 to #if 1 g++ 9.2.1 gives me error expected primary-expression before 'char'. clang++ gives a more helpful-sounding error: use 'template' keyword to treat 'log' as a dependent template name but I'm not sure where it wants template to occur.

So what gives?

#include <iostream>
using namespace std;



class Foo {

public:
  Foo() {};
  ~Foo() {};
  void log( int iSizeItem, int iAlignItem ) {
    cout << "size: " << iSizeItem << "  align: " << iAlignItem << endl;
  }
  
  template<class T> void log() {
    log( sizeof( T ), alignof( T ) );
  }
};


#if 0
template<class T> void Test( T& t ) {
  t.log<char>();
}
#endif


int main( int nArg, char* apszArg[] ) {
  Foo foo;
  foo.log<char>();

  //Test( foo );

  return 0;
}

Print all inherited class member variables and methods

Suppose I have inheritance like below:

class A
{
public:
A(){}
int s;
void Show(){}
};

class B : public A
{
public:
B(){}
int y;
void MyShow() {}
};

int main()
{
B b;
}

Is there a way that I can know by any mechanism [runtime/debug] etc that what are the member variables / methods of object 'b' - I mean complete list along with all it inherited?

variadic templates vs using tuples for adding different data pairs in an argument

following main code works fine

    string hello = "Hello ";
    string world = "templates!";

    cout << "var template add: ";


    cout << setprecision(2) <<
        var_template_add(5, 4, 5.5, 4.0);

for following template generator code and variadic func

template <typename T> 
auto add(T a, T b) {
    return a + b;
}


template <typename T, typename... Rest> 
auto var_template_add(T first, T second, Rest... others) {
    return first + second + add (others...);
}

But if added two more string args, like this

var_template_add(5, 4, 5.5, 4.0, hello, world);

is caught by compiler error saying "no matching overloaded function found".

Again,

string hello = "Hello ";
string world = "templates!";
cout << "strings add result: " << setprecision(2) << add(hello, world) << endl;

could work if i write template function "add" like below:

template <typename T1, typename T2>
auto add(T1 a, T2 b) {
    return a + b;
}

My question is, how could i make the line

var_template_add(5, 4, 5.5, 4.0, hello, world);

work without writing another add function like just above?!

please note i could use tuple to pass this values but for now, i just want to keep away. any thoughts/improvements?

Defining a parameter of a struct variable in a class constructor

I am using a struct variable inside a class and I would like to assign the value of a parameter of that variable in the class constructor.

But I can not find a way to compile. could you show me how to do it? This is an example of my code

struct mystruct
{
   int myvar;
}

class myclass
{
   mystruct s_;

public:
   myclass(int n) : s_.myvar{ n } {}
};

How to call the lambda stored in pointer to the `std::function`?

I have a pointer to std::function that stores lambda inside. How can I call that lambda?

example:

std::function <void()>* fx = new std::function <void()>([] {std::cout << "Hello world;\n"; });
    //here i need to call my fx, just fx(); does not works in this case

fx may be stored inside std::pair

LNK2019: unresolved external symbol even though other functions from the same header file work

I have a function named matToVector that is located in a namespace called sim that is located in header called SimilarityMeasures.h. When I call it in main.cpp it throws unresolved external even though function is declared and defined properly. Other functions in the same header file do work when called using sim::func. Below is the error code.

Severity    Code    Description Project File    Line    Suppression State
Error   LNK2019 unresolved external symbol "class std::vector<class std::complex<float>,class std::allocator<class std::complex<float> > > __cdecl sim::matToVector<class std::complex<float> >(class cv::Mat)" (??$matToVector@V?$complex@M@std@@@sim@@YA?AV?$vector@V?$complex@M@std@@V?$allocator@V?$complex@M@std@@@2@@std@@VMat@cv@@@Z) referenced in function main    bpv2    C:\Users\ASUS\source\repos\bpv2\bpv2\main.obj   1   

I included the header file that has the function in main.

#include "SimilarityMeasures.h"

Here is the function call in main.cpp

std::vector<std::complex<float>> imageVec = sim::matToVector<std::complex<float>>(xd);

Here is the function declaration in SimilarityMeasures.h

namespace sim {
    template <typename T>
    std::vector<T> matToVector(cv::Mat operand);
}

Here is the definition in SimilarityMeasures.cpp

template <typename T>
std::vector<T> sim::matToVector(cv::Mat operand) {   //https://stackoverflow.com/questions/62325615/opencv-data-of-two-mats-are-the-same-but-values-when-retrieved-with-matat-are
    std::vector<T> vecoper;
    uchar* pixelPtr = (uchar*)operand.data;
    int cn = operand.channels();
    cv::Scalar_<uchar> cnPixel;

    vecoper.push_back((T)operand.dims);
    for (int i = 0; i < (T)operand.dims; i++) {
        vecoper.push_back((T)operand.size[i]);
    }
    vecoper.push_back((T)operand.type());

    for (int i = 0; i < operand.total() * operand.elemSize(); i++) {
        vecoper.push_back((T)pixelPtr[i]);
    }

    return vecoper;
}

I only extracted the parts I thought necessary. If you need to see the whole header file or main.cpp or anything else just tell me.

C++ code terminates by Segmentation Fault?

#include <iostream>

using namespace std;


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
    int num, qr, maxSize = 0;
    cin >> num >> qr;
    for (int i = 0; i < num; i++)
    {
        int size;
        cin >> size;
        if (size > maxSize)
        {
            maxSize = size;
        }
    }
    int arr[num][maxSize];
    for (int i = 0; i < num; i++)
    {
        int s;
        cin >> s;
        for (int j = 0; j < s; j++)
        {
            int elem;
            cin >> elem;
            arr[i][j] = elem;
        }
    }
    for (int i = 0; i < qr; i++)
    {
        int a,b;
        cin >> a >> b;
        cout << arr[a][b];
    }
    return 0;
}

This code terminates giving Segmentation Fault Error. I am new to the world of C++ and I don't have any idea of this error message. Any help would mean a lot to me.

Program to check any number exist in 2D array

I know how to check if number exist in the array, but not in a 2D array.

Please help me in 2D.

#include<iostream>
using namespace std;

int main()
{
   int a[3] = { 4,5,6 };
   int b, c;
   int x = 1, fact = 1;

   cout << "enter no ";
   cin >> b;

   for (int i = 0; i < 3; i++) 
   {
      if (b == a[i]) {
         c = a[i];
         break;
      }
   }
   cout << "no entered is present" << endl;
}

a stack emplace a pair,but the result is not right

stack<pair<int, int>> v1;    
int x=1;                         
int y=2;
v1.emplace(x, y);           
v1.pop();
x=3;
y=4;
v1.emplace(x, y);    **second emplace,but not right,still push a {1,2}**

I use a stack of pair<int,int>,after the second time to use emplace,the pair in the stack is not {3,4},but still {1,2}. I do not now why is it wrong.

samedi 27 juin 2020

What this lines in bubble sort algorithm means?

In Introduction to programming with C++ 6th edition book, it explain the bubble sort algorithm with C++ and i understand it, but there is two lines of code I'm not understand why they in the code, when I tried to understand code I erase them and nothing changed and the algorithm still working. So I still confused about them. there is the code;

int main()
 {
     int numbers[4] = {23, 46, 12, 35};
     int sub = 0; //keeps track of subscripts
     int temp = 0; //variable used for swapping
     int maxSub = 3; //maximum subscript
     int lastSwap = 0; //position of last swap
     char swap = 'Y'; //indicates if a swap was made

     //repeat loop instructions as long as a swap was made
     while (swap == 'Y')
     {
     swap = 'N'; //assume no swaps are necessary

     sub = 0; //begin comparing with first
     //array element

     //compare adjacent array elements to determine
     //compare adjacent array elements to determine
     //whether a swap is necessary
     while (sub < maxSub)
     {
         if (numbers[sub] > numbers[sub + 1])
         {
             //a swap is necessary
             temp = numbers[sub];
             numbers[sub] = numbers[sub + 1];
             numbers[sub + 1] = temp;
             swap = 'Y';
             lastSwap = sub;
         } //end if
         sub += 1; //increment subscript
         } //end while

         maxSub = lastSwap; //reset maximum subscript
     } //end while

     //display sorted array
     for (int x = 0; x < 4; x += 1)
        cout << numbers[x] << endl;
     //end for

     system("pause");
     return 0;
 } //end of main function 

so I don't understand lastSwap = sub & maxSub = lastSwap. are they important or I'm right about erase them from the code? can anyone explain to it to me.

Operators overloading add using operator+ for a class-template

I need a function to add values ​​to v[i] using the operator+ the vector v contains the values 10,2 and 3.

#include <iostream>
#include <vector>

template<typename T>
class Measurement 
{
private:
    T val;
public:
    Measurement(T a)
        : val{ a }
    {}

    T value() const { return val; }

    Measurement<T>& operator+(const T& nr) 
    {
        //... ???
        return *this;
    }

};

int main()
{
    //create a vector with values (10,2,3)
    std::vector<Measurement<int>> v{ 10,2,3 };
    v[2] + 3 + 2; //add at v[2] value 5
    for (const auto& m : v) std::cout << m.value() << ",";
    return 0;
}

The result must be 10,2,8

C++ only forward construction if the object has not been created

Basically I've been looking into unordered_map and see that they delay construction of the value (if possible) with emplace.

I am trying to implement something similar and am able to forward an objects construction, but I also am forwarding already constructed objects.

I am looking for help on how I can check if an object is already created (in which case I would want to use std::move(obj) versus if just the pieces for construction have been passed in which case I want to use std::forward<Args>(args)...

This is the code I've been trying to use to figure this out but I have been unable to figure it out.

#include <vector>
#include <string>

#include <stdio.h>

template<typename T>
struct tester {
    std::vector<T> v;

    tester() : v(0) {}

    //we have a reference to existing object
    void
    add(const char * vname, const T & t) {
        fprintf(stderr, "Const lRef -> %s\n\n", vname);
        v.push_back(t);
    }

    //we have an actual copy
    void
    add(const char * vname, T && t) {
        fprintf(stderr, "Const rRef -> %s\n\n", vname);
        v.push_back(std::move(t));
    }

    //we have parameters necessary for construction
    template<typename... Args>
    void
    add(const char * vname, Args && ...args) {
        fprintf(stderr, "vArgs      -> %s\n\n", vname);
        v.push_back(std::forward<Args>(args)...);
    }
    
};


#define VAR_TO_STR(X) #X
#define ADD(X) add(VAR_TO_STR(X), (X))

int
main() {

    tester<std::string> str_tester;

    std::string constructed_str("Already Constructed String");
    const std::string const_constructed_str("Const Already Constructed String");
    
    str_tester.ADD("String That Can Be Constructed In Place");
    str_tester.ADD(constructed_str);
    str_tester.ADD(const_constructed_str);


    tester<int> int_tester;

    int constructed_int = 10;
    const int const_constructed_int = 50;

    int_tester.ADD(1);
    int_tester.ADD(constructed_int);
    int_tester.ADD(const_constructed_int);
}

The output is:

vArgs      -> "String That Can Be Constructed In Place"

vArgs      -> constructed_str

Const lRef -> const_constructed_str

Const rRef -> 1

vArgs      -> constructed_int

Const lRef -> const_constructed_int

I am basically looking for a way so that constructed_int and constructed_str can go to the "lRef" or "rRef" as reconstructing from copy constructor is pretty expensive.

Thank you!

Edit: To some degree I figured it out:

    //we have a reference to existing object
    void
    add(const char * vname, T & t) {
        fprintf(stderr, "lRef       -> %s\n\n", vname);
        v.emplace_back(t);
    }

will cause a non-const already constructed version of T to go here.

prevent hard coded numbers in C++

How may I prevent hard coded numbers in C++?

For example if I have Score+=10; In C I would do:

#define FACTOR 10
Score+=FACTOR

But In C++ my professor told we don't use #define anymore (It's a C thing and risky), So what should I use?

typeid returns strange output [duplicate]

How may I get the class name in C++?

For example inside my class GameException: I tried typeid(GameException).name()); but it print something strange like:

N3mtm13GameExceptionE @

While I expect it to give:

GameException

Inheriting static variable in classes?

Given an abstract class called Job and other classes that inherit it like Teacher, Worker ,etc...

I want those classes to inherit something like a static variable -I'm saying like since it's not allowed to inherit static according to what I read- for Job (Like Salary) with different values for each class, how may I do that?

Until now, in the c'tor for Teacher I have created a local variable for each object called salary such that it's equal to 100, but that doesn't seem smart since all teachers have the same salary according to what I'm working on.


For example:

class Job{
    int salary;
    std::string tag;
public:
    Job(int salary,std::string tag;) : salary(salary), tag(tag)
    {}
};

class Teacher: public Job{
public:
    Teacher(std::string tag) : Job(100,tag){}
};

class Worker: public Job{
    Worker(std::string tag) : Job(200,tag){}
};

every worker has salary=100 but I want this to be related to the class worker and not for each object. (I can define this as static for each class but again it doesn't seem smart to declare the same static value in 100 classes the inherit a one which has that static value)

Can we avoid using Sleep() API to ensure that threads are not blocked unnecessarily in C++?

In the below function, I am assuming that we can avoid using Sleep() API to ensure that threads are not blocked unnecessarily.

Below is the code snippet and explanation:

void CApplicationListener::createApplicationLaunchThread()
{
    CReqXMLMessageObject *l_objMesgObject = nullptr;

    while (!gShutDown)
    {
        if (m_hConnectStatus == SOCKET_ERROR)
        {
            bool l_boIsApplicationRun = CAppUtility::launchApplicationProcess(m_hApplicationProcess);
            // Here l_boIsApplicationRun returns true
            if (l_boIsApplicationRun)
            {
                if (startApplicationListener())
                {
                    if (m_hConnectStatus != SOCKET_ERROR)
                    {
                        Sleep(1200);
                        l_objMesgObject = new CReqXMLMessageObject();
                        l_objMesgObject->sendReqSFLoggedInXML();
                        if (l_objMesgObject != nullptr)
                        {
                            delete l_objMesgObject;
                            l_objMesgObject = nullptr;
                        }
                    }
                }
            }
        }
        
        Sleep(100);
    }
}

Information about the above function:

In the above function, we are invoking launchApplicationProcess. This function is checking the application process is running or not. If it is not launching, it is creating and starting the application process.

In our case it is launching the process and "l_boIsApplicationRun" returns true.

Then calling startApplicationListener function. This function reads the port no form the configuration file, creating the socket and initializing the socket connection and then connecting to the port no.

But in the above function and also in the project, I wanted to know the options to avoid using Sleep() API and ensure that threads are not blocked unnecessarily. And also if it is required to use the sleep to pause the execution temporarily, I was asked to use the platform independent function instead of using Sleep() API.

I Wanted to know the experts inputs/suggestions to use or remove the Sleep() function.

What are the consequnces if we remove the Sleep() function?

GCC Sees Multiple Arguments Although There is only one

#include <cassert>

template <bool D1, bool ...Ds>
constexpr int reversed_binary_value() {
    return D1 + 2 * reversed_binary_value<Ds...>();
}

template <>
constexpr int reversed_binary_value<0>() {
    return 0;
}

template <>
constexpr int reversed_binary_value<1>() {
    return 1;
}

int main() {
    assert(4 == reversed_binary_value<0, 0, 1>());
}

When I compiled, I got:

test_assert.cpp:19:47: error: macro "assert" passed 3 arguments, but takes just 1
  assert(4 == reversed_binary_value<0, 0, 1>() );
                                               ^
test_assert.cpp: In function ‘int main()’:
test_assert.cpp:19:2: error: ‘assert’ was not declared in this scope
  assert(4 == reversed_binary_value<0, 0, 1>() );
  ^~~~~~
test_assert.cpp:19:2: note: ‘assert’ is defined in header ‘<cassert>’; did you forget to ‘#include <cassert>’?
test_assert.cpp:2:1:
+#include <cassert>
 
test_assert.cpp:19:2:
  assert(4 == reversed_binary_value<0, 0, 1>());
  ^~~~~~

I am using g++ 8.3.1 if it matters.

I am not sure why the compiler sees 3 arguments instead of 1.

Tho, if I change the assertion to

assert(4 == reversed_binary_value<0, 0, 1>());

Then, it compiles fine.

Idea?

Method error "not all control paths return a value" and Method not returning a value

I'm getting the following errors with my code:

PoliceOfficer.cpp(39): warning C4715: 'PoliceOfficer::patrol': not all control paths return a value

ParkingTicket.cpp(54): error C4716: 'GetCarInfo': must return a value

I've commented out most of the PoliceOfficer::patrol so it is easier to troubleshoot. Not sure what I'm doing wrong. I've included all my files just in case something helps

        Car.h


    #pragma once
    #ifndef CAR_H
    #define CAR_H
    #include <string>
    
    using namespace std;
    
    // Car class contains the information about a car
    
    class Car
    {
    private:
        string make, model, color, licenseNumber;
    
    public:
        // Default Constructor
        Car();
    
        // Accessors
        string getMake();
        string getModel();
        string getColor();
        string getLicense();
    
        // Mutators
        void setMake(string);
        void setModel(string);
        void setColor(string);
        void setLicense(string);
    
        // Overload << operator
        friend ostream& operator << (ostream& strm, const Car& obj);
    
    };
    
    
    
    #endif // CAR_H
        Car.cpp


    #include "Car.h"
    #include <iostream>
    #include <string>
    using namespace std;
    
    // Default Constructor
    Car::Car()
    {
        make = "None Set";
        model = "None Set";
        color = "None Set";
        licenseNumber = "None Set";
    }
    
    // Accessors
    string Car::getMake()
    {
        cout << "Make: " << make;
        return make;
    
    }
    string Car::getModel()
    {
        cout << "Model: " << model;
        return model;
    }
    string Car::getColor()
    {
        cout << "Color: " << color;
        return color;
    }
    string Car::getLicense()
    {
        cout << "License: " << licenseNumber;
        return licenseNumber;
    }
    
    // Mutators
    void Car::setMake(string ma)
    {
        make = ma;
    }
    void Car::setModel(string mo)
    {
        model = mo;
    }
    void Car::setColor(string c)
    {
        color = c;
    }
    void Car::setLicense(string l)
    {
        licenseNumber = l;
    }
    
    // Overload << operator
    // Author note: I'm not sure what I am supposed to be overloading
    // this function with. 
    ostream& operator << (ostream& strm, const Car& obj)
    {
        return  strm;
    }
        ParkedCar.h


    #pragma once
    #ifndef PARKEDCAR_H
    #define PARKEDCAR_H
    #include <iostream>
    #include <string>
    #include "Car.h"
    
    using namespace std;
    
    // ParkedCar class simulates a parked car. Knows which type of car is parked and 
    // the number of minutes that the car has been parked
    
    class ParkedCar
    {
    private:
        // Private Members
    //  class Car;
        Car carObject;
        string make;
        string model;
        string color;
        string licenseNumber;
        int minutesParked;
    
    public:
        // Constructors
        ParkedCar();
        ParkedCar(string ma, string mo, string c, string l, int mp);
    
        // Copy Constructor
        ParkedCar(ParkedCar& obj);
    
        // Accessors
        int getMinutesParked() const;
        string getMake();
        string getModel();
        string getColor();
        string getLicense();
    
        // Mutators
        int setMinutesParked(int);
        void setMake(string ma);
        void setModel(string mo);
        void setColor(string c);
        void setLicense(string l);
    
    
    };
    
    #endif // PARKEDCAR_H

        ParkedCar.cpp


    #include "ParkedCar.h"
    #include <iostream>
    #include <string>
    using namespace std;
    
    
    ParkedCar::ParkedCar() // Default Constructor
    {
        minutesParked = 0;  
    }
    
    // make, model, color, licenseNumber;
    ParkedCar::ParkedCar(string ma, string mo, string c, string l, int mp) // Constructor with 5 parameters
    {
        carObject.setMake(ma);
        carObject.setModel(mo);
        carObject.setColor(c);
        carObject.setLicense(l);
        minutesParked = mp;
    }
    
    // Copy Constructor
    ParkedCar::ParkedCar(ParkedCar& obj)
    {
        carObject.setMake(obj.make);
        carObject.setModel(obj.model);
        carObject.setColor(obj.color);
        carObject.setLicense(obj.licenseNumber);
        minutesParked = obj.minutesParked;
    }
    
    // Accessors    
    string ParkedCar::getMake()
    {
        return make;
    }
    
    string ParkedCar::getModel()
    {
        return model;
    }
    
    string ParkedCar::getColor()
    {
        return color;
    }
    
    string ParkedCar::getLicense()
    {
        return licenseNumber;
    }
    
    int ParkedCar::getMinutesParked() const
    {
        return minutesParked;
    }
    
    // Mutators
    void ParkedCar::setMake(string ma)
    {
        make = ma;
    }
    
    void ParkedCar::setModel(string mo)
    {
        model = mo;
    }
    
    void ParkedCar::setColor(string c)
    {
        color = c;
    }
    
    void ParkedCar::setLicense(string l)
    {
        licenseNumber = l;
    }
    
    int ParkedCar::setMinutesParked(int mp)
    {
        minutesParked = mp;
        return 0;
    }
        ParkingMeter.h


    #pragma once
    #ifndef PARKINGMETER_H
    #define PARKINGMETER_H
    #include <iostream>
    #include <string>
    using namespace std;
    
    
    class ParkingMeter
    {
    private:
        // Private Members
        int minutes; // Minutes purchased for parking
    
    public:
        // Constructors
        ParkingMeter();
        ParkingMeter(int);
    
        // Accessors
        int getMinutes();
    
        // Mutators
        int setMinutes(int);
    };
    
    #endif // PARKINGMETER_H
        ParkingMeter.cpp


    #include "ParkingMeter.h"
    #include <iostream>
    #include <string>
    using namespace std;
    
    // Default Constructor
    ParkingMeter::ParkingMeter()
    {
        minutes = 0;
    }
    
    // Constructor with 1 parameter
    ParkingMeter::ParkingMeter(int i)
    {
        minutes = i;
    }
    
    // Accessor
    int ParkingMeter::getMinutes()
    {
        return minutes;
    }
    
    // Mutator
    int ParkingMeter::setMinutes(int m)
    {
        minutes = m;
        return 0;
    }
    
    // Overload << operator
    const ostream& operator << (ostream& strm, const ParkingMeter& obj)
    {
        return strm;
    }
        PoliceOfficer.h


    #include "ParkingMeter.h"
    #include <iostream>
    #include <string>
    using namespace std;
    
    // Default Constructor
    ParkingMeter::ParkingMeter()
    {
        minutes = 0;
    }
    
    // Constructor with 1 parameter
    ParkingMeter::ParkingMeter(int i)
    {
        minutes = i;
    }
    
    // Accessor
    int ParkingMeter::getMinutes()
    {
        return minutes;
    }
    
    // Mutator
    int ParkingMeter::setMinutes(int m)
    {
        minutes = m;
        return 0;
    }
    
    // Overload << operator
    const ostream& operator << (ostream& strm, const ParkingMeter& obj)
    {
        return strm;
    }
        PoliceOfficer.cpp


    #include "PoliceOfficer.h"
    #include <iostream>
    #include <string>
    using namespace std;
    
    //Default Constructor
    PoliceOfficer::PoliceOfficer()
    {
        ParkingTicket* ticketPtr = nullptr;
        officerName = " ";
        badgeNumber = " ";
    }
    
    // Constructor with 2 elements
    PoliceOfficer::PoliceOfficer(string n, string b)
    {
        officerName = n;
        badgeNumber = b;
    }
    
    ParkingTicket *PoliceOfficer::patrol(ParkedCar car, ParkingMeter meter)
    {
        parkedMinutes = car.getMinutesParked();
        cout << "Parked Minutes: " << parkedMinutes << endl;
        meterMinutes = meter.getMinutes();
        cout << "Meter Minutes: " << meterMinutes << endl;
        minutes = parkedMinutes - meterMinutes;
        cout << "Minutes: " << minutes << endl;
        if (minutes <= 0)
        {
            return nullptr;
        }
        else
        {
            ParkingTicket ticket(car, minutes);
        };
        
    }
    // Accessors
    string PoliceOfficer::getOfficerName()
    {
        return officerName;
    }
    string PoliceOfficer::getBadgeNumber()
    {
        return badgeNumber;
    }
    
    // Mutators
    string PoliceOfficer::setOfficerName(string n)
    {
        officerName = n;
        return 0;
    }
    string PoliceOfficer::setBadgeNumber(string b)
    {
        badgeNumber = b;
        return 0;
    }
    
    // Overload << operator
    const ostream& operator << (ostream& out, const PoliceOfficer& obj)
    {   
        out << "Officer: " << &PoliceOfficer::getOfficerName;
        out << " (badge #" << &PoliceOfficer::getBadgeNumber;
        out << ")" << endl;
        return out;
    }
        ParkingTicket.h


    #pragma once
    #ifndef PARKINGTICKET_H
    #define PARKINGTICKET_H
    #include <iostream>
    #include <string>
    #include "ParkedCar.h"
    #include "ParkingMeter.h"
    #include "Car.h"
    
    using namespace std;
    
    // ParkingTicket class simulates a parking ticket
    // Reports the car information for illegally parked car
    // Reports the fine which is $25 for the first hour or part
    // of an hour that the car is illegally parked, plus $10
    // for every additional hour or part of an hour
    
    class ParkingTicket
    {
    
    private:
        // Private Members
    //  class ParkedCar;
        double fine; // The calculated parking fine
        double* fineptr = &fine; // fine pointer
        int minutes; // The minutes illegally parked
        const int firstHour = 25; // first hour fine
        const int subHours = 10; // subsiquent hour fine
    
        // Car Info
        string make, model, color, licenseNumber;
    
    
    public:
        // Constructors
        ParkingTicket();
        ParkingTicket(ParkedCar car, int meter);
    
        // Accessors
        double getFine();
        int getMinutes();
    
        // Mutators
        double setFine(double);
        int setMinutes(int);
    
        // Method
        double fineCalc(); // calculate the fine
        string GetCarInfo();
    
    //  friend const ostream& operator << (ostream&, const ParkingTicket&);
    };
    
    const ostream& operator << (ostream&, const ParkingTicket&);
    
    #endif // PARKINGTICKET_H
        ParkingTicket.cpp


    #include "ParkingTicket.h"
    #include <iostream>
    #include <string>
    using namespace std;
    
    ParkingTicket::ParkingTicket() // Default Constructor
    {
        double fine = 0;
        double* fineptr = &fine;
        int minutes = 0;
        const int firstHour = 25;
        const int subHours = 10;
    }
    
    // Constructor with 2 parameters (ParkedCar and an integer)
    ParkingTicket::ParkingTicket(ParkedCar car, int min) 
    {
        minutes = min; // illegally parked minutes
        cout << "Minutes: " << endl;
        ParkingTicket::fineCalc(); // calculate fine
        cout << fine;
    }
    
    // Accessors
    double ParkingTicket::getFine()
    {
        return fine;
    }
    
    int ParkingTicket::getMinutes()
    {
        return minutes;
    }
    
    // Mutators
    double ParkingTicket::setFine(double f)
    {
        fine = f;
        return 0;
    }
    
    int ParkingTicket::setMinutes(int m)
    {
        minutes = m;
        return 0;
    }
    
    string GetCarInfo()
    {
        &Car::getMake;
        //&Car::getModel;
        //&Car::getColor;
        //&Car::getLicense;
    }
    
    // Car information, Time on the meter
    double ParkingTicket::fineCalc()
    {
        fine = 25;
        minutes -= 60;
        while (minutes >= 60)
        {
            fine += subHours;
            minutes -= 60;
        }
        if (minutes >= 0)
        {
            fine += subHours;       
        }
        return fine;
    }
    
    // Overload << operator
    const ostream& operator << (ostream& out, const ParkingTicket& obj)
    {
        out << &ParkingTicket::GetCarInfo;
        return out;
    }
        main.cpp


    #include <iostream>
    #include <string>
    #include "ParkedCar.h"
    #include "ParkingMeter.h"
    #include "ParkingTicket.h"
    #include "PoliceOfficer.h"
    
    using namespace std;
    
    int main()
    {
    
        ParkingTicket *ticket = nullptr;    
    
        ParkedCar car("Volkswagen", "1972", "Red", "147RHZM", 125);
    
        ParkingMeter meter(60);
    
        PoliceOfficer officer("Joe Friday", "4788");
    
        ticket = officer.patrol(car, meter);
        if (ticket != nullptr)
        {
            cout << "we made it this far officer" << endl;
            cout << officer;
            cout << "we are at the ticket" << endl;
            cout << *ticket;
    
            delete ticket;
            ticket = nullptr;
            
        }
        else
            cout << "No crimes were committed.\n";
    
        return 0;
    }

Why does the following code not result in moving the object instead of copying?

class A
{
public:
   A() { std::cout << "a ctor\n"; }
   A(const A&) { std::cout << "a copy ctor\n"; }
   A(A&&) { std::cout << "a move ctor\n"; }
};


A f(int i)
{
   A a1;
   return i % 2 == 0 ? a1 : A{};
}

int main()
{
   f(5);
   return 0;
}

The output is:

a ctor

a copy ctor

I would expect that a1 in f() will be moved not copied. If I change f() just a little bit, it's not a copy anymore but a move:

A f(int i)
{
   A a1;
   if (i % 2 == 0)
   {
      return a1;
   }
   return A{};
}

Could you explain me how does this work?

access and print data in a tuple and display it using a template function using C++14

i have a list like follows

my_mixed_list = {"Sample String", int_value, user_data_type}

I want to use C++11 std::tuple to display above list in simple white separated way. may be like this:

template <typename T>
    void display_mixed_items (std::tuple <T> mixed) {
         for (const auto& mixed_ele : mixed) std::cout << mixed_ele << " ";
}

I am aware that i would have to overload ostream operator to display the user defined data. But i hope you get the question. I'm not sure why compiler complains about argument list. what is proper way to accomplish above task. couldn't find exact answer on Stackoverflow so to mention.

in Python we could simple use list and tada! But if not tuple is there any other way to this may be using variadic templates or something.

Abort signal from abort(3) (SIGABRT) in C++

#include <iostream>
using namespace std;

int main()
{
    //code
    int test;
    cin >> test;
    while(test--)
    {
        int count = 0;
        string input;
        cin >> input;
        for (int j = 0; j < input.length() - 2; j++)
        {
           if (input.substr(j, 3) == "gfg")
           {
                count +=1;
           }
        }
        if (count > 0)
        {
            cout << count << endl;
        }
        else
        {
            cout << -1 << endl;
        }
        
    }
    return 0;
}

This code shows Abort signal from abort(3) (SIGABRT) while submitting in Geeks for Geeks while runs perfectly on the local computer and even works perfectly on various online compilers. Can't figure out the problem. Can someone help?

C++ 11 extension warning in VS code

I am trying to compile a c++ program in vs code and I am using mac osx. When I am trying to compile the program it shows "warning: range-based for loop is a C++11 extension [-Wc++11-extensions]".I have also changed the default C_Cpp.default.cppStandard to C++11. But after applying these changes also the error is showing.When I try to compile using "g++ -std=c++11" it is showing that 'cstdalign' file not found. I have included the bits/stdc++.h file.I am attaching the code images as well as my settings in vs code images below.Please help me to get rid of such error.

My c++ code

c_cpp_properties.json file

settings.json file

vendredi 26 juin 2020

accumulate with custom sum

The function below convert a string to integer, making use of std::accumulate.

It first checks the presence of a sign and skips it. The parameter c of lambda is fine as it just goes through all the remaining characters of input string s. But what about the first lambda parameter sum? How does it know that it should initialise sum to zero? And does the order of these lambda parameters matter?

int string2int(const string &s)
{
    return (s[0] == '-' ? -1 : 1) *
           accumulate(begin(s) + (s[0] == '-' || s[0] == '+'), end(s), 0,
                      [](int sum, char c) {
                          return sum * 10 + c - '0';
                      });
}

Btw, equivalent code without using std::accumulate would look something like this:

int string2int(const string &s)
{
    int sign = (s[0] == '-' ? -1 : 0);
    sign = (s[0] == '+' ? 1 : sign);

    int index = 0;
    if(sign != 0)
    {
        ++index;
    }

    int result = 0;
    for (auto i = index; i < s.size(); ++i)
    {
        result = result * 10 + (s[i] - '0');
    }

    sign = (sign < 0 ? -1 : 1);
    return result * sign;
}

UML Design Pattern and implementation into C++ classes

I am trying to learn Adapter Design Pattern UML with C++ and in one of the videos in youtube displayed this content - my issue is translating the UML picture to C++ class / code:

enter image description here

What I really get confused is:

  1. The Clinet -------> [solid line] association to interface Target. What does this means generally I have seen classes implementing interface something like Adapter class implementing Target

  2. What does the content Adapter is composed with the adaptee means here - if it is containership then does it completely or partially owns it?

Below is the code implementation that I can think of it:

class Target
{
public:
 void virtual ServiceA() = 0;
}; 

class Client : public Target
{
public:
Client(){}
void ServiceA() override {}
};

class Adaptee
{
public:
Adaptee(){}
void ServiceX(){}
};

class Adapter : public Target
{
public:
Adapter(){}
void ServiceA() override {adaptee.serviceX();}
Adaptee adaptee;
};

int main()
{
.....
}

How inside main we would code up? Please explain.

C++ Dynamic Dispatch Function

I'm trying to create an overloaded function that will be called with the dynamic type of an object. I try to do this without interfering with the actual class structure underneath, as I don't have direct access (i.e. I cannot add virtual methods, etc.)

As a concrete example, let's think of an AST class structure that looks somewhat like this:

class ASTNode {}; // this one is fully abstract; i.e. there's a virtual void method() = 0;

class Assignment : ASTNode {};
class Expression : ASTNode {};

class StringExpr : Expression {};
class MathExpr : Expression {};

I want to write a function act that will take an instance of ASTNode as parameter and, depending on its actual dynamic type do something different. The call will be something like this

std::shared_ptr<ASTNode> parsedAST = get_a_parsed_ASTNode(); // ... received from some parser or library
act(parsedAST);

Then, I want to act, depending on the dynamic type of the ASTNode.

void act(std::shared_ptr<MathExpr> expr)
{
  // Do something with Math expressions, e.g. evaluate their value
};

void act(std::shared_ptr<StringExpr> expr)
{
  // Do something with String  expressions, e.g. write their value to the log
};

void act(std::shared_ptr<Expression> expr)
{
  // do something with other types of expressions (e.g. Boolean expressions)
}; 

Currently though, I cannot call since they dynamic type will be maybe not the ``most concrete type''. Instead, I have to manually create a dispatcher manually as follows, but the method is a bit silly in my opinion, since it does literally nothing else but dispatch.

void act(std::shared_ptr<ASTNode> node_ptr)
{
  if(std::shared_ptr<MathExpr> derived_ptr = std::dynamic_pointer_cast<MathExpr>(node_ptr))
  {
    act(derived_ptr);
  }
  else if(std::shared_ptr<StringExpr> derived_ptr = std::dynamic_pointer_cast<StringExpr>(node_ptr))
  {
    act(derived_ptr);
  }
  else if(std::shared_ptr<Expression> derived_ptr = std::dynamic_pointer_cast<Expression>(node_ptr))
  {
     // do something with generic expressions. Make sure that this is AFTER the more concrete if casts
  }
  else if( ... )  // more of this
  {
     
  }
  // more else if
  else
  {
     // default action or raise invalid argument exception or so...
  }
};

This is especially annoying & error-prone since my class hierarchy has many (> 20) different concrete classes that can be instantiated. Also, I have various act-functions, and when I refactor things (e.g. add an act for an additional type), I have to make sure to pay attention to the correct order of if(dynamic_pointer_cast) within the dispatcher. Also it's not that stable, since a change in the underlying class hierarchy will require me to change every dispatcher directly, rather than just the specific act functions.

Is there a better / smarter solution? Evidently I'd appreciate "native" solutions, but I'm willing to consider libraries too.

Difficulty creating Spdlog asynchronous file logger

I am trying to make a logger for my application which doesn't run in the main thread. I am using a wrapper class, Logger, around spdlog. The class has a private static data member of type std::shared_ptr<spdlog::logger> which gets initialized in an init() function. I am able to successfully create a spdlog::sinks::basic_file_sink_mt but when I try to use spd::async_factory it won't compile.

Logger.h

class Logger {
public:
  static void init();
private:
  static std::shared_ptr<spdlog:::logger> my_logger;
}

Logger.cpp

std::shared_ptr<spdlog::logger> Logger::my_logger;

void Logger::init() {
  spdlog::sink_ptr my_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("myfile.log", true);
  my_logger = std::make_shared<spdlog::logger>("Application", my_sink);
}

This solution seems to work. It logs to the file, but the issue is that it is in the main thread. I try updating the logger to be asynchronous by changing the line std::make_shared<spdlog::sinks::basic_file_sink_mt> to be std::make_shared<spdlog::sinks::basic_file_sink_mt<spdlog::async_factory>> as follows:

void Logger::init() {
  spdlog::sink_ptr my_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt<spdlog::async_factory>>("myfile.log", true);
  my_logger = std::make_shared<spdlog::logger>("Application", my_sink);
}

When I try this I get compilation errors. What can I do to set my member variable to be an async logger?

Thanks for reading all of this, and thanks for the help.

I have tried this problem "SCUBADIV - Scuba diver" but i don't understand where am i getting wrong

this is the problem https://www.spoj.com/problems/SCUBADIV/

this is my solution

#include<bits/stdc++.h>
#define VI              vector <int>
#define ms(a,b)         memset(a, b, sizeof(a))
#define pb(a)           push_back(a)
typedef long long       ll;
using namespace std;

int dp[22][80][1001];
int knapsack(int o2[],int n2[],int wt[],int n,int t,int a)
{
    if(n==0||t==0||a==0)
    {
        return 0;
    }
    if(dp[t][a][n]!=-1)
    return dp[t][a][n];
    if(o2[n-1]>t && n2[n-1]>a)
    return dp[t][a][n]=knapsack(o2,n2,wt,n-1,t,a);
    if(o2[n-1]>t)
    return dp[t][a][n]=wt[n-1]+knapsack(o2,n2,wt,n-1,t,a-n2[n-1]);
    if(n2[n-1]>a)
    return dp[t][a][n]=wt[n-1]+knapsack(o2,n2,wt,n-1,t-o2[n-1],a);
    if(t>0 && a>0)
    return dp[t][a][n]=wt[n-1]+knapsack(o2,n2,wt,n-1,t-o2[n-1],a-n2[n-1]);
    if(t<0&& a>0)
    return dp[t][a][n]=knapsack(o2,n2,wt,n-1,0,a);
    if(t>0&& a<0)
    return dp[t][a][n]=knapsack(o2,n2,wt,n-1,t,0);
    if(t<0 && a<0)
    return dp[t][a][n]=knapsack(o2,n2,wt,n-1,0,0);
    
}
int main()
{   memset(dp,-1,sizeof(dp));
    int c;
    cin>>c;
    while(c--)
    {
        int t,a;
        cin>>t>>a;
        int n;
        cin>>n;
        int o2[n],n2[n],wt[n];
        for(int i=0;i<n;i++)
        cin>>o2[i]>>n2[i]>>wt[i];
        cout<<knapsack(o2,n2,wt,n,t,a)<<endl;
    }
}

I don\'t understand why is this giving wrong answer on submitting but passes the test case.

Here , I have taken a 3d dp having dimensions as oxygen , nitrogen,and weight of cylinder. Inside knapsack() arguments are o2 array,n2 array, wt array, size of array(n),oxygen need(t),nitrogen need(a).

C++ Builder adding Ctrl + A option

I have been trying to add Ctrl + A option in Builder 6 but I am out of ideas. I have tried using

(Shift.Contains(ssCtrl))

and add 'a' and 'A'. And I am kinda out of ideas how to look at this because as far as I remember Ctrl + C and Ctrl + V are added differently since they are default options. Or so I have been told.

I want a function to make a calculation in another function C++

I try to make a function in C++ to assign a value to a variable and keep it, But I want to make with void function. This is the Main function;

int main(){
    //declar variables
    double sales=0.0,commission=0.0,totalCom=0.0,totalSales=0.0,totalEmployee=0.0;
    //call soldEmployee function
    sales = soldEmployee(sales);    
    // if use enter sales negative the programe end
    while(sales > 0){
        //call calc commission
        commisionCalc(sales,commission);
        //call display commission
        displayCom(commission);
        //call display total (commission + sale)
        disTotal(sales,commission,totalEmployee);
        // ask user to put input again
        sales = soldEmployee(sales);
    }
    total(totalSales,commission);

    return 0;
 } //end of main function

And this the function;

double soldEmployee(double &s){//function to get the user input
    cout << "Next Sales: "; cin >> s;   
    return s;   
}

void commisionCalc(double s, double &com){//function to calc commission
    com = s * 0.10;
}

void displayCom(double c){;// function to display commission
    cout <<fixed << setprecision(2) << "Commision= " << c << endl;
}

void disTotal(double s,double com,double &total){// function to get commission + sales
    total = s + com;
    cout << "Salary + Com: " << total << endl;
}

void total(double t, double &total){// function to get the total of all employee commision and store it in total sales
    t += total;
    cout << "Total Salary: " << total << endl;
}

So, in function total I want to make it assign the commission I get into the totalSales, I know that the name of variables seems confusing but, this is because I made some modifies in the program. Can anyone help me explain how to make because I stuck when I made many function. and if you asking that there is a easy way to make i want this way because it's a assignment not work to learn how to make function and get used to it.

Using [][] operator with vectors?

I have created a one dimensional vector of int, how may I treat it like 2 dimensional one?

While I can write arr[1]; I can't write arr[1][2];

Why I need this: Instead of defining a vector of vectors [3x5] I defined a vector whose length is 15, so every time I have a function that takes coordinations of a place in matrix I have to call another function which converts those into one dimensional value, which is really annoying.

How to increase the priority of a thread on unix like platforms

I am trying to increase the priority of an std::thread in the following way.

auto t = std::thread([]() {
    // Some heavy logic
});
int policy;
sched_param sched_p;
pthread_getschedparam(t.native_handle(), &policy, &sched_p);
sched_p.sched_priority = 20;
pthread_setschedparam(t.native_handle(), SCHED_FIFO, &sched_p);

I wish to know what is the highest priority I can assign to my std::thread named as t above. Will above code set the priority of my std::thread to highest possible value?

Can I set sched_p.sched_priority higher than 20? Is there an option better than SCHED_FIFO to use so that I give it a higher priority?

Please note that I am trying to set a thread with a higher priority within a process.

Create Deep copy of boost::shared_ptr

I have two vectors of shared_ptr;

typedef boost::shared_ptr <A> someptr;
std::vector<someptr>src;
std::vector<someptr>dest;

If I copy using dest=src,both the vector elements are sharing the same memory location which increases the ref count of pointer.They both point to common location and any change in elements of one vector will affect the other.I understood that this is a shallow copy and it is the intended behaviour.

But if I want to create a deep copy for dest vector elements with different memory location ,what should I do?How to achieve this?

Does boost have a function to achieve this?

why I search in map stl time difference is a lot?

when I use stl map ,I meet some problems?

method1

cnt += umap[t];

method2

if (umap.find(t) != umap.end())
cnt += umap[t];

why method2 is more faster?

C++ std::experimental::is_detected not working in MSVC

I have some code which allow a value to be converted into a string, and this works perfectly in g++ and CLion, however when I try to run the same program with MSVC in Visual Studio the program gives many errors, some of which are syntax errors which is quite odd.

This is the code I am using:

// 1- detecting if std::to_string is valid on T
 
template<typename T>
using std_to_string_expression = decltype(std::to_string(std::declval<T>()));
 
template<typename T>
constexpr bool has_std_to_string = is_detected<std_to_string_expression, T>;
 
 
// 2- detecting if to_string is valid on T
template<typename T>
using to_string_expression = decltype(to_string(std::declval<T>()));
 
template<typename T>
constexpr bool has_to_string = is_detected<to_string_expression, T>;
 
 
// 3- detecting if T can be sent to an ostringstream
 
template<typename T>
using ostringstream_expression = decltype(std::declval<std::ostringstream&>() << std::declval<T>());
 
template<typename T>
constexpr bool has_ostringstream = is_detected<ostringstream_expression, T>;



// -----------------------------------------------------------------------------


// 1-  std::to_string is valid on T
template<typename T, typename std::enable_if<has_std_to_string<T>, int>::type = 0>
std::string toString(T const& t) {
    return std::to_string(t);
}
 
// 2-  std::to_string is not valid on T, but to_string is
template<typename T, typename std::enable_if<!has_std_to_string<T> && has_to_string<T>, int>::type = 0>
std::string toString(T const& t) {
    return to_string(t);
}
 
// 3-  neither std::string nor to_string work on T, let's stream it then
template<typename T, typename std::enable_if<!has_std_to_string<T> && !has_to_string<T> && has_ostringstream<T>, int>::type = 0>
std::string toString(T const& t) {
    std::ostringstream oss;
    oss << t;
    return oss.str();
}

I wonder if I am doing something very obviously wrong, or if there is something a bit more complicated leading to the issue. What do I need to change in order to make this program work in Visual Studio and compile correctly?

Exceptions Using Inheritance?

I wrote the following code:

class GameException : public mtm::Exception {
};

class IllegalArgument : public GameException {
public:
    const char *what() const noexcept override {
        return "A game related error has occurred: IllegalArgument";
    }
};

class IllegalCell : public GameException {
public:
    const char *what() const noexcept override {
        return "A game related error has occurred: IllegalCell";
    }
};

How may I use inheritance here to prevent some code duplication? As you can see I'm returning the same sentence but with different ending (Which is the class name). I though about implementing GameException as the following:

class GameException : public mtm::Exception {
     std::string className;
public:
    const char *what() const noexcept override {
        return "A game related error has occurred: "+className;
    }
};

But how may I change the value of className for the rest of my classes? Plus, I'm getting the error:

No viable conversion from returned value of type 'std::__1::basic_string' to function return type 'const char *'

Statelessly wrap a C callback interface in C++

I need to wrap a callback mechanism of a C interface statelessly in C++ accepting callables, i. e. the wrapper class shall not have any non-const members. In the C interface (not under my control) there is a function to add a callback:

void c_add_callback(void(*callback)(void* context), void* context)

Here is my attempt to wrap the C interface in a class accepting a reference to a callable:

class CppWrapper
{
public:
    // C++ callable parameter
    template<typename Function>
    void AddCallback(Function& function)
    {
        c_callbacks_.push_back
            ([](void* context)
                {
                    (*reinterpret_cast<Function*>(context))();
                }
            );
        c_add_callback
            (c_callbacks_.back()
            , reinterpret_cast<void*>(&function)
            );
    }
private:
    // storage of c callbacks
    std::list<void(*)(void*)> c_callbacks_;
};

Obviously, this approach is not stateless, as I have to store the callbacks (member c_callbacks_) as passed to the C interface.

Is there a way to implement the wrapper class stateless, i. e. get rid of the member?

Please see https://onlinegdb.com/rkeh-UNX0U for the full code example.

Some background: The intention to make the wrapper stateless comes from the fact that the library behind the C interface may at some point dispose all added callbacks. Obviously this would lead to an ever growing list (member c_callbacks_) when cyclically adding callbacks and triggering the library to dispose them. How can I cope with such leak if the dispose action is not propagated over the C interface?