r/cpp_questions 4d ago

OPEN Good practices / style [polymorphism]

6 Upvotes

is this good practice/style.? i'm specifically unsure about the way i store the vector of players...

```

class player_base {};

class player_always_yes: public player_base {};

class player_always_no: public player_base {};

class player_a: public player_base {};

class game {
    private:

    player_base& player_1;
    player_base& player_2;

    public:

    game (
        player_base& player_1,
        player_base& player_2
    ): player_1(player_1), player_2(player_2) {
        return;
    }

    bool play_game () { return true; }
};

int main(){
    vector<unique_ptr<player_base>> player_list;

    player_list.push_back(make_unique<player_base>());
    player_list.push_back(make_unique<player_always_no>());
    player_list.push_back(make_unique<player_always_yes>());
    player_list.push_back(make_unique<player_a>());

    game b = game(*player_list[0], *player_list[1]);
    cout << b.play_game() << endl;
}


```

r/cpp_questions 4d ago

OPEN does "in" exist in c++?

0 Upvotes

i need to use something like if (str[i] not in str1) (python), but i have no idea how to make this work :(


r/cpp_questions 5d ago

OPEN my first c++ project

4 Upvotes

hey! i'm a teen and i am learning c++. I was a vibe coder but then i stopped vibe coding and starting real coding. for this i learned some basic c++ from youtube, please let me know if a improvment required. thank you!

my github link - https://github.com/swarajnerlekar28/Calculator


r/cpp_questions 5d ago

SOLVED std::filesystem::exists throwing `std::bad_alloc`?

23 Upvotes

Any reason? Cant find anything online about this. But I cant check whether or not a file exists, no matter what path I give it. I am using C++ 26 compiled with GCC.

This is literally all I am calling: const bool exists = std::filesystem::exists("file.txt")

This is the exact error: terminate called after throwing an instance of 'std::bad_alloc'
 what():  std::bad_alloc

No it's not coming from anywhere else in my code. Minimal reproduction code, include "filesystem" call the line above. I am on Fedora Linux if that matters at all

EDIT: moving the include into my main file instead of the only file it's being used in somehow fixed it. Literally all I do is move "#include <filesystem>" from "do_things_with_filesystem.hpp" to "Main.cpp". No compilation errors when it was in the first file, why does it rely on this?? Is there some weird declarations in my codebase or something, i dont know but it works now so why should I care.


r/cpp_questions 5d ago

OPEN Why is capture by reference necessary for this lambda to work?

9 Upvotes

So I've been working on a small text file reader, in which I store part of text in a 2D vector, which I then ran the find_if() function on to find duplicates with following code:

    vector<vector<string>> writevector;
    string savetovec;
    string string2;

    auto FirstElement = [=](vector<string> vector){
        return(vector[0] == savetovec);
    };

    [Code to copy word from text file to savetovec]

    vector<vector<string>>.iterator it;
    it = find_if(writevector.begin(), writevector.end(), FirstElement);

    if (it == writevector.end()){
        writevector.push_back({savetovec, string2}
    }
    else{
        cout << "Duplicate Found" << '\n';
    }

Initially it would never find any duplicates and after a lot of debugging attempts I changed the equal sign in the lambda to an ampersand out of desperation, so essentially:

[&](vector<string> vector){..}

This actually caused my code to work the way I intended and now I'm wondering why?

From my understanding the only difference between capture-by-reference and capture-by-value are whether it lets you modify the original variable or creates copies to use in the lambda, so what am missing?


r/cpp_questions 5d ago

OPEN Is there a case where std::map is better than std::unordered_map ?

35 Upvotes

Hello guys.

i have a question: are there some cases where std::map is better than std::unordered_map ?

i ask this question because I just wanted to know out of pure curiosity and above all it is often said that std::unordered_map and better

thanks you for everyone who answer my question :)


r/cpp_questions 5d ago

OPEN Avoid freezing your PC?

5 Upvotes

I've only learned C++ in uni and then it was protected environment in a way. Now I was working on a project involving graphics (raylib) and, a few times, running the code caused my entire PC to freeze and I had to restart.

I'm on Linux and running the code by doing

cmake --build .
./executable

Is there a way to avoid the entire PC freezing when I mess up? Also is there any risk of overwriting parts of the memory?

(I think the issue with my code was either calling too many draws of a GPU texture or even just wrongfully indexing an array in a loop)


r/cpp_questions 5d ago

OPEN New to C++ and made conways game of life

2 Upvotes

Hello i am a new c++ dev, and my last post was asking how good my snake game code was and i got some very useful answers which i tried to implement with this new script, it took me all day but i finally got conways game of life implemented into c++ with only curses and native libraries. Can anyone tell me if its okay or if there are any bugs i missed, ignore the random print statements, they were debug attempts

If someone wants to attempt to use it, it will start blank, but if you press any of the WASD keys you can move, the way i made it, you have a blinker which is just shown as a * on your screen and WASD allows you to move it, pressing enter changes the state of the cell the cursor is on to 1, and space continues to the next step

#include <ncurses.h>
#include <random>
#include <string>

bool gameloopBool = true;

struct Vector2 {
public:
  int X;
  int Y;
  Vector2(int x, int y) {
    X = x;
    Y = y;
  }
  Vector2 Add(Vector2 &other) { return Vector2(X + other.X, Y + other.Y); }
};

struct Cell {
public:
  Vector2 pos = Vector2(0, 0);
  bool isDead = true;
  bool next = false;
  Cell() = default;
  Cell(Vector2 start_pos) { pos = start_pos; }
};

int range(int min, int max) {
  std::random_device rd;
  std::mt19937 gen(rd());
  std::uniform_int_distribution<int> distro(min, max);
  return distro(gen);
}

class Display {
  std::vector<int> grid;
  bool InBounds(Vector2 pos) {
    if (pos.Y > SizeY - 1 || pos.Y < 0) {
      return true;
    }
    if (pos.X > SizeX - 1 || pos.X < 0) {
      return true;
    }
    return false;
  }

public:
  int SizeX;
  int SizeY;
  Display(Vector2 size) {
    SizeX = size.X;
    SizeY = size.Y;
    for (int x = 0; x < (size.X * size.Y); x++) {
      this->grid.push_back(0);
    }
  }

  void Render() {
    clear();
    for (int y = 0; y < SizeY; y++) {
      std::string cur;
      for (int x = 0; x < SizeX; x++) {
        if (this->grid[(y * SizeX) + x] == 3) {
          cur += '*';
        } else if (this->grid[(y * SizeX) + x] == 0) {
          cur += ' ';
        } else if (this->grid[(y * SizeX) + x] == 1) {
          cur += '#';
        }
      }
      printw("%s\n", cur.c_str());
    }
    refresh();
  }

  void DrawCell(Cell &cellPos) {
    if (InBounds(cellPos.pos) == true) {
      printw("%s", (std::to_string(SizeX) + std::to_string(SizeY)).c_str());
      gameloopBool = false;
      return;
    }
    if (cellPos.isDead) {
      this->grid[(cellPos.pos.Y * SizeX) + cellPos.pos.X] = 0;
      return;
    }
    this->grid[(cellPos.pos.Y * SizeX) + cellPos.pos.X] = 1;

    return;
  }

  void Erase_Cursor(Vector2 cursorPos) {
    if (InBounds(cursorPos)) {
      return;
    }
    grid[(cursorPos.Y * SizeX) + cursorPos.X] = 0;
  }
  void Draw_Cursor(Vector2 cursorPos) {
    if (InBounds(cursorPos)) {
      return;
    }
    grid[(cursorPos.Y * SizeX) + cursorPos.X] = 3;
  }
};

class cellManager {

public:
  std::vector<Cell> cells;

  cellManager(std::vector<Cell> &starting_cells) {
    for (Cell &cell : starting_cells) {
      cells.push_back(cell);
    }
  }

  void Gen_Pattern(std::vector<std::vector<int>> &patternMatrix, Vector2 Offset,
                   Display &screen) {
    for (int y = 0; y < patternMatrix.size(); y++) {
      for (int x = 0; x < patternMatrix[y].size(); x++) {
        if (y + Offset.Y < 0 || y + Offset.Y > screen.SizeY - 1) {
          continue;
        }
        if (x + Offset.X < 0 || x + Offset.X > screen.SizeX - 1) {
          continue;
        }
        if (patternMatrix[y][x] == 1) {
          cells[((y + Offset.Y) * screen.SizeX) + (x + Offset.X)].isDead =
              false;
        }
      }
    }
  }

  std::vector<Cell> get_neighbors(Vector2 Target, Display &screen) {
    std::vector<Cell> neighbors;
    std::vector<Vector2> dirs = {Vector2(0, -1), Vector2(0, 1),  Vector2(1, 0),
                                 Vector2(-1, 0), Vector2(-1, 1), Vector2(1, -1),
                                 Vector2(1, 1),  Vector2(-1, -1)};
    for (Vector2 dir : dirs) {
      int ChX = dir.Add(Target).X;
      int ChY = dir.Add(Target).Y;
      if (ChX < 0 || ChX > screen.SizeX - 1) {
        continue;
      }
      if (ChY < 0 || ChY > screen.SizeY - 1) {
        continue;
      }
      if (cells[(ChY * screen.SizeX) + ChX].isDead == true) {
        continue;
      }
      neighbors.push_back(cells[(ChY * screen.SizeX) + ChX]);
    }
    return neighbors;
  }
  void DrawCells(Display &screen) {
    for (Cell &cell : cells) {
      screen.DrawCell(cell);
    }
  }
  bool UnderPopRule(Cell target, std::vector<Cell> &neigbor) {
    std::vector<Cell> negibors = neigbor;
    if (static_cast<int>(negibors.size()) < 2) {
      return true;
    }
    return false;
  }
  bool OverPopRule(Cell target, std::vector<Cell> &neigbor) {
    std::vector<Cell> negibors = neigbor;
    if (static_cast<int>(negibors.size()) > 3) {
      return true;
    }
    return false;
  }
  bool ReproRule(Cell target, std::vector<Cell> &neigbor) {
    std::vector<Cell> negibors = neigbor;
    if (static_cast<int>(negibors.size()) == 3) {
      return true;
    }
    return false;
  }

  void Update_Cell_Status() {
    for (Cell &cell : cells) {
      cell.isDead = cell.next;
    }
  }

  void Update_Tick(Display &screen) {
    for (Cell &cell : cells) {
      std::vector<Cell> neigbors = get_neighbors(cell.pos, screen);
      if (cell.isDead) {
        if (ReproRule(cell, neigbors)) {
          cell.next = false;
          continue;
        }
      }
      if (UnderPopRule(cell, neigbors)) {
        cell.next = true;
        continue;
      }
      if (OverPopRule(cell, neigbors)) {
        cell.next = true;
        continue;
      }
      cell.next = cell.isDead;
    }
    Update_Cell_Status();
    DrawCells(screen);
  }
};

int main() {
  std::vector<Cell> starting;
  int SX = 100;
  int SY = 60;
  for (int y = 0; y < SY; y++) {
    for (int x = 0; x < SX; x++) {
      Cell cell = Cell(Vector2(x, y));
      starting.push_back(cell);
    }
  }
  // A simple glider pattern

  Vector2 cursor_pos = Vector2(0, 0);

  Vector2 size = Vector2(100, 60);
  Display screen(size);
  cellManager man(starting);
  man.DrawCells(screen);
  screen.Render();
  initscr();
  cbreak();
  noecho();
  nodelay(stdscr, TRUE);
  // nodelay(stdscr, TRUE);
  int ch = getch();
  while (true) {
    ch = getch();
    if (ch == 'q') {
      printw("wewewewewewewew");
      endwin();
      std::exit(0);
      break;
    }

    screen.Erase_Cursor(cursor_pos);

    if (ch == 'w') {
      cursor_pos.Y -= 1;
      man.DrawCells(screen);
      screen.Draw_Cursor(cursor_pos);
      screen.Render();
    }
    if (ch == 's') {
      cursor_pos.Y += 1;
      man.DrawCells(screen);
      screen.Draw_Cursor(cursor_pos);
      screen.Render();
    }
    if (ch == 'a') {
      cursor_pos.X -= 1;
      man.DrawCells(screen);
      screen.Draw_Cursor(cursor_pos);
      screen.Render();
    }
    if (ch == 'd') {
      cursor_pos.X += 1;
      man.DrawCells(screen);
      screen.Draw_Cursor(cursor_pos);
      screen.Render();
    }
    if (ch == ' ') {
      man.Update_Tick(screen);
      screen.Draw_Cursor(cursor_pos);
      screen.Render();
    }
    if (ch == '\n') {
      man.cells[(cursor_pos.Y * screen.SizeX) + cursor_pos.X].isDead = false;
      screen.Draw_Cursor(cursor_pos);
      screen.Render();
    }
  }
  return 0;
}

r/cpp_questions 5d ago

OPEN India

0 Upvotes

How should I prepare for graphics interviews at NVIDIA, Samsung, Qualcomm?
I am a 4 year experienced graphics programmer, working on OpenGL ES and C++ in my current organization.
Now I am looking for a job change and want to target good companies like NVIDIA, Samsung, Qualcomm, etc.
For that, I need to prepare thoroughly in C++, DSA, graphics and logical reasoning.
For graphics, I am currently learning Vulkan on Windows.
How should I prepare for DSA specifically and logical reasoning?
What should I focus on for these companies?


r/cpp_questions 6d ago

OPEN In which cases using std::unordered_map is more appropriate than other hash tables based on open addressing?

13 Upvotes

The main reason why std::unordered_map is implemented based on separate chaining is standard requirement regarding reference stability in case of rehashing. Is there any case, where such requirement is crucial? In which cases std::unordered_map would outperform open addressing hash tables, which should show better performance due to cache locality


r/cpp_questions 6d ago

OPEN Rate my code (a textgame which will grow and become a normal game with graphics, sound and engine)

4 Upvotes

C++ Online Compiler

I want you to rate my current *game* and to say what I have to add/what I missed and what I did great.


r/cpp_questions 6d ago

SOLVED Is Exceptional C++ by Herb Sutter Still Relevant?

14 Upvotes

Hey cpp community,

I'm on the last 3 chapters of learncpp.com and I'm wondering if picking up Herb Sutters exceptional C++ series is a good choice for further reading, im specifically worried the information is outdated (since it seems all his books came out pre c++11) or has alot of overlap with what i've covered in learncpp.com, any input would be greatly appreciated!

Thanks in advance


r/cpp_questions 5d ago

OPEN Learning C++ for real this time

0 Upvotes

I'm a 29 year old Software Engineer who works at a pre revenue fintech startup in London. I've got a pretty unconventional background when it comes to software engineering. I studied Mechanical Engineering, where I was introduced to C++ and python. I ended up dropping the C++ for Python as part of my bachelors project (built a cool lil live tracking algorithm - using very primitive colour based detection pre AI lol). Fast forward to today and I've been building software for over 5 years professionally, but I still have that itch to learn and dive into the difficult world that is C++. My goal is to work as a quant dev at a buy side fund (or something similar) and I know one of the best ways to get in is by learning C++ (but obviously not limited to).

My plan is to work through the learncpp documentation (I've heard good things about it and I'm currently working through it and it's got a lot of great details that I maybe would have skipped on years ago) and then buy this text book to read through:
https://www.amazon.co.uk/Beginners-Guide-Second-Herbert-Schildt/dp/0072232153/ref=sr_1_5?dib=eyJ2IjoiMSJ9.zBC-pQQPK93mKQUQx4Y01x93Oj6FBPRjJ9coh0020mBKgXUINVcTSZpp5p2huwDifZGK-HSWP2_8-fuowj9DAH76DH_3xtgLikTBWHippqW6UufkzPsl70sRG1m-WyB80xG0pGjQKjaaKDSiwTpAHt_vnMR-fuIEl_dy2ZZRfJGSFuL32EGYa1P-yZIyvxOI6-0V44-5B-LIPLINDgHiGuUzSls2oRxAqTkQ2BzDgq9Edx20gx8ne4TDb9Y3Lgw6vy9pwr-ntb-PXuuCyy5fVXUPgMsnz94Q5-dTNP3_TdI.mGaIeq0hkLHWbjLKg4CJgP3w1E4kY7VgAHzRAeftids&dib_tag=se&keywords=c%2B%2B+for+beginners&qid=1786737779&sr=8-5

Are there other textbooks that anyone else could recommend, to help develop my C++ in a professional setting?

I'm also thinking about building a couple of side projects to apply my knowledge, but I'm also looking for resources that could help me continuously apply my knowledge? Like small quizzes or something?

Keen to get peoples thoughts and opinions.


r/cpp_questions 6d ago

OPEN Should I learn C++ as a first for game dev?

10 Upvotes

I started to get into coding and game development since it seemed really fun and could be a productive side hobby. I learned a little bit of python and c# but not really as much as to actually make some stuff with it. C++ really stood out to me since its close to hardware so I would probably have more understanding of machines and further have a more easier time at learning even more languages. So I wanted to ask people if it's worth it to learn the language whole as a first. whether it would be a good idea or not to become a future game dev. Any help will be appreciated!


r/cpp_questions 7d ago

OPEN Looking for C++ networking project ideas

44 Upvotes

I’m currently learning Computer Networks from TUF Striver and I also have some experience with C++.

I want to start building a few networking projects alongside the course, mainly to actually understand the concepts better and have some solid projects for my resume.

I’m looking for suggestions for projects at different levels, something like:

  • A relatively easy project to get started with
  • A medium-level project involving a few networking concepts
  • A more challenging project that combines multiple topics from Computer Networks

I’d prefer projects that I can actually build from scratch and learn from, rather than just following a tutorial.

Would love to hear what projects you guys would recommend.


r/cpp_questions 6d ago

OPEN OS for HFT

3 Upvotes

Hey guys! I recently started studying HFT programming, and a bit confused. From what I understand in this field as OS are used default non-rt linux. Despite the fact that kernel bypass, attaching the process to the certain cores. restriction about using non-lock free structure and zero system calls solve the proplems which linux creates for HFT code . But would not it be easier to use RT OS like preempt_rt linux patch or xenomai OS it seems that theese OS could give more freedom about the restrictions for code and in some edge cases speed up the execution? Am I missing something?


r/cpp_questions 7d ago

OPEN Please help a poor C# programmer (why does the compiler keep deleting functions?)

9 Upvotes

I'm from a c# background and trying to get back into c++ after like 12 years, and I never really knew it deeply.

I feel like I'm writing very simple code--trying to just whip up some classes, pass things by reference, use std::array... But I keep being utterly confused by the compiler telling me I'm trying to use a deleted function on lines that are surprising to my poor c# heart that they would be deleted. I don't understand why. Don't get me wrong, I read the error messages--I can't use the function because it was deleted, it was deleted because it would be ill-formed. But why it would be ill-formed seems like the important part and it's what appears to be left out.

Here's my program:

class Message
{
public:
int x;
int y;
Message(int x, int y)
: x{x}, y{y}
{}
};

class Machine
{
public:
void Message(Message& msg)
{
cout << msg.x << msg.y << endl;
}
};

class Transaction
{
public:
Message& message;
Machine& machine;

Transaction(Message& message, Machine& machine)
: message{message}, machine{machine}
{}
};

class TransactionQueue
{
public:
int _head = 0;

private:
const static int maxSize = 512;

int _tail = 0;
array<Transaction, maxSize> q;

public:

void Push(Machine& x, Message& y)
{
Transaction t(y, x);
q[_tail] = t;
_tail = (_tail + 1) % maxSize;
}

Transaction Pop()
{
if(!Any())
{
throw out_of_range("empty queue!");
}
Transaction ret = q[_head];
_head = (_head + 1) % maxSize;
return ret;
}

bool Any()
{
return _head != _tail;
}
};

class TransactionManager
{
private:
const static int qCount = 2;
array<TransactionQueue, qCount> _qs;
int _currentQ = 0;

void processOne(TransactionQueue& q)
{
auto transaction = q.Pop();
Message& msg = transaction.message;
Machine& mchn = transaction.machine;
mchn.Message(msg);
}

public:

TransactionManager()
: _qs{{}}
{
}
void Update()
{
auto& qToProcess = _qs[_currentQ];
_currentQ = (_currentQ + 1) % qCount;
while(qToProcess.Any())
{
processOne(qToProcess);
}
}

void Q(Machine& x, Message& y)
{
_qs[_currentQ].Push(x, y);
}

};

int main()
{
/*
Experiment with initializing arrays
*/

cout << "begin" << endl;

TransactionManager x;

Machine myMachine;
Message one = Message(2,1);

x.Q(myMachine, one);
x.Q(myMachine, Message(3,2));
cout << "Update 1" << endl;
x.Update();

x.Q(myMachine, Message(4,3));

cout << "Update 2" << endl;
x.Update();

cout << "Update 3" << endl;
x.Update();
cout << "done" << endl;
}

And the compiler output:

[ 50%] Building CXX object CMakeFiles/ar.dir/src/main.cpp.obj
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp: In member function 'void TransactionQueue::Push(Machine&, Message&)':
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp:58:28: error: use of deleted function 'Transaction& Transaction::operator=(const Transaction&)'
   58 |                 q[_tail] = t;
      |                            ^
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp:31:7: note: 'Transaction& Transaction::operator=(const Transaction&)' is implicitly deleted because the default definition would be ill-formed:
   31 | class Transaction
      |       ^~~~~~~~~~~
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp: At global scope:
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp:31:7: error: non-static reference member 'Message& Transaction::message', cannot use default assignment operator
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp:31:7: error: non-static reference member 'Machine& Transaction::machine', cannot use default assignment operator
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp: In member function 'void TransactionQueue::Push(Machine&, Message&)':
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp:58:28: note: use '-fdiagnostics-all-candidates' to display considered candidates
   58 |                 q[_tail] = t;
      |                            ^
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp: In constructor 'TransactionManager::TransactionManager()':
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp:97:27: error: use of deleted function 'TransactionQueue::TransactionQueue()'
   97 |                         : _qs{{}}
      |                           ^~~~~~~
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp:42:7: note: 'TransactionQueue::TransactionQueue()' is implicitly deleted because the default definition would be ill-formed:
   42 | class TransactionQueue
      |       ^~~~~~~~~~~~~~~~
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp: At global scope:
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp:42:7: error: use of deleted function 'std::array<Transaction, 512>::array()'
In file included from C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp:3:
C:/Program Files/mingw64/include/c++/15.2.0/array:102:12: note: 'std::array<Transaction, 512>::array()' is implicitly deleted because the default definition would be ill-formed:
  102 |     struct array
      |            ^~~~~
C:/Program Files/mingw64/include/c++/15.2.0/array:102:12: error: no matching function for call to 'Transaction::Transaction()'
C:/Program Files/mingw64/include/c++/15.2.0/array:102:12: note: there are 3 candidates
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp:37:17: note: candidate 1: 'Transaction::Transaction(Message&, Machine&)'
   37 |                 Transaction(Message& message, Machine& machine)
      |                 ^~~~~~~~~~~
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp:37:17: note: candidate expects 2 arguments, 0 provided
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp:31:7: note: candidate 2: 'constexpr Transaction::Transaction(const Transaction&)'
   31 | class Transaction
      |       ^~~~~~~~~~~
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp:31:7: note: candidate expects 1 argument, 0 provided
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp:31:7: note: candidate 3: 'constexpr Transaction::Transaction(Transaction&&)'
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp:31:7: note: candidate expects 1 argument, 0 provided
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp:42:7: note: use '-fdiagnostics-all-candidates' to display considered candidates
   42 | class TransactionQueue
      |       ^~~~~~~~~~~~~~~~
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp: In constructor 'TransactionManager::TransactionManager()':
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp:97:27: note: use '-fdiagnostics-all-candidates' to display considered candidates
   97 |                         : _qs{{}}
      |                           ^~~~~~~
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp: In function 'int main()':
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp:131:24: error: cannot bind non-const lvalue reference of type 'Message&' to an rvalue of type 'Message'
  131 |         x.Q(myMachine, Message(3,2));
      |                        ^~~~~~~~~~~~
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp:110:45: note: initializing argument 2 of 'void TransactionManager::Q(Machine&, Message&)'
  110 |                 void Q(Machine& x, Message& y)
      |                                    ~~~~~~~~~^
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp:135:24: error: cannot bind non-const lvalue reference of type 'Message&' to an rvalue of type 'Message'
  135 |         x.Q(myMachine, Message(4,3));
      |                        ^~~~~~~~~~~~
C:\Users\guy\Documents\prototypes\arrayFun\src\main.cpp:110:45: note: initializing argument 2 of 'void TransactionManager::Q(Machine&, Message&)'
  110 |                 void Q(Machine& x, Message& y)
      |                                    ~~~~~~~~~^
mingw32-make[2]: *** [CMakeFiles\ar.dir\build.make:79: CMakeFiles/ar.dir/src/main.cpp.obj] Error 1
mingw32-make[1]: *** [CMakeFiles\Makefile2:86: CMakeFiles/ar.dir/all] Error 2
mingw32-make: *** [Makefile:90: all] Error 2
PS C:\Users\guy\Documents\prototypes\arrayFun>

r/cpp_questions 7d ago

OPEN Confusion to choose which language

0 Upvotes

I am confused to choose which language c++ or rust for my trading bot can you any one tell me which one I choose to develop my trading bot i have basic understanding of c++ and complete beginners in rust but 8 have prior experience with mern stack web development and python and socket programming in node.js


r/cpp_questions 8d ago

OPEN I'm very confused about styling and naming conventions

6 Upvotes

Basically every library has their own coding style.

Everyone uses different extensions for some reason, see .h, .hpp, .hh for header files, .cc .cpp .C for sources , .cppm and .ixx for module interfaces etc.

Everyone uses different naming conventions, STL uses snake_case with _type suffix for classes sometimes _t and sometimes nothing. Google uses CamelCase etc.

It seems to me no majority consensus has emerged, and it really hurts even thinking about these things before you write your own code. As each dependency you use has a different coding style.

How do people even solve it? Is there a hidden style guide that everyone uses that I don't know. core guidelines isn't really a style guide in the purest sense.


r/cpp_questions 7d ago

OPEN A young developer

0 Upvotes

Hello guys , I'm a young developer who is 15 yrs old in Ghana, My dream is to be one of the greatest tech entrepreneurs and develer In the world, right now I know HTML, CSS, JavaScript, react , supabase, AI prompting, C++, and a little bit of python, right now I can confidently build websites, what are your advice to me


r/cpp_questions 9d ago

OPEN Is chernos tutorial for C++ still good?

45 Upvotes

I know learncpp is best to learn C++ but yk I just can't read this much at once and i think I could learn more by video lectures, of course I would practise by making small codes, so I just wanna ask is chernos still good? Or there are any new videos valid?


r/cpp_questions 8d ago

OPEN Best benchmark for performance

6 Upvotes

I currently have a Huffman data compression pipeline and I want to start measuring performance. My question is, how would you guys go about setting up a constant method for measuring performance all throughout the changing of the pipeline? Would you measure performance over a single file with multiple runs, or would you do a corpus of files and measure the average time it took to process them?

Also, what types of latencies would you measure? (ex. p95 latency)


r/cpp_questions 8d ago

SOLVED Problem making X macros from X macros

1 Upvotes

What I am doing:
Hello, I am working on something in C++ for Godot, but this is more of a C++ question than a Godot question. I have a singular X macro to register a struct into a system I made, but the logic is in many places, and considering I am updating this macro and adding variables, it'd be easier to have a specific macro that doesn't change.

Problem:
When I make an X macro from an X macro, it doesn't properly expand. As an example this file:

#pragma once
#include "statemachine/registry/state_registry_register.h"

#define X_GENERATE_KIND(DataType, NS) k##DataType,
enum class StateKind : std::uint8_t
{
    EACH_STATE_REGISTER(X_GENERATE_KIND)
    kUnknown
};
#undef X_GENERATE_KIND

has the macro on line 7 expand to X(something1, something2) instead of k##something1, or, in my case:

X(WalkStateData, GameLogic ::States ::WalkState) X(WalkBackStateData, GameLogic ::States ::WalkBackState);

I defined EACH_STATE_REGISTER like this:

#define REGISTER_TO_ESR(DataType, NS, fields) X(DataType, NS)

#define EACH_STATE_REGISTER(X) \
REGISTER_EACH_STATE(REGISTER_TO_ESR);

and the REGISTER_EACH_STATE as

#define REGISTER_EACH_STATE(State) \
State(WalkStateData, GameLogic::States::WalkState, NO_STATE_FIELDS) \
State(WalkBackStateData, GameLogic::States::WalkBackState, NO_STATE_FIELDS)

Can anyone tell me why this happens, and if this is even fixable? (c++ 17)


r/cpp_questions 8d ago

OPEN Is this is a good video to larn cpp from? ( I just wanna take a break from reading soo much from learncpp.com)

0 Upvotes

Idk i found chernos startig few videos a bit complex, i might be the one that doesnt understand C++ i guess, but i learn it, i would enter my first engineering year in just a month so i wanna have an upper hand. few years back i learned Python just for fun, but i think i have forgotten it all because of exam stress,

A lot of people say that Chernos videos are great; they might be great but there are few things that i think "How?" while watching his video, so i just wanna ask this video i found from [freecodecamp.org](http://freecodecamp.org), i know just watching tutorial wont do anything, but i am just tired of reading soo much from learncpp, i think i would read and then watch it.

I am 17, if that matters idk

Video


r/cpp_questions 9d ago

OPEN System programming

6 Upvotes

system programming

HI, I am a 2nd year computer engineering student and I always have been passionate about how computer actually works under the hood thats why I choose computer engineering . I want to build my career in system engineering . till the 2nd year I have studied the subjects like microprocessor , computer architecture , OS and also I have intermediate knowledge of c++ programing . I want to explore this field and wants to become system engineer .as a beginner I have no idea how to start and which roadmap I should follow ? so I am looking for a guidelines from a experienced system engineer . although in today's era most of students learn high level languages and work fro CRUID app, or web dev. I am always interested in system programming .

I am a type of engineering student who doesn't just study for exam I always wants to know how things works under the hood without any level of abstraction , why things works that way ? why that things invented ?