question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
72,491,412
72,495,481
Getting Qt Test output in GitHub actions
Currently the only thing I can see is the executable exit code, so I can see if any tests failed or not, but I don't get any other output. Is there a way to show something similar to what you see in Qt Creator when running tests? I am using CMake and the Qt Test framework.
You can use -junitxml option to output test results to xml file(s) and use one of actions to watch detailed reports: action-junit-report publish-unit-test-results junit-report-action test-reporter report-junit-annotations-as-github-actions-annotations
72,491,968
72,492,095
CreateProcessWithLogonW can't read 0xCCCCCCCC Error
I am currently trying to inject a username and password into lsass.exe with c++, i am pretty new to c++ so this might be a stupid question but it always throws me the error '0xC0000005: Access violation reading at location 0xCCCCCCCC'. Here is my code: #include <iostream> #include <windows.h> #include <processthreadsapi.h> int main() { STARTUPINFO si; PROCESS_INFORMATION pi; si.dwFlags = 0x00000001; si.wShowWindow = 0; LPCWSTR userName = L"username"; // The username that will be injected into LSASS LPCWSTR userDomain = L"domain"; // The Logon Domain that will be injected into LSASS LPCWSTR userPassword = L"password"; // The User Password that will be injected into LSASS LPCWSTR applicationName = L"path"; LPCWSTR currentDirectory = L"C:\\"; bool r = CreateProcessWithLogonW(userName, userDomain, userPassword, 0x00000002, applicationName, NULL, 0x04000000, NULL, currentDirectory, &si, &pi); std::cout << r << std::endl; WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } I'm not sure, but in the variable list of visual studio debugger, the &pi and &si contain '0xCCCCCCCC', more specific: the hProcess and hThread of &pi both have it I pretty much just copy-pasted the code from here: https://blog.spookysec.net/DnD-LSASS-Injection/ and it worked for them... Thanks for any help in advance Edit: It does run now, I have changed STARTUPINFO si; PROCESS_INFORMATION pi; to STARTUPINFO si = {0}; PROCESS_INFORMATION pi = {0}; but it doesn't seem like I have the rights I should have... I logged in to my own user account but couldn't even copy a file in the startup folder...
You need more initialization of the STARTUPINFO structure. In particular, the size of the structure. The operating system uses the size of the structure to determine what members are present. It is like a structure version. STARTUPINFO si = {0}; si.cb = sizeof(si);
72,492,238
72,492,351
Invalid application of incomplete type 'Test::Impl'
Please have a look at directory structure first [ attached at the bottom of the question end]. Following are my Cmake files : Main cmake cmake_minimum_required(VERSION 3.9) set (CMAKE_CXX_STANDARD 14) add_executable (test main.cc) target_include_directories(test PUBLIC test_include_interface) target_link_libraries(test PUBLIC test_test) Test cmake : add_library(test_include_interface INTERFACE) target_include_directories(test_include_interface INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}) add_library(test_test STATIC test_interface.h test.h test.cc) target_include_directories(test_test INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}) test.h #pragma once #include "test_interface.h" #include <memory> class Test : public ITest { public: Test(); private: class Impl; std::unique_ptr<Impl> impl_; }; test.cc #include "test.h" class Test::Impl { public: Impl() {} ~Impl() {} }; Test::Test() : impl_{std::make_unique<Impl>()} {} Error : In file included from /usr/include/c++/9/memory:80, from /home/vkd0726/test/test/test.h:9, from /home/vkd0726/test/main.cc:2: /usr/include/c++/9/bits/unique_ptr.h: In instantiation of ‘void std::default_delete<_Tp>::operator()(_Tp*) const [with _Tp = Test::Impl]’: /usr/include/c++/9/bits/unique_ptr.h:292:17: required from ‘std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp = Test::Impl; _Dp = std::default_delete<Test::Impl>]’ test/test/test.h:11:7: required from here /usr/include/c++/9/bits/unique_ptr.h:79:16: error: invalid application of ‘sizeof’ to incomplete type ‘Test::Impl’ 79 | static_assert(sizeof(_Tp)>0, | ^~~~~~~~~~~ make[2]: *** [CMakeFiles/test.dir/build.make:63: CMakeFiles/test.dir/main.cc.o] Error 1 make[1]: *** [CMakeFiles/Makefile2:76: CMakeFiles/test.dir/all] Error 2 make: *** [Makefile:84: all] Error 2 Please help me understand this error and how to resolve it ? Is it a problem with the Cmake or code itself. I have seen such "Impl" design pattern use at many places but unable to write a test snippet. What is wrong here ? Directory structure
The Test does not contain a user defined destructor, so the compiler generates a inlined version of this destructor. Since this destructor involves logic to delete the Test::Impl object when the destructor of std::unique_ptr<Test::Impl> is invoked, you get the error your compiler complains about. You can fix this by defining the destructor in test.cc: test.h #include <memory> class Test : public ITest { public: Test(); ~Test(); // new private: class Impl; std::unique_ptr<Impl> impl_; }; test.cc class Test::Impl { ... }; ... Test::~Test() = default;
72,492,416
72,494,236
Missing libgcc_s_seh-1.dll starting the .exe on Windows
Intro I have a CMake-based C++ project. Until now I build and ran the project via CLion. Everything worked fine until I tried to run the .exe-file directly (not via CLion). Problem When I navigate to the cmake build directory in order to start my program via the executable file, it fails with the following message in the popup: Cannot continue the code execution because libgcc_s so-1.dll was not found. Reinstalling the program may resolve the issue. I have the following questions If I interpret the error message correctly, then this dll is missing on my computer. So I ask myself, why does my program still work when I start it via the development environment (CLion), although the error message expressly states that the source code requires this dll? Is it the fault of my application/source code that the error appears or rather the current state of my computer? If the former, how can I prevent this error from appearing for other users? What is the best way to fix this error? It's obvious that I need to download this dll, but where is the best place to put it (which directory and environment variable to use on Window)? Which source is trustworthy to download this dll? I don't want to download any malware under this dll-name. Optional: What kind of library is that? What functionalities does it offer? Additional information I use CMake as my build tool, CLion as the IDE and MinGW as the compiler. What I have did so far? I made sure it still works through the IDE. I found this dll does not exist in the MinGW installation folder. I searched the web for more information. Unfortunately, there are only pages unknown to me that only offer the download of this dll. That doesn't satisfy me.
I found the cause of my problem: I had two MingGW installations on my machine. Once the installation that comes with CLion and a separate one. The latter did not have the required dll. However, CLion used its own installation, which in turn owns the DLL. So the solution was to remove the separate installation and include the path to the CLion installation's bin/ directory in the PATH environment variable.
72,492,589
72,493,650
How to overlay 2 Images in QT
I have 2 images that I load in QImage and my question is : How can I overlay these 2 images in the simplest way, to then save it in a QPixmap ? Here are the following images : And the awaited result : (The final image will be used in a QTableView to show the user if it has more of the same potion)
I was able to find the answer on my own after some more research. Here is my code that I came up with (if you can do it better I would like to see it because I would like to implement any better approach if there is any): QPixmap base = QPixmap::fromImage(QImage("Your 1st img")); QPixmap overlay = QPixmap::fromImage(QImage("your 2nd img")); QPixmap result(base.width(), base.height()); result.fill(Qt::transparent); // force alpha channel { QPainter painter(&result); painter.drawPixmap(0, 0, base); painter.drawPixmap(0, 0, overlay); } QStandardItem *pCombinedItem = new QStandardItem(); //this variable should be in the .h file if you want to conserve it further on. pCombinedItem->setData(QVariant(result), Qt::DecorationRole);//adding the final img into the StandardItem which we can put then into our table after we put it into a StandardItemModel like so : model->setItem(1,4,pCombinedItem); pInventory->setModel(model); //and we can put our model into our tableview
72,493,507
72,493,647
Line 1034: Char 9: runtime error: reference binding to misaligned address 0xbebebebebebebebe for type 'int'
class Solution { private: void make_zero(vector<vector<int> >& matrix,vector<pair<int,int>>v,int n,int m) { for(auto i:v) { for(int j=0;j<n;j++) { matrix[i.first][j]=0; } for(int j=0;j<m;j++) { matrix[j][i.second]=0; } } } public: void setZeroes(vector<vector<int>>& matrix) { int n=matrix.size(); int m=matrix[0].size(); vector<pair<int,int>>v; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(matrix[i][j]==0) { v.push_back({i,j}); } } } make_zero(matrix,v,n,m); } };
n and m are swapped around in make_zero(), you confused the row and column dimensions.
72,493,660
72,493,692
Why does 0.125, formatted with 2 digits of decimal precision, show "0.12" not "0.13"?
Consider: #include <iostream> #include <iomanip> int main() { std::cout << std::fixed << std::setprecision(2); std::cout << 0.125 << '\n'; // Prints "0.12" std::cout << 0.126 << '\n'; // Prints "0.13" as expected } Demo I know that floating point math isn't perfectly precise, but isn't 0.125 one of the values that actually is represented exactly? Why does it round down to "0.12" instead of up to "0.13" when formatting it?
Yes, 0.125 is one of the rare floating point values that should have an exact binary representation. Your rounding mode is probably set to round-half-to-even.
72,493,712
72,493,772
Why does the "size_of_array" template fucntion does not work with int a[n] (size defined at runtime) while it works fine with int a[4]?
template <typename T, int n > int tell_me_size(T (&) [n]){ return n; } this code works fine with int a[4]; cout<< tell_me_size(a)<<endl; while does not work with int n; cin>>n; int a[n]; cout<< tell_me_size(a)<<endl; The later gives the error "no matching function for call to ‘tell_me_size(int [n])"
According to the C++ 20 Standard (13.4.3 Template non-type arguments) 2 A template-argument for a non-type template-parameter shall be a converted constant expression (7.7) of the type of the template-parameter. Pay attention to that variable length arrays like this int n; cin>>n; int a[n]; are not a standard C++ feature.
72,493,969
72,494,031
Unexpected behavior of c++ program on executing two equivalent statements
I was trying to solve this problem, while doing so, it looks like for (int i=row1; i<=row2; i++) { if (col1 != 0) sum -= mat[i][col1-1]; sum += mat[i][col2]; } and for (int i=row1; i<=row2; i++) { sum += (mat[i][col2] - (col1 != 0) ? mat[i][col1-1] : 0); } are equivalent, but executing the later results in following error Line 1038: Char 34: runtime error: addition of unsigned offset to 0x618000000080 overflowed to 0x61800000007c (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34 Am I missing something?, Thank You In Advance. complete program: class NumMatrix { public: vector<vector<int>> mat; NumMatrix(vector<vector<int>>& matrix) { mat = matrix; for (int i=0; i<matrix.size(); i++) { for (int j=1; j<matrix[0].size(); j++) mat[i][j] += mat[i][j-1]; } } int sumRegion(int row1, int col1, int row2, int col2) { int sum = 0; for (int i=row1; i<=row2; i++) { if (col1 != 0) sum -= mat[i][col1-1]; sum += mat[i][col2]; // sum += (mat[i][col2] - (col1 != 0) ? mat[i][col1-1] : 0); // this gives error : // Line 1038: Char 34: runtime error: addition of unsigned offset to 0x618000000080 overflowed to 0x61800000007c (stl_vector.h) // SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34 } return sum; } }; /** * Your NumMatrix object will be instantiated and called as such: * NumMatrix* obj = new NumMatrix(matrix); * int param_1 = obj->sumRegion(row1,col1,row2,col2); */
This statement sum += (mat[i][col2] - (col1 != 0) ? mat[i][col1-1] : 0); is equivalent ti sum += (mat[i][col2] - (col1 != 0) ) ? mat[i][col1-1] : 0; So for example if this expression (mat[i][col2] - (col1 != 0) ) is not equal to 0 then you will have in fact sum += mat[i][col1-1]; even when col1 is equal to 0. It seems you mean sum += mat[i][col2] - ( (col1 != 0) ? mat[i][col1-1] : 0); Pay attention to that this function int sumRegion(int row1, int col1, int row2, int col2) { is unsafe. There is no check whether row1, row2, col1 and col2 are in valid ranges.
72,494,117
72,497,888
Compile time check that lcm(a,b) doesn't overflow
I would like to have a compile-time check that taking the least common multiple of two numbers doesn't overflow. Difficulty: regarding std::lcm, The behavior is undefined if |m|, |n|, or the least common multiple of |m| and |n| is not representable as a value of type std::common_type_t<M, N>. (Source: https://en.cppreference.com/w/cpp/numeric/lcm) Here is what I have come up with: #include <type_traits> #include <cstdint> #include <numeric> template<int8_t a, int8_t b, std::enable_if_t< (std::lcm(a,b) > 0 && (std::lcm(a,b) % a == 0) && (std::lcm(a,b) % b == 0)), std::nullptr_t> = nullptr> void f() { } The rationale here is that that the condition checks that std::lcm(a,b) has produced a positive number of type std::common_type_t<typeof(a), typeof(b)> which is a multiple of both a and b. Given that some common multiple of a and b fits in std::common_type_t<typeof(a), typeof(b)>, it follows that the least common multiple fits, and therefore we are guaranteed by the definition of std::lcm that what we have computed is in fact the lcm. I checked that this appears to work correctly, e.g. f<3, 5>(); // compiles f<127, 127>(); // compiles f<35, 48>(); // doesn't compile However I have a couple of questions. The documentation says that if the least common multiple is not representable, the behavior is undefined, and not just implementation-dependent or something. Does this mean that a program containing something like f<35,48>() is ill-formed and that the compiler is welcome to actually compile said code with arbitrary results? Is there a simpler way of doing what I'm trying to do? I suppose I could write my own constexpr safe_lcm function that would guarantee defined behavior and return 0 in the case of an overflow, but that seems like a pretty inelegant solution and also I'd have to work pretty hard to make sure I covered every conceivable combination of arithmetic types I might feed to it. Update: It sounds like undefined behavior isn't allowed in constant expressions. Since I clearly need this to be a constant expression in order to use it at compile time, does that mean I'm safe here? Update 2: This appears to be a definite strike against the no-undefined-behavior-in-constexpr theory: template<int n> struct S {}; template<int8_t a, int8_t b> S<std::lcm(a, b)> g() { return S<std::lcm(a,b)>(); } int main(int, char **) { g<35, 48>(); // compiles :'( return 0; }
Assuming that both a and b are positive, there is the relationship a * b == lcm(a,b) * gcd(a,b) that you can use to your advantage. Computing gcd(a,b) does not overflow. Then you can check whether a / gcd(a,b) <= std::numeric_limits<CT>::max() / b where CT is std::common_type_t<decltype(a),decltype(b)>.
72,494,498
72,494,834
How do i print the path to a node in C++ if the nodes only contain pointers to their parents?
The task was to make a kind of file system in c++, where the user can create, remove, cd into and out of folders and list subfolders. After every operation the program should print out the path to either the current folder or the created/removed folder. I stumbled on the path printing: struct dir { std::string name; dir* parent; }; std::string path(dir* a) { if(a->parent==NULL) return ""; return path(a->parent) +"/"+ a->name; } Example: #include<iostream> #include<vector> #include<string> struct dir { std::string name; dir* parent; }; std::vector<dir> sys; dir* currentdir; std::string path(dir* a) { if(a->parent==NULL) return ""; return path(a->parent) +"/"+ (*a).name; } int main() { sys.push_back({"",NULL}); sys.push_back({"a",&sys[0]}); sys.push_back({"b",&sys[1]}); sys.push_back({"c",&sys[2]}); sys.push_back({"d",&sys[3]}); sys.push_back({"e",&sys[4]}); sys.push_back({"f",&sys[5]}); sys.push_back({"g",&sys[6]}); sys.push_back({"h",&sys[7]}); sys.push_back({"i",&sys[8]}); currentdir = &sys[9]; std::cout << path(currentdir); } This gives the output ////////h/i instead of /a/b/c/d/e/f/g/h/i
As you push new elements into sys it will eventually fill up and have to reallocate its elements, at that point all the pointers you've saved into parent become invalid and your program has undefined behaviour. An easy solution would be to call reserve before creating any elements, you'll need to ensure you never exceed the reserved capacity otherwise you'll have the same problem again. Another option would be to store an index into the sys array instead.
72,494,618
72,494,688
Undefined behavior allowed in constexpr -- compiler bug?
My understanding is that: Signed integer overflow in C++ is undefined behavior Constant expressions are not allowed to contain undefined behavior. It seems to follow that something like the following should not compile, and indeed on my compiler it doesn't. template<int n> struct S { }; template<int a, int b> S<a * b> f() { return S<a * b>(); } int main(int, char **) { f<50000, 49999>(); return 0; } However, now I try the following instead: #include <numeric> template<int n> struct S { }; template<int a, int b> S<std::lcm(a, b)> g() { return S<std::lcm(a,b)>(); } int main(int, char **) { g<50000, 49999>(); return 0; } Each of g++, clang, and MSVC will happily compile this, despite the fact that The behavior is undefined if |m|, |n|, or the least common multiple of |m| and |n| is not representable as a value of type std::common_type_t<M, N>. (Source: https://en.cppreference.com/w/cpp/numeric/lcm) Is this a bug in all three compilers? Or is cppreference wrong about lcm's behavior being undefined if it can't represent the result?
According to [expr.const]/5, "an operation that would have undefined behavior as specified in [intro] through [cpp]" is not permitted during constant evaluation, but: If E satisfies the constraints of a core constant expression, but evaluation of E would evaluate an operation that has undefined behavior as specified in [library] through [thread], or an invocation of the va_­start macro ([cstdarg.syn]), it is unspecified whether E is a core constant expression. We usually summarize this as "language UB must be diagnosed in a context that requires a constant expression, but library UB does not necessarily need to be diagnosed". The reason for this rule is that an operation that causes library UB may or may not cause language UB, and it would be difficult for compilers to consistently diagnose library UB even in cases when it doesn't cause language UB. (In fact, even some forms of language UB are not consistently diagnosed by current implementations.) Some people also refer to language UB as "hard" UB and library UB as "soft" UB, but I don't like this terminology because (in my opinion) it encourages users to think of "code for which it's unspecified whether language UB occurs" as somehow less bad than "code that unambiguously has language UB". But in both cases, the result is that the programmer cannot write a program that executes such code and expect anything to work properly.
72,494,684
72,495,061
restore broken cpp libs linux
So, I was trying to compile dlib but it spitted out many errors. Appearently, my cpp files are broken. Even as simple as compiling a cout << "Hello World"; with g++ resolves in issues. Here's the log: https://pastebin.com/bTkdaycn Is there any way to "restore" broken cpp files? I haven't really messed around with the libraries. Yes, I WANT TO reinstall (remove/install) CPP 11 libs. I just don't know, how. I tried apt install --reinstall and dpkg-reconfigure and everything. Thank you in advice
So, I got it. For everyone wondering, I went to my windows pc, which had wsl on it. I scp'd the entire /usr/include/c++/11 directory to myself and replaced. Now everything works. Like a dirty wooden-hammer solution, but it's a solution
72,494,822
72,494,879
Max Heap Insert Function Implementation C++
I'm trying to insert key values into heap. I'm using TestUnit.cpp for errors. I got these errors: Assert failed. Expected:<[(10,100),(7,70),(6,60),(5,50),(2,20),(1,10),(3,30),(4,40)]> Actual:<[(7,70),(5,50),(6,60),(4,40),(2,20),(1,10),(3,30),(10,100)]> Assert failed. Expected:<[(10,100),(4,40),(5,50),(1,10),(2,20),(3,30)]> Actual:<[(5,50),(4,40),(3,30),(1,10),(2,20),(10,100)]> Assert failed. Expected:<[(9,90),(7,70),(8,80),(6,60),(2,20),(1,10),(3,30),(5,50)]> Actual:<[(9,90),(7,70),(8,80),(5,50),(2,20),(1,10),(3,30),(6,60)]> Assert failed. Expected:<[(6,60),(5,50),(4,40),(1,10),(2,20),(3,30)]> Actual:<[(6,60),(5,50),(3,30),(1,10),(2,20),(4,40)]> My insert function is : void insert(KeyValueType const& keyValue) { size_t asize = size(); if (asize == 0) { table.push_back(keyValue); } else { table.push_back(keyValue); for (int i = asize / 2 - 1; i >= 0; i--) { heapify(i); } } } and my heapify function is : void heapify(size_t index) { auto previous_index = index; do { previous_index = index; auto largest = getLargestFromParentAndHisChildren(index); if (index != largest) { std::swap(table[index], table[largest]); index = largest; } } while (index != previous_index); }
Your loop starts at the wrong value. It should be: for (int i = (asize - 1) / 2; i >= 0; i--) Not your question, but: calling heapify is not the fastest way to bubble a value up, since that function needs to check also the sibling value, which is unnecessary. i-- will make this loop O(n), which is not the complexity you would want for a heap. This operation should be O(logn), and so i should jump from child to parent, in each iteration. Moreover, when the previous point is implemented, this loop could exit when no more swap occurs.
72,494,915
72,495,027
How do you get the component of a vector in the direction of a ray
I have an object moving in the direction of vector A. There's another vector B which points in an arbitrary direction (but can be considered an infinite line) I want to get vector C, which is a vector in the direction of B, but with the magnitude of the A's component in the direction of B. To illustrate, if vector A was Vector(1,.5,0) and vector B was Vector(0,1,0) Then my vector C would be Vector(0,.5,0). Easy enough if B is aligned on an axis, but how can I do this if B is something like (6,3,8)?
Let C = normalize(B). (divide B by its length) Then dot(A, C) gives you the length of the desired vector, and dot(A, C) * C is the vector itself.
72,495,247
72,495,489
Implementing Game Outcomes with While Loop: Turn-based Dueling Game
Background I'm making a turn-based dueling game against a computer. Right now, I'm trying to get the barebones of the game to work without player input. After each turn (one action by the player or computer) one of four possibilities can happen: Player lives and computer lives Player lives and computer dies Player dies and computer lives Player dies and computer dies (ex: player's attack damages the player too. Haven't done anything with that yet) Problem I can't figure out how to make the program stop when possibilities 2,3, or 4 happen. Right now, the entire thing runs and the player and computer die, even when the player should live with my current code. Code Here's a minimum working example of my current efforts. I know I'm doing something dumb, but I just can't pinpoint it. Any suggestions/pointers would be greatly appreciated! #include <iostream> class Player { private: int m_hp {}; int m_action {}; public: Player(int hp = 5): m_hp{hp} { } int attack(const int& attackDamage) { return attackDamage; } int getHP() const // const because getHP shouldn't alter hp { return m_hp; } void takeHP(int damage) { m_hp = m_hp - damage; } void giveHP(int healing) { m_hp = m_hp + healing; } }; class Computer { private: int m_hp {}; public: Computer(int hp = 5): m_hp{hp} { } int attack(const int& attackDamage) { return attackDamage; } int getHP() const // const because getHP shouldn't alter hp { return m_hp; } void takeHP(int damage) { m_hp = m_hp - damage; } void giveHP(int healing) { m_hp = m_hp + healing; } }; int healthCheck(Player& player, Computer& computer) { if (player.getHP() > 0 && computer.getHP() > 0) { return 1; } else if (player.getHP() > 0 && computer.getHP() <= 0) { return 2; } else if (player.getHP() <= 0 && computer.getHP() > 0) { return 3; } else if (player.getHP() <= 0 && computer.getHP() <= 0) { return 4; } else { return 0; } } int gameStatus(int healthCheck, Player& player, Computer& computer) { switch(healthCheck) { case 1: std::cout << "The battle continues." << "\n"; std::cout << "Player HP: " << player.getHP() << "\n"; std::cout << "Computer HP: " << computer.getHP() << "\n"; return 1; break; case 2: std::cout << "The monster has been slain"; // add looting function here in future // Will add money to player object here with addmoney() return 2; break; case 3: std::cout << "The player has been slain"; return 3; break; case 4: std::cout << "Both duelers have been slain"; return 4; break; default: std::cout << "error: received an int not 1,2,3,4"; return 5; break; } } void playerTurn(Player& player, Computer& computer) { computer.takeHP(1); } void computerTurn(Player& player, Computer& computer) { player.takeHP(1); } int main() { // initialize player and computer Player player {}; Computer computer {}; int gameCondition{1}; // game should continue while the player is still alive while(gameStatus(gameCondition, player, computer) == 1) { playerTurn(player, computer); // attempt at checking the game status after each turn gameCondition = healthCheck(player,computer); gameStatus(gameCondition, player, computer); computerTurn(player, computer); gameCondition = healthCheck(player,computer); gameStatus(gameCondition, player, computer); } std::cout << "The battle is over" << "\n"; return 0; }
you only test the status at the top of the loop, do this if you want to exit immediately // game should continue while the player is still alive while(gameStatus(gameCondition, player, computer) == 1) { playerTurn(player, computer); // attempt at checking the game status after each turn gameCondition = healthCheck(player,computer); if(gameStatus(gameCondition, player, computer) != 1) <<<<===== break; computerTurn(player, computer); gameCondition = healthCheck(player,computer); // test not needed here since its tested at the start of the loop gameStatus(gameCondition, player, computer); }
72,495,369
72,495,428
Build a generic `map` like function in cpp
Consider template <typename S, typename T, typename F> vector<T> map(const vector<S> &ss, F f){ vector<T> ts; ts.reserve(ss.size()); std::transform(ss.begin(), ss.end(), std::back_inserter(ts), f); return ts; } int main(){ vector<int> is = {...}; vector<double> ts = map(is, [](int i){return 1.2*i;}); } because the compiler 'couldn't deduce template parameter T'. Specifying map of type template <typename S, typename T> vector<T> map(const vector<S> &ss, std::function<T(S)> f) also doesn't work, because it doesn't match lambdas. What's the correct way?
Something like this: template <typename S, typename F> auto map(const std::vector<S> &ss, F f) -> std::vector<std::decay_t<decltype(f(ss[0]))>> { std::vector<std::decay_t<decltype(f(ss[0]))>> ts; ts.reserve(ss.size()); std::transform(ss.begin(), ss.end(), std::back_inserter(ts), std::move(f)); return ts; } I've opted for a trailing return type, to be able to use f and ss in decltype. You could just use auto return type, but explicitly specifying the type makes the function SFINAE-friendly. Or, a slightly overengineered version with hottest C++20 features: template < template <typename...> typename C = std::vector, typename S, typename F > [[nodiscard]] C<std::decay_t<std::indirect_result_t<F, std::ranges::iterator_t<S>>>> map(S &&ss, F f) { C<std::decay_t<std::indirect_result_t<F, std::ranges::iterator_t<S>>>> ts; ts.reserve(std::ranges::size(ss)); std::ranges::transform(ss, std::back_inserter(ts), std::move(f)); return ts; }
72,495,509
72,495,555
Filling the array horizontally alternately C++
I'm trying to fill the array horizontally alternately such as: My default ArrayFill function is : void fillArray(std::array<std::array<int, maxColumns>, maxRows> & array, size_t rows, size_t columns) { if (rows == 0 || rows > maxRows || columns == 0 || columns > maxColumns) throw std::invalid_argument("Invalid array size."); int value = 1; for (size_t row = 0; row < rows; ++row) for (size_t column = 0; column < columns; ++column) array[row][column] = value++; } How can I change the implementation that will fill the array horizontally? UPDATE - I tried the suggested solution and here is the result: -- FINAL -- ( IT WORKS PERFECTLY )
there are two properties which you should obey: start filling not from top (row=0) but bottom (row=rows-1) each row (from bottom to top) changes the order of columns so, finally it can look like this: int value = 1; int colOrder = 1; // 1 means from left to right, 0 from right to left for (size_t row = 0; row < rows; ++row) { for (size_t column = 0; column < columns; ++column) array[rows - 1 - row][colOrder ? column : (columns - 1 - column)] = value++; colOrder ^= 1; // change column order }
72,496,216
72,496,296
Builder patterns with vectors evaluated at compile time (with `consteval`)
I am attempting to create a class that follows the builder pattern and also runs completely at compile time (with the use of the new consteval keyword in C++20), but whatever I try doesn't work. For example, this won't work: #include <vector> class MyClass { private: std::vector<int> data; public: consteval MyClass& setData() { this->data = {20}; return *this; } consteval std::vector<int> build() { return data; } }; int main() { std::vector<int> data = MyClass().setData().build(); } Which gives the error "<anonymous> is not a constant expression". This led me to believe I should instead return copies of the class instead: #include <vector> class MyClass { private: std::vector<int> data; public: consteval MyClass setData() { // https://herbsutter.com/2013/04/05/complex-initialization-for-a-const-variable/ return [&]{ MyClass newClass; newClass.data = {20}; return newClass; }(); } consteval std::vector<int> build() { return data; } }; int main() { std::vector<int> data = MyClass().setData().build(); } Yet, I got the same error. How should I use a constant-time builder pattern in C++? It seems this only occurs with vectors, and I am using a version which supports C++20 constexpr vectors.
Your code does not compile because current C++ only permits "transient" allocation in constant expressions. That means that during constant expression evaluation, it is permitted to dynamically allocate memory (since C++20) but only under the condition that any such allocations are deallocated by the time the constant expression is "over". In your code, the expression MyClass().setData() must be a constant expression because it is an immediate invocation (which means a call to a consteval function, other than one that occurs inside another consteval function or inside an if consteval block). The expression MyClass().setData().build() also must be a constant expression. This implies that, while MyClass().setData().build() is being evaluated, dynamic allocations are permitted, but there must be no "surviving" allocations at the end of MyClass().setData() nor at the end of MyClass().setData().build(). Since there is no way to prevent the result of MyClass().setData() from having a live allocation, you must only call it inside an enclosing consteval function or if consteval block. For example, the following will be valid: consteval int foo() { return MyClass().setData().build()[0]; } Notice that the temporary MyClass object (and thus the std::vector<int> subobject) will be destroyed, and all dynamic allocations will therefore be cleaned up, just before foo() returns. You want to keep the vector around after the outermost consteval function completes? Sorry, you can't do that---not in the current version of C++, at least. You need to copy its content into a std::array or some other kind of object that doesn't use dynamic allocation.
72,496,693
72,496,729
Why is my code with chars messing up a counting variable?
This is Arduino code, but I have a feeling my error is with C++ in general and not specific to Arduino. I'm new to pointers and strings, so I probably am doing something wrong in that regard. This is from a much larger program, but I've whittled it down to as little code as I can where I can still reproduce the bug. It should just iterate through the letters of text[] and save each letter into newText[0][0], as well as print newText[0][0] and the counter variable i. void setup() { Serial.begin(9600); } void loop() { const char text[] = "chunk"; static char newText[][10] = {}; static unsigned int i=0; static int code = 0; if(code == 0){ newText[0][0] = text[i]; //This Serial.print(i); Serial.println(newText[0][0]); //This i++; if(i>=strlen(text)){ code=1; } } } But as I have the code, i jumps to some number like 104 by the second iteration, when it should be equal to 1. (The exact value varies depending on how exactly the code looks.) If I comment out either of the lines that have the comment //This, then the counter works fine. Also, if I switch Serial.print(i); and the line before it, then it counts fine.
static char newText[][10] = {}; This creates a zero sized array (to be more precise a matrix of 0 rows and 10 columns). This would be illegal in C++ but gcc has an extension to allow it. Nevertheless even with gcc's extension, it's UB when you access newText[0][0] which is outside the size of the array. When you have UB anything can happen, the program can appear to work as you expect, it can print gibberish, it can crash, etc., literally anything. So you need to declare a size that accommodates all your accesses, e.g.: static char newText[1][10] = {}; if you only want 1 row (but in this case you don't need a matrix, a one dimension array would do fine). Tip: use the String class for strings instead of raw arrays.
72,496,829
72,496,834
Changing the value of a const variable using pointer in C++
Run the code below: #include <iostream> int main() { const int NUM = 1; int *p = (int *)&NUM; *p = 2; std::cout << *p << "\n"; std::cout << NUM << "\n"; return 0; } The output of the program above is: 2 1 The expected output was: 2 2 Can anyone please explain why the value of NUM is 1? The same can be tested with https://www.onlinegdb.com/
A const is a read-only value. You are trying to do something that is not allowed so you should have Undefined behaviours like this one.
72,497,582
72,497,938
Couldn't deduce template paramter even if it is known at compile time
I have a variadic template class SomeClass that looks like this (basically): template<std::size_t SIZE_> class SomeClass { public: static constexpr std::size_t SIZE = SIZE_; }; It has a constexpr member that simply contains the std::size_t template parameter used to instantiate it. I want a constexpr function that can sum all the sizes of SomeClass<SIZE_> specializatins. My first idea was to make a simple variadic template function that adds all the SIZEs like that: template<typename T> constexpr std::size_t totalSize() { return T::SIZE; } template <typename T, typename... Ts> constexpr std::size_t totalSize() { return totalSize<T>() + totalSize<Ts...>(); } Now I try to call it: constexpr std::size_t size = totalSize<SomeClass<1>, SomeClass<2>, SomeClass<3>>() // should return 6 It turns at that the last parameter unpacking makes call to totalSize<T> function ambiguous because both template totalSize functions match it. Fine, I modified my code to have two distinct functions and came up with this: template<typename T> constexpr std::size_t totalSizeSingle() { return T::SIZE; } template <typename T, typename... Ts> constexpr std::size_t totalSize() { std::size_t result = totalSizeSingle<T>(); if (sizeof...(Ts) > 0) result += totalSize<Ts...>(); return result; } Again, the last unpacking seem to be problematic. Apparently, T can't be deduced even though it is known at compile time. I get the following error (compiling with GCC): In instantiation of 'constexpr std::size_t totalSize() [with T = SomeClass<3>; Ts = {}; std::size_t = long long unsigned int]': main.cpp:129:51: required from here main.cpp:134:82: in 'constexpr' expansion of 'totalSize<SomeClass<1>, SomeClass<2>, SomeClass<3> >()' main.cpp:129:51: in 'constexpr' expansion of 'totalSize<SomeClass<2>, SomeClass<3> >()' main.cpp:129:58: error: no matching function for call to 'totalSize<>()' 129 | if (sizeof...(Ts) > 0) result += totalSize<Ts...>(); | ~~~~~~~~~~~~~~~~^~ main.cpp:127:23: note: candidate: 'template<class T, class ... Ts> constexpr std::size_t totalSize()' 127 | constexpr std::size_t totalSize() { | ^~~~~~~~~ main.cpp:127:23: note: template argument deduction/substitution failed: main.cpp:129:58: note: couldn't deduce template parameter 'T' 129 | if (sizeof...(Ts) > 0) result += totalSize<Ts...>(); | ~~~~~~~~~~~~~~~~^~ I don't really understand why it is not working. Every type is know at compile time. Why is this happening and how can I get it to work? I'm using C++11.
There's a reason people call structs metafunctions in c++ template metaprogramming. In our case the major advantage of doing metaprogramming in a struct is that resolving function overloading by template arguments is different and more limited than that of class specialisation. So I suggest: template <class ...> // only called if there's no arguments struct add_sizes { static constexpr auto value = 0; }; template <class T, class ... Ts> struct add_sizes <T, Ts...> { static constexpr auto value = T::SIZE + add_sizes<Ts...>::value; }; // then wrap it into your function: template <class ... Ts> constexpr std::size_t totalSize () { return add_sizes<Ts...>::value; } demo Another advantage of using structs is for easy "return" of multiple values or types, which for functions gets complicated. Sometimes by calculating A you've already calculated B, so it can make sense to store both. In general I'd say that if you're ever struggling solving a metaprogramming problem with functions, switch to structs.
72,497,636
72,497,811
Getting class' method address
I'm asking you to help me understand this concept. Maybe I don't understand something, I don't know.. So I have this sample code: #include <iostream> class X{ int a; public: void do_lengthy_work(); }; void X::do_lengthy_work(){ std::cout << a << std::endl; } int main(){ X my_x; printf("%p\n", &X::do_lengthy_work); // -> does compile printf("%p\n", &my_x.do_lengthy_work); // -> doesn't compile, // error: ISO C++ forbids taking the address of a bound member function to // form a pointer to member function. Say &X::do_lengthy_work } I saw this sample of code in one book. I thought that we can't get an address of a class' method unless there's an object specified from which we want to get that function's address. But it turns out we can only get a class' method address, but not object's method address. I thought everytime we declare an object of a class, it gets it's own method, with separate address. Also if we do something like this: #include <iostream> class X{ int a; public: void do_lengthy_work(); int b; }; void X::do_lengthy_work(){ std::cout << a << std::endl; } int main(){ X my_x; printf("%p\n", &X::do_lengthy_work); printf("%p\n",&X::b); printf("%p",&my_x.b); } Example output is: 0x562446a9c17a 0x4 0x7ffe7491a4cc Both class method's and object's variable address change. But the b's variable address does not change. It's always 0x4, 4 bytes further away from 0x00 because it's an int variable. But why it's address is so close to 0x00, but function's address is so further away? Also - repeating my question from previous code sample - why can't we get an address of a bound member function, but we can of a class' method? So for example we can do this: &X::method but not this: &object.method I started thinking - can you correct me if I'm right? - variables from a class are initialized once when class is declared (thus we see an address of 0x4 when printing out an address of X::b), and then (uniquely) every other time we specify new object (thus we see 0x7ffe7491a4cc when printing out an address of my_x.b), but methods are initialized only once and every object uses the same method which is always on the same address?
You can basically think of X as being implemented something like this: struct X{ int a; int b; }; void X__do_lengthy_work(X* this); Methods are pretty much the same as a normal function just with the addition of a hidden parameter of a pointer to the instance of the class. Each instance of a class uses the same methods. It could be misleading to take a pointer to a method for a particular instance as that might imply that you could call that method without having to provide the instance which is I guess why the language doesn't allow you to do that.
72,497,910
72,498,394
why was invalid substitution of class template deriving template arguments in alias declaration not resulting in error
I have tested these several templates to show the validity of the template instantiation: template <typename T> using LRef = T&; template <typename T> using Ptr = T*; template <typename> requires false class A {}; // ... using T0 = LRef<int>; // expected ok // using T1 = LRef<void>; // expected error, forming void& which is invalid using T2 = Ptr<void>; // expected ok // using T3 = Ptr<int&>; // expected error, forming int& * which is invalid // using T4 = A<int>; // expected error, unsatisfied constraint resulting in invalid instantiation However, template <typename T> struct Box { T value; }; template <typename T, typename U = T> struct Derive : T, U {}; // ... using T5 = Derive<int, float>; // unexpected no-error, but should be invalid // template struct Derive<int, float>; // expected error using T6 = Derive<Box<int>, Box<float>>; // expected ok template struct Derive<Box<int>, Box<float>>; // expected ok using T7 = Derive<Box<int>>; // unexpected no-error, but should be invalid // template struct Derive<Box<int>>; // expected error void foo() { // T5 {}; // error // T7 {}; // error } type alias declarations of T5 and T7 have no error, which are unexpected. I suppose that they should be invalid since the explicit instantiation with the same template arguments and the usage of type alias has errors. Is this the correct behavior in standard C++ or just not implemented properly? These 3 major compilers (GCC, Clang, and MSVC) show no compilation error with this program. https://godbolt.org/z/hcbszo49a
Is this valid in standard C++ or just not implemented properly? The second snippet without the use of T5{}; and T7{}; is well-formed. This is because typedefs, using and do not require a completely defined type. And from implicit instantiation's documentation: When code refers to a template in context that requires a completely defined type, or when the completeness of the type affects the code, and this particular type has not been explicitly instantiated, implicit instantiation occurs. For example, when an object of this type is constructed, but not when a pointer to this type is constructed. (emphasis mine) And as type alias doesn't require a completely defined type, according to the above quoted statement there will be no implicit instantiation for a typedef or using. For example: template<typename T> struct C{ T& k;}; using V = C<void>; //no implicit instantiation int main() { C<int>* k;//no implicit instantiation C<void>* l; //no implicit instantiation }; Demo They should be invalid since the explicit instantiation with the same template arguments and the usage of type alias has errors. Note in first snippet where you use an alias template instead of a class template, all compilers seem to produce the error(Demo) you mentioned but this is because they are allowed(but not required) to do so as also explained in Template class compiles with C++17 but not with C++20 if unused function can't be compiled.
72,497,912
72,497,949
Why getting runtime-error even after declaring size of vector?
I am solving leetcode problem : https://leetcode.com/problems/number-of-islands/ It gives me this error: Char 34: runtime error: addition of unsigned offset to 0x6080000000a0 overflowed to 0x60800000008c (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34 My code: class Solution { public: void bfs(vector<int>&visited,vector<vector<char>>& grid,int r,int c,int n,int m) { queue<pair<int,int>>q; q.push({r,c}); int dx[4]={1,-1,0,0}; int dy[4]={0,0,1,-1}; visited[r*m+c]=1; while(!q.empty()) { int x=q.front().first; int y=q.front().second; q.pop(); for(int i=0;i<4;i++) { int newX=x+dx[i]; int newY=y+dy[i]; if(newX<n && newY<m && visited[newX*m+newY]==-1 && grid[newX][newY]=='1') { q.push({newX,newY}); visited[newX*m+newY]=1; } } } } int numIslands(vector<vector<char>>& grid) { int n=grid.size(); int m=grid[0].size(); vector<int>visited(n*m+1,-1); int cnt=0; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(visited[i*m+j]==-1 && grid[i][j]=='1') { bfs(visited,grid,i,j,n,m); cnt++; } } } return cnt; } }; I have used the BFS algorithm here. I have declared sizes of all vectors to prevent out of bounds error, still its occuring.
In this line: if(newX<n && newY<m && visited[newX*m+newY]==-1 && grid[newX][newY]=='1') You never check if newX or newY are less than 0. If so, accessing grid[newX][newY] could give a runtime error. Just add two conditions, as shown below: if(newX<n && newY<m && newX >= 0 && newY >= 0 && visited[newX*m+newY]==-1 && grid[newX][newY]=='1')
72,498,003
72,498,880
C++ Program with matrix class ending abruptly
I am writing a matrix class where I need to perform some matrix calculations in the main program. I am not sure why the program is ending abruptly when user chooses a matrix of size more than 2x2 matrix. The std::cin works fine until two rows but program ends after the loop reaches third row. Only part of the code is shown below which is related to my question. #include<iostream> #include <vector> #include <cassert> using std::vector; using namespace std; class Matrix { private: int rows; int cols; int **vtr; public: Matrix(int m = 2, int n = 2) { rows = m; cols = n; vtr = new int*[m]; for (int i = 0; i < m; i++) { vtr[i] = new int [n]; } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { vtr[i][j] = 0; } } } void read() { cout << "Enter the number of rows and columns of Matrix separated by a space: "; cin >> rows >> cols; Matrix a(rows, cols); a.write(); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { cout << "(" << i << "," << j << ") : "; cin >>vtr[i][j]; } } } void write() { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { cout << vtr[i][j] << " "; } cout << endl; } cout << endl << endl; } }; int main() { Matrix A, B, C; int row, column ; cout << "For Matrix A" << endl; A.read(); cout << "For Matrix B " << endl; B.read(); cout << "For Matrix C" << endl; C.read(); }
Since the 2D array, vtr is created when declaring the Matrix object, you can move the vtr creation after reading the console input like below. Matrix(int m = 2, int n = 2) { /*rows = m; cols = n; vtr = new int*[m]; for (int i = 0; i < m; i++) { vtr[i] = new int [n]; } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { vtr[i][j] = 0; } }*/ } void read() { cout << "Enter the number of rows and columns of Matrix separated by a space: "; cin >> rows >> cols; vtr = new int*[rows]; for (int i = 0; i < rows; i++) { vtr[i] = new int [cols]; } //Matrix a(rows, cols); //write(); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { cout << "(" << i << "," << j << ") : "; cin >>vtr[i][j]; } } write(); //Prints the array }
72,498,346
72,498,391
Question about linking compute shader program in OpenGL
I'm trying to create a single compute a shader program computeProgram and attach two source codes on it. Here are my codes: unsigned int computeProgram = glCreateProgram(); glAttachShader(computeProgram, MyFirstComputeShaderSourceCode); glAttachShader(computeProgram, MySecondComputeShaderSourceCode); glLinkProgram(computeProgram); glGetProgramiv(computeProgram, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(computeProgram, 512, NULL, infoLog); std::cout << "ERROR::SHADER::COMPUTE_PROGRAM::LINKING_FAILED\n" << infoLog << std::endl; exit(1); } I get this type of linking error information: ERROR::SHADER::COMPUTE_PROGRAM::LINKING_FAILED ERROR: Duplicate function definitions for "main"; prototype: "main()" found. I do have main functions in both shader source codes, and I understand why this is not gonna work cause there is only one main function expected in one program. But here comes my question: If I'm trying to link a vertex shader source and a fragment shader source to a single program, say, renderProgram, there are also two main functions, one in vertex shader, one in fragment shader. However, if I link these two, it somehow works fine. Why is this difference happen? And if I want to use these two compute shaders, am I supposed to create two compute programs in order to avoid duplication of the main function? Any help is appreciated!!
Why is this difference happen? When you link a vertex shader and a fragment shader to the same shader program, then those two (as their names imply) are in different shader stages. Every shader stage expects exactly one definition of the main() function. When you attach two shaders that are in the same shader stage, such as your two compute shader objects, then those get linked into the same shader stage (compute). And that does not work. And if I want to use these two compute shaders, am I supposed to create two compute programs in order to avoid duplication of the main function? Yes. When you have two compute shaders that each define their own functionality in terms of a main() function, then creating two shader programs each with one of the shader objects linked to it would work. Especially, when your two shaders have completely different interfaces with the host, such as SSBOs or samplers/images.
72,498,843
72,498,942
C++ doesn't display array values
My code doesn't display array values that I input, instead it only prints zero. It supposed to print the values if I choose case 2 after completing the case 1. My code doesn't display array values that I input, instead it only prints zero. It supposed to print the values if I choose case 2 after completing the case 1. #include <iostream> using namespace std; int main(){ string candidate[4]; int a[5], b[5], c[5], d[5];//precint int total; int choice; char yesNo; int i; do{ cout<<"[1] Enter candidates names and votes"<<endl; cout<<"[2] Show Tally"<<endl; cout<<"[3] Exit"<<endl; cout<<"Enter a choice: "; cin>>choice; switch(choice){ case(1): for(int i=0; i<4; i++){ cout<<"Enter candidate names: "; cin>>candidate[i];} for(int i=0; i<5; i++){ cout<<"Candidate "<<candidate[0]<<" precinct "<<i+1<<" votes: "; cin>>a[i]; } for(int i=0; i<5; i++){ cout<<"Candidate "<<candidate[1]<<" precinct "<<i+1<<" votes: "; cin>>b[i]; } for(int i=0; i<5; i++){ cout<<"Candidate "<<candidate[2]<<" precinct "<<i+1<<" votes: "; cin>>c[i]; } for(int i=0; i<5; i++){ cout<<"Candidate "<<candidate[3]<<" precinct "<<i+1<<" votes: "; cin>>d[i]; } break; case(2): cout<<"Precinct\tCandidate: "<<candidate[0]<<"\tCandidate: "<<candidate[1]<<"\tCandidate: "<<candidate[2]<<"\tCandidate: "<<candidate[3]<<endl; for(int j=1; j<6;j++) cout<<j<<"\t\t"<<a[i]<<"\t\t"<<b[i]<<"\t\t"<<c[i]<<"\t\t"<<d[i]<<endl; break; } cout<<"Do you want to continue(Y/N): "; cin>>yesNo; }while (yesNo == 'y' || yesNo == 'Y'); cout<<"Thank You!"; return 0; }
There is a mismatch between the variable used in the for loop vs variable used to print the values. case(2): cout<<"Precinct\tCandidate: "<<candidate[0]<<"\tCandidate: "<<candidate[1]<<"\tCandidate: "<<candidate[2]<<"\tCandidate: "<<candidate[3]<<endl; for(int i=0; i<5;i++) cout << i+1 << "\t\t" << a[i] << "\t\t" << b[i] << "\t\t" << c[i] << "\t\t"<< d[i] << endl;
72,499,077
72,499,516
3 dimensional vector in c++
i want to store a vector of objects for a node and subset of set. so I want to implement a 3 d vector where the first dimension has size #nodes = n and the second dimension has size 2^|set| = m. the last dimension shouldn't have fixed size, because I want to append new objects in my program. vector< vector < vector<Object>>> Vector3d( n , ( m, ( ( ???))) what should I write instead of ??? i have tried to use arrays inside of a vector, but I didn't succeed that way. thank you in advance
The method of initialisation is vector< vector < vector<Object>>> Vector3d(n,vector<vector<Object>(m)) This will work, as it will initialize the first dimension's size as n, which would contain n no of vector<vector<Object>(m) which is the default value. Now the size of the second dimension is defined as m, which has no initial value, hence you can append any vector to the second dimension space. i.e. vector<Object> v; Vector3d[i][j].push_back(v); where i and j are the indexes of the first 2 dimensions
72,499,080
72,499,106
Accessing Enum defined within a class C++
I have the following code: // Piece.h class Piece { public: enum class Color {BLACK, WHITE}; Piece(); Piece(int x, int y, Piece::Color color); private: int m_x; int m_y; Piece::Color m_color; static const int UNINITIALIZED = -1; }; How do I access the enum from the method functions: (attempt) // Piece.cpp Piece::Piece() : m_x(Piece::UNINITIALIZED), m_y(Piece::UNINITIALIZED), m_color(Piece::Color BLACK) // PROBLEM {} Piece::Piece(int x, int y, Piece::Color color) : m_x(x), m_y(y), m_color(color) {} The Problem: Piece.cpp: In constructor ‘Piece::Piece()’: Piece.cpp:8:24: error: expected primary-expression before ‘BLACK’ 8 | m_color(Piece::Color BLACK) I'm new to C++ so this might not be good code practice, but I would generally like to know how to achieve this (and also understand why I shouldn't write like this, if it is in fact bad practice) Thank you
You access enum (class) members like you would access any static member. Piece::Color::BLACK in this case. In the constructor, you could omit the "Piece" part and just write the following: Piece::Piece() : m_x(UNINITIALIZED), m_y(UNINITIALIZED), m_color(Color::BLACK) {} Regarding your hint about this being bad practice: It isn't. You could probably change the int to be a constexpr instead of just const, but whatever you are trying to do with the enum value is totally fine.
72,499,201
72,499,562
define / use a Macro inside a fcuntion - good style/practice?
I folks, I have a question for the C/C++ Syntax / Coding-Style Gurus out there: The situation: I am working on an STM32 Microcontroller and in some functions I have to do a lot of bit shifting, logical operations (and, or, xor) on bits, set/clear bits and writing / reading this code is really painfull. An example: lets asume I had to turn an device on with a digital Output, and I have 5 sensors to check, where each of the sensors has its own dedicated digital Input. Some of them need to be TRUE, others need to be FALSE A (Pseudo-)Code would eventually look like this: Note: this code is obviously nonsense/nothing really functional, it's just for explaining the principle. #define SENSOR1 0 #define SENSOR2 1 #define SENSOR3 2 #define SENSOR4 3 #define SENSOR5 4 void DeviceOn(void) { uint8_t DIOPort = ReadDIOPort(); if((DIOPort & (1 << SENSOR1)) && (!(DIOPort & (1 << SENSOR2))) && (DIOPort & (1 << SENSOR3))) { turnOnDevice(); } else { turnOffDevice(); } } As you see, the if-condition becomes pretty ugly and if there are more signals involved it becomes more and more unreadable. My idea was to define macros inside the function, only used by / within that function, to make the code more readable. This would look like this. void DeviceOn(void) { #define __POWER_ISOK (DIOPort & (1 << SENSOR1)) #define __SAFETY_ISOK (!(DIOPort & (1 << SENSOR2))) #define __LIGHT_ISON (DIOPort & (1 << SENSOR3)) #define __COFFEEMUG_ISFULL (DIOPort & (1 << SENSOR4)) uint8_t DIOPort = ReadDIOPort(); if(__POWER_ISOK && __SAFETY_ISOK && __LIGHT_ISON && __COFFEEMUG_ISFULL) { turnOnDevice(); } else { turnOffDevice(); } } IMHO the if-condition is much more readable as the first example. The question is: is this considered to be "good coding style" or is that an absoulte no-go and other developers will start to avoid me and consider me to be the worst coder in the whole universe? I want the macros to be defined within the function, because they are ONLY used in this one function, and it makes documentation easier: the one who has to read this code just has to scroll up to the start of the function and does not have to search in the C-File or even the Header-File for the definition. The Definitions of the bits in the Digital Input Status Variable are defined gobally (at the beginning of the C-File) as they are used in other functions, too. Of course I'd define any macros gobally, that are used in multiple functions. Of course I could also define all macros gobally, but I think that it makes the code more readable, if those who are used only in one function, are defined in that function. Technically I don't see any issues, as the preprocessor should replace the macros in the build process, or am I wrong?
Alternate solution: #include <stdbool.h> void DeviceOn(void) { uint8_t DIOPort = ReadDIOPort(); bool PowerIsOK = DIOPort & 1 << SENSOR1; bool SafetyIsOK = ! (DIOPort & 1 << SENSOR2); bool LightIsOn = DIOPort & 1 << SENSOR3; bool CoffeeMugIsFull = DIOPort & 1 << SENSOR4; if (PowerISOK && SafetyIsOK && LightIsOn && CoffeeMugIsFull) turnOnDevice(); else turnOffDevice(); }
72,499,298
72,499,380
C++ wrong calculation and no percentage showing
The calculation is only right in a and c, it is very wrong on b and c is off by 1. And the percentage only shows zero. Although the formulas is the same I can't figure out why the two is wrong, And why the percentage only shows zero and doesn't follow my formula. Here the output enter image description here And here is my code #include <iostream> using namespace std; int main(){ string candidate[4]; int a[5], b[5], c[5], d[5];//precint int at,bt,ct,dt; int ap, bp, cp, dp; int total; int choice; char yesNo; int i; do{ cout<<"[1] Enter candidates names and votes"<<endl; cout<<"[2] Show Tally"<<endl; cout<<"[3] Exit"<<endl; cout<<"Enter a choice: "; cin>>choice; switch(choice){ case(1): for(int i=0; i<4; i++){ cout<<"Enter candidate names: "; cin>>candidate[i];} for(int i=0; i<5; i++){ cout<<"Candidate "<<candidate[0]<<" precinct "<<i+1<<" votes: "; cin>>a[i]; } for(int i=0; i<5; i++){ cout<<"Candidate "<<candidate[1]<<" precinct "<<i+1<<" votes: "; cin>>b[i]; } for(int i=0; i<5; i++){ cout<<"Candidate "<<candidate[2]<<" precinct "<<i+1<<" votes: "; cin>>c[i]; } for(int i=0; i<5; i++){ cout<<"Candidate "<<candidate[3]<<" precinct "<<i+1<<" votes: "; cin>>d[i]; } break; case(2): cout<<"Precinct\t"<<candidate[0]<<"\t\t"<<candidate[1]<<"\t\t"<<candidate[2]<<"\t\t"<<candidate[3]<<endl; for(int i=0; i<5; i++){ //for displaying the tally cout<<i+1<<"\t\t"<<a[i]<<"\t\t"<<b[i]<<"\t\t"<<c[i]<<"\t\t"<<d[i]<<endl; } cout<<endl; for(int i=0; i<5; i++){ //for the total votes at=at+a[i]; bt=bt+b[i]; ct=ct+c[i]; dt=dt+d[i]; } total=at+bt+ct+dt; //for the percent ap=(at/total)*100; bp=(bt/total)*100; cp=(ct/total)*100; dp=(dt/total)*100; cout<<"Candidate "<<candidate[0]<<" total votes and percentage: "<<at<<" votes. "<<ap<<"%"<<endl; cout<<"Candidate "<<candidate[1]<<" total votes and percentage: "<<bt<<" votes. "<<ap<<"%"<<endl; cout<<"Candidate "<<candidate[2]<<" total votes and percentage: "<<ct<<" votes. "<<ap<<"%"<<endl; cout<<"Candidate "<<candidate[3]<<" total votes and percentage: "<<dt<<" votes. "<<ap<<"%"<<endl; break; } cout<<"Do you want to continue(Y/N): "; cin>>yesNo; }while (yesNo == 'y' || yesNo == 'Y'); cout<<"Thank You!"; return 0; }
Use double instead of int to represent the variables that are used to store the percentages. Initialize the variables that are used to store the totals. You can find more about double conversion here. How to convert integer to double implicitly? And you are printing the same percentage value i.e. ap for all the candidates. int at = 0, bt = 0, ct = 0, dt = 0; double ap, bp, cp, dp; //Rest of the code ap = ((double)at / total) * 100; bp = ((double)bt / total) * 100; cp = ((double)ct / total) * 100; dp = ((double)dt / total) * 100;
72,499,538
72,502,221
Understanding clang-tidy "DeadStores" and "NewDeleteLeaks" warnings
I am relatively new to c++ programming, especially when dealing with OOP and pointers. I am trying to implement a binary search tree, and here is the code I have struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode() : val(0), left(NULL), right(NULL){}; TreeNode(int v) : val(v), left(NULL), right(NULL){}; TreeNode(int v, TreeNode* l, TreeNode* r) : val(v), left(l), right(r){}; }; void insert(TreeNode* root, TreeNode* v) { // inserts v into root, assuming values distinct if (root == NULL) { root = v; // L52 return; } if (v == NULL) { return; } // traverse through tree using structure of BST TreeNode* cur = root; while (cur != NULL) { if (cur->val <= v->val) { if (cur->right == NULL) { cur->right = new TreeNode(v->val); break; } cur = cur->right; } else if (cur->val >= v->val) { if (cur->left == NULL) { cur->left = new TreeNode(v->val); break; } cur = cur->left; } } } void insert(TreeNode* root, int v) { insert(root, new TreeNode(v)); // L78 } Now, I have two questions. I realised that the L52 labelled above would not work. For example, if I do TreeNode* node = new TreeNode(5); TreeNode* empty = NULL; insert(empty, node);, it would not work. I am not sure how to fix this, so any help would be great. Running clang-tidy on my code, I get the following slightly confusing warning: ./main.cpp:78:69: warning: Potential memory leak [clang-analyzer-cplusplus.NewDeleteLeaks] void insert(TreeNode* root, int v) { insert(root, new TreeNode(v)); } ^ ./main.cpp:132:3: note: Calling 'insert' insert(node, 3); ^ ./main.cpp:78:51: note: Memory is allocated void insert(TreeNode* root, int v) { insert(root, new TreeNode(v)); } ^ ./main.cpp:78:69: note: Potential memory leak void insert(TreeNode* root, int v) { insert(root, new TreeNode(v)); } ^ I am not sure what this means, and whether it would be dangerous in any way. I found this from the LLVM docs and it seems that the temporary new TreeNode(v) is causing the problem. What is a better way to achieve what I want? Any further explanation or resources that I can read would be great. Of course, any improvement to my bad coding style would be great as well ;) formatter saves the day. Thank you!
Q1: How do I insert into a binary tree? The main problem with the fragment: void insert(TreeNode* root, TreeNode* v) { // inserts v into root, assuming values distinct if (root == NULL) { root = v; // L52 return; } is, although you have set a new value for root, root is a parameter to the insert function, and consequently is discarded when insert returns. One way to fix this is to return the new value: TreeNode* // <-- changed return type insert(TreeNode* root, TreeNode* v) { // inserts v into root, assuming values distinct if (root == NULL) { root = v; // L52 return root; // <---- changed to return a value } Every place insert returns (including at the end), return the value of root. Then when you call insert, save the returned value: TreeNode* root = ...; // some existing tree root = insert(root, 5); // insert 5 and save the result Now, the new value of root points to the tree that contains the inserted value. Q2: What is clang-tidy complaining about? Invoking new allocates memory. It must eventually be freed, otherwise (if this keeps happening) your program will eventually use all available memory. See the question When should I use the new keyword in C++?. Note especially this advice: "every time you type new, type delete." Now, in this code as it stands, the problem is actually not the missing delete, it is the failure to return the updated root. clang-tidy realizes that, because the updated root is never returned, you can't possibly eventually delete it, so complains. Once you start returning that value, clang-tidy will wait to see what you do next. As for what to do next, one simple approach is to regard TreeNode as owning its children, meaning it is obliged to delete them when it is destroyed. For example, first add a destructor method to TreeNode: struct TreeNode { ... ~TreeNode() { // <--- this is the destructor delete left; // free left child (if not NULL) delete right; // free right child } }; Then in your code that manipulates trees, remember to delete the root node when finished: TreeNode* root = NULL; root = insert(root, 1); root = insert(root, 2); delete root; // <--- free entire tree A note about smart pointers My suggestions above use a very direct, literal style of memory management, with explicit use of new and delete where needed. However, it is easy to forget to use delete, and tricky to get it right in the presence of exceptions. A commonly preferred alternative is to use smart pointers. But that's a somewhat advanced topic, so when just starting out, I recommend first getting comfortable with explicit new and delete, but keep in mind there is a better way when you're ready for it.
72,499,630
72,499,807
Chaining return-by-reference calls to access underlying data
I worked previously only with pointers and i don't know if references behave the same way in return-statements. Can I chain multiple return-by-reference methods to access data without fearing for a "dangling" reference which contains garbage? Or would the reference go out of scope before passing it to the function-call above? See the code below if this is a valid way to pass references (we assume that the indexes are all in range) struct Data { //Non-Trivial Data } class Container { public: Data& get(int index) { return m_Collection[index]; } private: Data[100] m_Collection; } class ContainerCollection { public: Data& get(int containerindex, int dataindex) { return m_Container[containerindex].get(dataindex); } private: Container[3] m_Container; }
Yes, this is a valid way of chaining references. You can chain references within functions without worrying about dangling references (which you should worry with pointers). As long as m_Container exists, the reference is available, after that it points to NULL.
72,499,700
72,499,749
Could not find a package configuration file provided by "boost_json"
While following this link to setup boost for json parsing, I am unable to find the boost json component. Link: Using boost::json static library with cmake Here's my CMakeLists.txt: cmake_minimum_required(VERSION 3.9) set (CMAKE_CXX_STANDARD 14) set( Boost_USE_STATIC_LIBS ON ) #set( Boost_USE_MULTITHREADED ON ) #set( Boost_USE_STATIC_RUNTIME OFF ) find_package( Boost REQUIRED COMPONENTS json ) if ( Boost_FOUND ) include_directories( ${Boost_INCLUDE_DIRS} ) else() message( FATAL_ERROR "Required Boost packages not found. Perhaps add -DBOOST_ROOT?" ) endif() add_executable (test main.cc) target_include_directories(test PUBLIC ${Boost_INCLUDE_DIRS}) target_link_libraries(test PUBLIC Boost::boost Boost::json) Error: CMake Error at /usr/lib/x86_64-linux-gnu/cmake/Boost-1.71.0/BoostConfig.cmake:117 (find_package): Could not find a package configuration file provided by "boost_json" (requested version 1.71.0) with any of the following names: boost_jsonConfig.cmake boost_json-config.cmake Add the installation prefix of "boost_json" to CMAKE_PREFIX_PATH or set "boost_json_DIR" to a directory containing one of the above files. If "boost_json" provides a separate development package or SDK, be sure it has been installed. Call Stack (most recent call first): /usr/lib/x86_64-linux-gnu/cmake/Boost-1.71.0/BoostConfig.cmake:182 (boost_find_component) /usr/share/cmake-3.16/Modules/FindBoost.cmake:443 (find_package) CMakeLists.txt:11 (find_package) -- Configuring incomplete, errors occurred How do I resolve this error? I did go through some of the posts describing similar issues with boost but nothing worked.
Boost JSON was introduced in version 1.75.0. It's not available in version 1.71.0. You need to install a more recent version of boost on your system. From the boost version history page (emphasis mine): Version 1.75.0 December 11th, 2020 19:50 GMT New Libraries: JSON, LEAF, PFR. Updated Libraries: Asio, Atomic, Beast, Container, Endian, Filesystem, GIL, Histogram, Interprocess, Intrusive, Log, Move, Mp11, Optional, Outcome, Polygon, Preprocessor, Rational, Signal2, System, uBLAS, VMD, Wave.
72,501,170
72,501,327
C and C++ see which compiler used for which code
Im currently working on a big project that uses C and c++ code in one project using the extern "c" keyword in my declartions. However I am unsure whether the compiler is actually doing anything with this as my output is the same when using the C keyword. Is there a way to print something to the console to show what compiler was used for a specific peice of code in my project or a way to see if something is actually being compiled in C or c++. For example I tried using std::cout << something in the c code and it almost worked, the error didnt say anything like std not found or cout not found IIRC which I found to be a bit strange. Ive tried googling this and didnt find any results. Thanks for any help! Edit. Im using G++ as my compiler and would like the code to work on other compilers. my c code should work on both c and c++ but I need it to be C as im using union type pruning. Im at work right now so I cant recall the error message exactly. I also get the same ouput changing file extention to .c. Is there a way to see if the code is being compiled as C or c++ thanks!
to answer your specific question about knowing if its a c or c++ compiler processing your code you can look for __cplusplus standard define It's common to see: #ifdef __cplusplus extern "C"{ .....
72,502,085
72,502,937
undefined reference issue with latest gcc
I have link-time error when trying to compile following code with gcc 12.1.0. With clang, msvc and older gcc it compiles as expected. template<typename T> void def() {} template<void (*foobar)() = def<int>> void bar() { foobar(); } template<typename T> void foo() { bar(); } int main() { foo<int>(); } Error: /usr/bin/ld: /tmp/cchkaKVw.o: in function `void bar<&(void def<int>())>()': > main.cpp:(.text._Z3barIXadL_Z3defIiEvvEEEvv[_Z3barIXadL_Z3defIiEvvEEEvv]+0x5): undefined reference to `void def<int>()' Is this a gcc regression or is there some problem with this code?
Reported this bug to GCC Bugzilla: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105848
72,502,150
72,503,227
Wrap an interface around a class from library
There is a class defined in a library: class fromLib{}; used as argument to invoke a method implemented within the library : method_from_lib(const fromLib& from_lib){}; I want wrap this method within an interface class Methods{ virtual invoke_method(const& genericArg) } where class genericArg is generic representation of fromLib. A simple implementation would be: class MethodImpl: public Methods { invoke_method(const genericArg& arg) { method_from_lib(arg); // this is not going to work since the argument is not an instance of `fromLib` nor convertible nor does it inherit from it. }; } In an ideal world, I would have made the class fromLib directly inherit from genericArg . However, this is not possible given that this class is from a library that I really dont want to touch. How would I achieve a wrapper around fromLib which is also an implemetation of genericArg. The motivation for this is the following: A library provides some method with the signature method_from_lib(const fromLib& from_lib){}; that we might or might not use. We potentially want to either use that method or some other implementation. If we were to use some other implementation the argument to the function would also need to change since the argument fromLib is tightly coupled to the implementation provided by the library. Therefore, providing an interface for the method itself is straightforward, however, the purpose of this question is to how we can generalize the argument fromLib into some interface. So that our interface would be like class Methods{ virtual invoke_method(const& genericArg) } When we want to implement the case with using the library, the implementation is fairly easy we just invoke the method from the library i.e. invoke_method(const TYPE& arg) { method_from_lib(arg); }; Now as you see implementing this method either requires the TYPE to be genericArg or some class that inherits from it. The problem here is that method_from_lib expects the type fromLib which we cannot directly make as a child from genericArg since that type is contained in a thirdparty library
I think you're looking for an adapter. https://refactoring.guru/design-patterns/adapter/cpp/example Usage examples: The Adapter pattern is pretty common in C++ code. It’s very often used in systems based on some legacy code. In such cases, Adapters make legacy code work with modern classes. Identification: Adapter is recognizable by a constructor which takes an instance of a different abstract/interface type. When the adapter receives a call to any of its methods, it translates parameters to the appropriate format and then directs the call to one or several methods of the wrapped object. You state you don't want to touch the fromLib class. Under the assumption that the data required by fromLib will definitely be required for the operation that is to be executed, you'll have to implement your own struct which contains the required data. This own struct can then be passed to the adapter. The adapter will then pass it on to the lib, and return the correct result. If you want to switch out the lib, you switch out the adapter to work with the new lib. The rest of your code will remain unchanged. E.g.: class fromLib{ int degrees;// You can't change this even if you'd want to use radians in your program. } struct myActualRequiredData { double radians;// Choose something here which works well within your own program. } class MethodsTarget{ virtual invoke_method(const myActualRequiredData& data); } class MethodsAdapter : public MethodsTarget{ virtual invoke_method(const myActualRequiredData& data) { fromLib myFromLib = { .degrees = radians * 360 / PI;// Or so. I currently don't care, not what your question is about. In any case, here's where you do all the work to speak the libraries language. }; method_from_lib(myFromLib); } }; MethodsAdapter adapter; adapter.invoke_method({ .radians = 0.2 }); // Oh look I found a better lib class fromLib2{ std::string degrees; } class MethodsAdapter2 : public MethodsTarget { virtual invoke_method(const myActualRequiredData& data) { fromLib2 myFromLib = { .degrees = std::string(radians * 360 / PI); }; method_from_lib(myFromLib); } } MethodsAdapter2 adapter2; adapter.invoke_method({ .radians = 0.2 }); This example shows that changing the library will lead to minimal adjustment when using the adapter pattern. Use with pointers to MethodsTarget if necessary. But usually for libs, simply having one adapter class should be enough. You won't be hotswapping anyways.
72,502,526
72,502,632
segfault with self-declared hash function
ChunkCorner.h #pragma once #include <filesystem> #include <iostream> class ChunkCorner { public: int x; int y; std::filesystem::path to_filename(); }; size_t hf(const ChunkCorner &chunk_corner); bool eq(const ChunkCorner &c1, const ChunkCorner &c2); ChunkCorner.cpp: fwiw: The hf and eq function implementation is based on the C++ Book p. 917. #include "ChunkCorner.h" using namespace std; size_t hf(const ChunkCorner &chunk_corner) { return hash<int>()(chunk_corner.x) ^ hash<int>()(chunk_corner.y); } bool eq(const ChunkCorner &c1, const ChunkCorner &c2) { return c1.x == c2.x && c1.y == c2.y; } [...] In another bit of code I use the class as follows: unordered_set<ChunkCorner, decltype(&hf), decltype(&eq)> chunks_to_load {}; ChunkCorner c {1,2}; chunks_to_load.insert(c); On the insert call I get a segfault (determined using breakpoints). I use VS Code and when I launch the program in debug mode, it jumps to the following bit on segfault in hashtable_policy.h: __hash_code _M_hash_code(const _Key& __k) const { static_assert(__is_invocable<const _H1&, const _Key&>{}, "hash function must be invocable with an argument of key type"); return _M_h1()(__k); } I am new to C++ and have trouble understanding what the issue is and I am not sure how to proceed debugging...
You need to pass the hash and equals functions to your constructor. You've declared their type in the type arguments, which is going to be a pointer to function, but you haven't passed them in. So they're likely being zero initalized, so nullptr. Using them correctly should be done like this: unordered_set<ChunkCorner, decltype(&hf), decltype(&eq)> chunks_to_load {16, hf, eq}; However, what I recommend is rewrite your Hash/Equals functions into function objects. This way, the default operations will work properly. struct MyHasher { size_t operator()(const ChunkCorner &chunk_corner) const { return hash<int>()(chunk_corner.x) ^ hash<int>()(chunk_corner.y); } }; struct MyEq { bool operator()(const ChunkCorner &c1, const ChunkCorner &c2) const { return c1.x == c2.x && c1.y == c2.y; } };
72,502,840
72,503,023
Is two-way BFS not supposed to work in this case?
I am solving a problem on LeetCode: In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform one string to the other. Input: start = "RXXLRXRXL", end = "XRLXXRRLX"; Output: true I solved it using two-way BFS like below: class Solution { public: bool canTransform(string& start, string& end) { if(start==end) return true; unordered_set<string> first{start}, last{end}, visited{start,end}; while(first.size() && last.size()) { if(first.size()>last.size()) swap(first,last); unordered_set<string> tmp; for(auto curr:first) { for(int i=1; i<curr.size(); i++) { if((curr[i-1]=='X' && curr[i]=='L') || (curr[i-1]=='R' && curr[i]=='X')) { swap(curr[i-1],curr[i]); // cout<<"Checking for: "<<curr<<"\n"; if(last.count(curr)) return true; if(!visited.count(curr)) { tmp.insert(curr); visited.insert(curr); } swap(curr[i-1],curr[i]); } } } swap(tmp,first); } return false; } }; However, for the given input start = "RXXLRXRXL", end = "XRLXXRRLX";, it returns the output false. It follows the below path: Checking for: XRXLRXRXL Checking for: RXLXRXRXL Checking for: RXXLXRRXL Checking for: RXXLRXXRL Checking for: RXXLRXRLX Checking for: XRLXXRRLX Checking for: RLXXXRRLX I am not sure why it doesn't consider all the paths and return true. IMO my implementation of two-way BFS is correct. Is this even solvable by two-way BFS? Am I missing something? Note: The actual constraints on LeetCode are higher: 1 <= start.length <= 10^4; but for now I am just interested in a two-way BFS implementation (assuming the constraints are 1 <= start.length <= 100 instead). Thanks!
Debugging: if I comment the "swap first and last" line, the solution works on this test. The culprit: when considering the actual last instead of first, the program should do inverse operations: not XL to LX and RX to XR, but LX to XL and XR to RX. Perhaps keep a boolean value (switching whenever you swap first and last) to track which set of operations to use. The two-way BFS goes forward from the start, and simultaneously backward from the end. As soon as the two searches meet, it has found a path. To choose in which direction to go, the two-way BFS checks the size of the last layers in both BFS instances, and proceeds with the layer that is smaller. Naturally, the steps backward from the end have to be reverse steps. The program does not take that into account, and so does not work.
72,503,214
72,503,666
Using constexpr vectors in template parameters (C++20)
Recently, I've been playing around with C++20's new constexpr std::vectors (I'm using GCC v12), and have run into a slight problem (this is actually an extension of my last question, but I thought it would just be better to make a new one). I've been trying to use constexpr std::vectors as members to a class, but this seems like it doesn't work as you cannot annotate them with constexpr and therefore constexpr functions think they can't be evaluated at compile time, so now I am trying to use template parameters instead, like this: #include <array> template<int N, std::array<int, N> arr = {1}> class Test { public: constexpr int doSomething() { constexpr const int value = arr[0]; return value * 100; } }; int main() { Test<10> myTestClass; // return the value to prevent it from being optimized away return myTestClass.doSomething(); } This results in the expected assembly output (simply returning 100 from main): main: mov eax, 100 ret However, something like this doesn't work for std::vectors, even though they can be constexpr now! #include <vector> template<std::vector<int> vec = {1}> class Test { public: constexpr int doSomething() { constexpr const int value = vec[0]; return value * 100; } }; int main() { Test<> myTestClass; return myTestClass.doSomething(); } This throws this error: <source>:3:35: error: 'std::vector<int>' is not a valid type for a template non-type parameter because it is not structural 3 | template<std::vector<int> vec = {1}> | ^ In file included from /opt/compiler-explorer/gcc-12.1.0/include/c++/12.1.0/vector:64, from <source>:1: /opt/compiler-explorer/gcc-12.1.0/include/c++/12.1.0/bits/stl_vector.h:423:11: note: base class 'std::_Vector_base<int, std::allocator<int> >' is not public 423 | class vector : protected _Vector_base<_Tp, _Alloc> | ^~~~~~ <source>: In function 'int main()': <source>:17:24: error: request for member 'doSomething' in 'myTestClass', which is of non-class type 'int' 17 | return myTestClass.doSomething(); How can I do this with vectors, or is it even possible? And, is it possible to make constexpr members, or not?
You still (in C++20 and I don't think there is any change for C++23) can't use a std::vector as a non-type template argument or have any std::vector variable marked constexpr or have any constant expression resulting in a std::vector as value at all. The only use case that is allowed now in C++20 that wasn't allowed before is to have a (non-constexpr) std::vector variable or object which is constructed while a constant expression is evaluated and destroyed before the constant evaluation ends. This means you can now for example take the function int f() { std::vector<int> vec; vec.push_back(3); vec.push_back(1); vec.push_back(2); std::sort(vec.begin(), vec.end()); return vec.front(); } add a constexpr on it and use it in constant expression e.g. static_assert(f() == 1); But that's all. It is still very useful, because beforehand you could only use algorithms that don't need any dynamic memory allocation to calculate something at compile-time. That meant that you often couldn't just use the usual runtime algorithm/implementation directly in a compile-time context. The same is true for any type that keeps references to dynamically allocated memory. You need to destroy them during the constant expression evaluation, i.e. they must be temporaries or local variables in a function or return values which are not stored in a runtime context. In the specific case of non-type template arguments the situation is even stricter. Not all types that you could make a constexpr variable of, can be used as non-type template arguments. There are much stricter restrictions. They must be so-called structural types. These are for example fundamental types such as arithmetic types, pointers, etc. A class type is a structural type if it is a literal type and also has only non-static data members which are public and non-mutable as well as all of them, recursively, structural types as well. I think it is clear that std::vector doesn't satisfy these requirements. std::array is explicitly specified to be a structural type, which is why you are allowed to use it as non-type template argument.
72,503,312
72,503,395
How to implement a destructor
I am having trouble to understand vector and heap. So far, I want to create a vector of int. The element of this vector should be stored in the heap. I have implemented a class, but I don't think that I have implement the destructor correctly. There is also a problem with the move constructor. If I want to move vector a to vector b, a stays with the same values. Class A { private : vector<int> myV ; int val; size_t Size; public: A(){ myV.resize(0); this->value = 0 ; } A(size_t size){ MyVector.resize(0); Size = size ; this->value = 0 ; } A(size_t size, int value){ A.resize(0); Size = size; Val = value; MyVector.push_back(Val); } ~A() { myV.clear(); delete &myV; } A(A&&other) { *this = std::move(other); this->myV = other.myV ; } I tried to check the code, But int main() { Vector myVect(2,5); Vector m (std::move(myVect)); std::cout<<m[0]<<std::endl; } values of myVect is not moved, though it stayed as they are. From what I understood that vector should allocate the element on the heap, how can I release it where there isn't memory leak.
Please find below a working example. #include <vector> #include <iostream> // Debug only class Vector { private: std::vector<int> _myVec; int _val; size_t _size; public: // "Regular" Construtors Vector() : _val(0), _size(0) {} Vector(size_t size) : _size(size), _val(0) {} Vector(size_t size, int value) : _val(value), _size(size) { _myVec.push_back(_val); } // Move Constructor Vector(Vector&& other) { std::cout << "Move Constructor called\n"; // Debug purpose _myVec = std::move(other._myVec); _val = std::move(other._val); _size = std::move(other._size); } // Destructor ~Vector() { _myVec.clear(); // useless being given the destructor will destroy the vector of int anyway } // Getter std::vector<int> getMyVec() const { return _myVec; } }; int main() { std::cout << "Hello world\n"; Vector _myVecect(2, 5); Vector m(std::move(_myVecect)); std::cout << m.getMyVec()[0] << std::endl; return 0; } When you create a move constructor, you have to move every members of the class, like it is done above ^. For your cout line in your main, this can't work like because your variable 'm' is an instance of your class Vector. You cannot manipulate it through the [] operator unless you define it yourself to work with it like it is an array. You don't need this kind of destructor doing this being given you do not manage streams or dynamic memory. If you have a stream, the destructor would be a good place to close to ensure no one will try to use the stream after the object deletion. In the case of dynamic memory, you would not have to use delete here because we now have in modern C++ smart pointers (unique_ptr and smart_ptr that do the job for you).
72,504,041
72,504,110
Reinterpret cast conversions
To my understanding of the standard regarding [expr.reinterpret.cast]—but please correct me if I'm wrong—converting a pointer to member function to some other pointer to member function and back to its original is actually legal, well-defined behavior. As laid out in section 7.6.1.10: A prvalue of type “pointer to member of X of type T1” can be explicitly converted to a prvalue of a different type “pointer to member of Y of type T2” if T1 and T2 are both function types or both object types.59 The null member pointer value ([conv.mem]) is converted to the null member pointer value of the destination type. The result of this conversion is unspecified, except in the following cases: (10.1) Converting a prvalue of type “pointer to member function” to a different pointer-to-member-function type and back to its original type yields the original pointer-to-member value. (10.2) Converting a prvalue of type “pointer to data member of X of type T1” to the type “pointer to data member of Y of type T2” (where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer-to-member value. This seems to be contrary to regular function pointers, where doing the same conversions would result in unspecified behavior. As laid out in section 7.6.1.6: A function pointer can be explicitly converted to a function pointer of a different type. [Note 4: The effect of calling a function through a pointer to a function type ([dcl.fct]) that is not the same as the type used in the definition of the function is undefined ([expr.call]). — end note] Except that converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are function types) and back to its original type yields the original pointer value, the result of such a pointer conversion is unspecified. [Note 5: See also [conv.ptr] for more details of pointer conversions. — end note] Some example code to illustrate the distinction between the two types of conversions: struct s { auto f() -> void {} }; struct t { auto g(t) -> t { return {}; } }; auto f() -> void {}; auto g(t) -> t { return {}; } auto main() -> int { auto ps = &s::f; auto pt = reinterpret_cast<decltype(&t::g)>(ps); (s{}.*reinterpret_cast<decltype(&s::f)>(pt))(); // well-defined behavior auto pf = &f; auto pg = reinterpret_cast<decltype(&g)>(pf); reinterpret_cast<decltype(&f)>(pg)(); // unspecified behavior } What is the reason behind having the regular function pointer conversions result in unspecified behavior? Why aren't both types of conversions either well-defined or unspecified? What are the ramifications of allowing regular function pointer conversions to be well-defined as well? It strikes me as quite odd to have this distinction when both types of conversions appear to be of such a similar nature.
You simply misread the second quote. In the highlighted sentence everything in the subordinate clause before the main clause "the result of such a pointer conversion is unspecified" is stating an exception to that main statement. The reinterpret_cast round-trip conversion guarantee works for function pointers exactly like it does for member function pointers (but not for object pointers or data member pointers, where it is restricted by alignment). So both of the examples you give result in specified function/member pointer values after the back-reinterpret_cast and the program has well-defined behavior. The second quote is simply using a more compact wording to say that aside from this use of the result of the conversion, nothing else is specified about reinterpret_cast<decltype(&g)>(pf). The same is true for reinterpret_cast<decltype(&t::g)>(ps). The relevant statement for this is in the first quote before the highlighted section: "The result of this conversion is unspecified, except in the following cases:"
72,504,525
72,504,643
What's the difference of "co_await other_co" and "other_co.resume"?
The following code doesn't work as my expectation. #include <iostream> #include <coroutine> #include <vector> struct symmetic_awaitable { std::coroutine_handle<> _next_h; symmetic_awaitable(std::coroutine_handle<> h) : _next_h(h) {} constexpr bool await_ready() const noexcept { return false; } std::coroutine_handle<> await_suspend(std::coroutine_handle<>) const noexcept { return _next_h; } constexpr void await_resume() const noexcept {} }; struct return_object : std::coroutine_handle<> { struct promise_type { return_object get_return_object() { return std::coroutine_handle<promise_type>::from_promise(*this); } std::suspend_always initial_suspend() noexcept { return {}; } std::suspend_always final_suspend() noexcept { return {}; } void return_void() {} void unhandled_exception() {} }; return_object(std::coroutine_handle<promise_type> h) : std::coroutine_handle<>(h) {} }; std::vector<return_object> co_list; return_object fa() { std::cout << "fa1" << std::endl; co_await symmetic_awaitable(co_list[1]); std::cout << "fa2" << std::endl; co_return; } return_object fb() { std::cout << "fb1" << std::endl; co_await symmetic_awaitable(co_list[2]); std::cout << "fb2" << std::endl; co_await std::suspend_always{}; std::cout << "fb3" << std::endl; co_return; } return_object fc() { std::cout << "fc1" << std::endl; co_await symmetic_awaitable(co_list[1]); std::cout << "fc2" << std::endl; co_return; } int main() { auto a = fa(); auto b = fb(); auto c = fc(); co_list.push_back(a); co_list.push_back(b); co_list.push_back(c); a.resume(); std::cout << "end" << std::endl; a.destroy(); b.destroy(); c.destroy(); } I think the output will be fa1 fb1 fc1 fb2 fa2 end But the actual output is fa1 fb1 fc1 fb2 end Then I replace all co_await symmetic_awaitable(co_list[i]) with co_list[i].resume. The ouput is very strange fa1 fb1 fc1 fb1 fc1 ..... // the following is infinite loop of "fb1 fc1" ..... ..... The C++20 coroutine shadow too many details, such that the code can't work normally as my expectation unless I know them all clearly. Here are my questions after I read cppreference: 1. What's the defference of "caller" and "resumer" ? a call b.resume(), then a is the resumer or caller of b ? 2. What's the exact meanning of "suspended" ? a call b.resume(), then a is suspended or running? a resume b through co_await, then a is suspended or running ?
If a function is a coroutine, it can only become suspended in one of the following ways: When the coroutine starts, if the promise initially suspends. When a co_await expression (or equivalent, like co_yield) is directly invoked. When the coroutine co_returns, if the promise finally suspends. Nothing else can cause a coroutine to become suspended. The "co" in "coroutine" represents cooperative multitasking. That means there's no multitasking unless the function(s) involved cooperate. Explicitly. Your assumptions about how you expect your code to work seem to suggest that you believe that coroutines have some kind of execution stack. That when await_suspend is called, the current coroutine gets put onto a stack that will be poped when the coroutine handle you returned finishes in some way. And therefore, when you invoke co_await std::suspend_always{}; this will resume the previously suspended coroutine. None of that is true. Not unless you build that machinery yourself. The coroutine system does exactly and only what you tell it to do. The call stack immediately after calling a.resume() looks like this: main() fa() When fa suspends and resumes fb, it now looks like this: main() fb() fa is gone. You suspended it. It is no longer on the call stack. And it will only ever be resumed if you explicitly ask to resume it. If you want fa's suspension into fb to mean that fa will be continued after fb finishes, then you must build that into your coroutine machinery. It doesn't just happen; it's your responsibility to make it happen. Your await_suspend code needs to take the handle it is given (which refers to fa) and store it in a place where, when fb is finished, it can resume fa. This will typically be in fb's promise object, so that final_suspend can resume it (typically passing along the data generated by fb). Remember: the final-suspend point will co_await on whatever the promise's final_suspend returns, so you can just return the handle of the coroutine you want to resume. What's the defference of "caller" and "resumer" ? I don't know what that means. I suspect you are asking what the difference is between co_awaiting on something and directly calling coroutine_handle::resume function. As previously indicated, outside of the initial and final suspend points, only co_await (or equivalent) expressions can cause a coroutine to suspend. Calling resume on a handle is like you called into the middle of a function. It works just like any other function call; it goes onto the stack and so forth. Having co_await resume a coroutine is different. When await_suspend returns a coroutine handle, this replaces your coroutine with the resumed coroutine on the call stack. That's the whole point of suspending the coroutine.
72,505,009
72,505,254
Why can't I initialize this std::vector with an l-value?
I've come across an interesting issue, and I can't understand what's happening: /* I WANT 6 ELEMENTS */ int lvalue = 6; std::vector<int*> myvector { 6 }; /* WORKS FINE */ std::vector<int*> myvector{ lvalue }; /* DOESN'T WORK */ /* Element '1': conversion from 'int' to 'const unsigned __int64 requires a narrowing conversion */ From what I can see a single integer argument that I've provided can either be interpreted as calling the constructor with argument size_type count, or the one that takes an initializer list. It seems to call the initialiser_list constructor only when I provide an l-value but the size_t count constructor when I give an r-value int (well, a literal at least). Why is this? Also this means that: int num_elements = 6; std::vector<int> myvector{num_elements}; Results in a vector of only size 1; std::vector<int> myvector(num_elements); Results in a vector of size num_elements, but I thought this initialization should be avoided because of occasionally running into most vexing parse issues.
TL;DR The problem is not specific/limited to std::vector but instead is a consequence of the rule quoted below from the standard. Let's see on case by case basis what is happening and why do we get the mentioned narrowing conversion error/warning when using lvalue. Case 1 Here we consider: int lvalue = 6; // lvalue is not a constant expression //---------------------------v------------------->constant expression so works fine std::vector<int*> myvector { 6 }; std::vector<int*> myvector{ lvalue }; //--------------------------^^^^^^--------------->not a constant expression so doesn't work First note that std::vector<int*> does not have an initializer list constructor that takes an initializer list of int. So in this case the size_t count ctor will be used. Now let's see the reason for getting narrowing conversion error/warning. The reason we get an error/warning when using the variable named lvalue while not when using a prvalue int is because in the former case lvalue is not a constant expression and so we have a narrowing conversion. This can be seen from dcl.init.list#7 which states: A narrowing conversion is an implicit conversion from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression whose value after integral promotions will fit into the target type. (emphasis mine) This means that the conversion from lvalue(which is an lvalue expression) which is of type int to size_t parameter of the vector's std::vector::vector(size_t, /*other parameters*/) ctor, is a narrowing conversion. But the conversion from prvalue int 6 to the size_t parameter of the vector's std::vector::vector(size_t, /*other parameters*/) is not a narrowing conversion. To prove that this is indeed the case, lets look at some examples: Example 1 int main() { //----------------v---->no warning as constant expression std::size_t a{1}; int i = 1; //----------------v---->warning here i is not a constant expression std::size_t b{i}; constexpr int j = 1; //----------------v---->no warning here as j is a constexpr expression std::size_t c{j}; return 0; } Example 2 struct Custom { Custom(std::size_t) { } }; int main() { //-----------v---->constant expression Custom c{3}; //no warning/error here as there is no narrowing conversion int i = 3; //not a constant expressoion //-----------v---->not a constant expression and so we get warning/error Custom d{i}; //warning here of narrowing conversion here constexpr int j = 3; //constant expression //-----------v------>no warning here as j is a constant expression and so there is no narrowing conversion Custom e{j}; return 0; } Demo Case 2 Here we consider: //------------v-------------------------->note the int here instead of int* unlike case 1 std::vector<int> myvector{num_elements};//this uses constructor initializer list ctor In this case there is a initializer list ctor available for std::vector<int> and it will be preferred over the size_t count constructor as we've used braces {} here instead of parenthesis (). And so a vector of size 1 will be created. More details at Why is the std::initializer_list constructor preferred when using a braced initializer list?. On the other hand, when we use: std::vector<int> myvector(num_elements); //this uses size_t ctor Here the size_t ctor of std::vector will be used as the initializer list ctor is not even viable in this case as we've used parenthesis (). And so a vector of size 6 will be created. You can confirm this using the example given below: struct Custom { Custom(std::size_t) { std::cout<<"size t"<<std::endl; } Custom(std::initializer_list<int>) { std::cout<<"initializer_list ctor"<<std::endl; } }; int main() { Custom c(3); //uses size_t ctor, as the initializer_list ctor is not viable return 0; }
72,505,267
72,505,375
Rotate a vector in right direction using std::rotate()
How to rotate a vector in right direction by K steps using std::rotate? Is there a better or faster method to rotate a vector(array) than std::rotate?
How to rotate a vector in right direction by K steps using std::rotate? The second parameter to std::rotate is an iterator to the new first element after the rotation. So, to do a right rotate by 1 step, that would mean the end() - 1 should be the new first etc. Generalized: template<class... T> void rotate_right(std::vector<T...>& v, std::size_t steps) { if(steps %= v.size()) std::rotate(v.begin(), std::prev(v.end(), steps), v.end()); } Is there a better or faster method to rotate a vector(array) than std::rotate? No, I don't think there is. If you find it too slow, you could use the version that uses one of the parallel execution policies and see if that speeds it up. Example: #include <execution> template<class... T> void rotate_right(std::vector<T...>& v, std::size_t steps) { if(steps %= v.size()) std::rotate(std::execution::par, v.begin(), std::prev(v.end(), steps), v.end()); }
72,505,524
72,676,373
SysTick_Handler works as a normal function but not on SysTick interrupt (on QEMU)
I am trying to implement a simple RTOS with round robin scheduling. Since I do not have a physical board yet, I am running the ELF file on QEMU (qemu-system-gnuarmlinux). For development I am using Eclipse CDT. I use the following command to run the code on QEMU: /opt/xpack-qemu-arm-7.0.0-1/bin/qemu-system-gnuarmeclipse -M STM32F4-Discovery -kernel /mnt/d/eclipse-workspace/rtos/Debug/rtos.elf Each task has an associated struct: struct TCB { int32_t *stackPt; struct TCB *nextPt; }; At initialization, the structs are chained up in a circular linked list via the nextPt, their stacks (stackPt) are set as TCB_STACK[threadNumber][STACK_SIZE-16]; and the stack's program counter is set up as TCB_STACK[0][STACK_SIZE - 2] = (int32_t)(taskA);. The current thread's pointer is maintained as: currentTcbPt. Then the systick is set up to interrupt at every 10ms. An assembly setup function sets up initial stack pointer to the thread stack pointed to by currentTcbPt. This function is as follows: osSchedulerLaunch: // This routine loads up the first thread's stack pointer into SP CPSID I LDR R0,=currentTcbPt LDR R2,[R0] // R2 = address of current TCB LDR SP,[R2] POP {R4-R11} POP {R0-R3} POP {R12} ADD SP,SP,#4 // Skip 4 bytes to discard LR POP {LR} ADD SP,SP,#4 // Skip 4 bytes to discard PSR CPSIE I BX LR Now, my SysTick_Handler looks like this: __attribute__( ( naked ) ) void SysTick_Handler(void) { __asm( "CPSID I \n" "PUSH {R0-R12} \n" "LDR R0,=currentTcbPt \n" "LDR R1,[R0] \n" "STR SP,[R1] \n" "LDR R1,[R1,#4] \n" "STR R1,[R0] \n" "LDR SP,[R1] \n" "POP {R4-R11} \n" "POP {R0-R3} \n" "POP {R12} \n" "ADD SP,SP,#4 \n" "POP {LR} \n" "ADD SP,SP,#4 \n" "CPSIE I \n" "BX LR \n" :[currentTcbPt] "=&r" (currentTcbPt) ); } I have added extra register operations so I can use it as a normal function. Problem **First**, I disable interrupts in the `onSchedulerLaunch` function (comment out `CPSIE I`) and in the systick handler. Also renaming `SysTick_Handler` to a random function name (say `Foo`). Then, I call this `Foo` function at the end of each task (tasks do not have an infinite loop). This works absolutely fine. The tasks get switched over and over as intended. **Second**, I enable interrupts, set the function's name back to `SysTick_Handler`, re enable interrupts and `extern "C"` and remove the call from the end of tasks. Now, as soon as the SysTick exception happens, the function get's executed, but I get a Usage Fault with a stack register print on terminal. OS init Launching scheduler t2 t2 [UsageFault] Stack frame: R0 = 00000003 R1 = 2000008C R2 = 00000000 R3 = 000004B8 R12 = 00000000 LR = 0800148D PC = 000004B8 PSR = 20000000 FSR/FAR: CFSR = 00000000 HFSR = 00000000 DFSR = 00000000 AFSR = 00000000 Misc LR/EXC_RETURN= FFFFFFF9 On examining the asm code using -d in_asm option in QEMU and also using remote gdb, The problem seems to happen at the first line of the next task (the same address in PC above). Question What could be the cause of this problem ? Is it perhaps specific to QEMU or is there something wrong with the assembly code ? EDIT: See the full code to reproduce https://gist.github.com/shivangsgangadia/b78c7c66492d5332c7b4d1806be9c5f6 The order of execution of function would be something like: RTOS rtos(); rtos.addThreads(&task_a, &task_b, &task_c); rtos.osKernelLaunch();
The problem was setting the T-bit in the Execution PSR register for individual task stacks. The course content that I was following skipped over the fact that the PSR is composed of 4 bytes, and the T-bit in the most significant byte. Initially, I was setting it as: TCB_STACK[threadNumber][STACK_SIZE-1] = (1U << 6);. This was causing the BX LR to not pick up the return address properly. Setting the 6th bit in the 4th byte, i.e., TCB_STACK[threadNumber][STACK_SIZE-1] = (1U << 24); solved the problem and now the scheduler works flawlessly.
72,505,589
72,505,610
How to pass a variable's pointer?
This is my code: GLint framebuffer_handle = 0; void glGetIntegerv(GLenum pname, GLint * data){ ... } glGetIntegerv(GL_FRAMEBUFFER_BINDING, *framebuffer_handle); The last line reports an error: indirection requires pointer operand ('GLint' (aka 'int') invalid) What's the problem with this code?
framebuffer_handle is not a pointer, so you can't dereferenced it with the * operator. That is what the compiler is complaining about. glGetIntegerv() wants a pointer to a GLint. A pointer holds a memory address. You need to use the & operator to get the address of (ie, a pointer to) the framebuffer_handle variable, eg: glGetIntegerv(GL_FRAMEBUFFER_BINDING, &framebuffer_handle);
72,505,726
72,505,786
Having trouble accessing a list value inside a map | C++
I've made a map that has string keys with either string values or list values. It gives me no syntax errors and has worked fine for me so far until I've tried accessing the list value. I've tried setting it as a variable, using auto, and no go. Don't know what else to try, any help is appreciated. using map = std::map<std::string, std::variant<std::string, std::list<std::string>>>; std::list<std::string> TagList{ "Paid", "Needs invoice" }; map m{ {"TIME",TimeHourAndMin}, {"HEADER","Title"},{"TAGS", TagList},{"CONTENT", "Hey this is content!"} }; // E0135 class "std::variant<std::string, std::list<std::string, std::allocator<std::string>>>" has no member "begin" // E0135 class "std::variant<std::string, std::list<std::string, std::allocator<std::string>>>" has no member "end" for (auto it = m["TAGS"].begin(); it != m["TAGS"].end(); it++) { }
The problem is that m["TAGS"] is of type std::variant and so doesn't have a begin method. Since you want to get the list out of your variant you can use the std::get function to do that auto it = std::get<std::list<std::string>>(m["TAGS"]).begin();
72,505,769
72,505,863
How to put 3 elements in priority_queue in c++
I been studying priority_queue in c++ from Leetcode and I found this code from solution I understand that this is minimum heap but don't understand how is this storing 3 elements to minHeap. is vector<int> gets matrix[r][0], vector<vector<int>> gets r and greater<> gets 0???? Why do we need to put priority_queue<int,vector<int>,greater<int>> minHeap a vector<int> to make Minimum heap?
First, let's look at the meaning of the template arguments in the class of minHeap. From cppreference: template< class T, class Container = std::vector<T>, class Compare = std::less<typename Container::value_type> class priority_queue; Template parameters T - The type of the stored elements. ... Container - The type of the underlying container to use to store the elements. ... Compare - A Compare type providing a strict weak ordering. So, for minHeap, it contains vector<int> objects. It uses a vector<vector<int>> as the underlying storage to contain these vector<int> objects. And it uses greater<> to compare two vector<int> objects to decide what order they go in. What does the greater<> signify? The Compare argument is used to decide which element goes on top. By default, priority_queue uses less<>, which means that larger elements go on top. By using greater<> instead, it flips the direction of the comparison, so smaller elements go on top. This is what makes it a "min" heap. Now, looking at the call to push: void push( const value_type& value ); void push( value_type&& value ); (since C++11) push is only accepting a single argument, and the argument is of type value_type, which in this case is vector<int>. So the line minHeap.push({matrix[r][0], r, 0}); Is actually adding a single vector<int> to minHeap. The values contained in that vector<int> are matrix[r][0], r, and 0.
72,506,092
72,506,169
How are unknown attributes supposed to be treated before C++17?
cppreference says that All attributes unknown to an implementation are ignored without causing an error. ... but that this edict was introduced in C++17. What about earlier versions of C++? Are unknown attributes supposed to be errors? Is it implementation-defined what to do with them?
It was implementation-defined since its introduction in C++11. See [dcl.attr.grammar]/5: For an attribute-token not specified in this International Standard, the behavior is implementation-defined.
72,506,335
72,506,497
Concatenate 2 string using operator+= in class C++
I've seen some similar questions before asking, but I'm still stuck at the part of concatenating two strings using operator+=. Currently, I can get separate strings correctly by constructor method. But when I compile code, the line str[length+i] = s[i]; in the method String& String::operator+= (const String& s) shows an error: no match for ‘operator[]’ (operand types are ‘const String’ and ‘unsigned int’) So I need your help to fix this bug. Here's my code: #include <iostream> #include <cstring> class String { // Initialise char array char* data; unsigned length; public: // Constructor without arguments String(); // Constructor with 1 arguments String(char* s); // Copy Constructor String(const String& source); // Move Constructor String(String&& source); // Destructor ~String() { delete[] data; } /*! * @brief String length. * @return Value in String @c length. */ unsigned len ( ) const; /*! * @brief Append to String. * @param[in] s A String object. * @return A String reference to *this. * @post String will equal the concatenation of itself with @a s. */ String& operator+= (const String& s); }; // Constructor with no arguments String::String() : data{ nullptr } { data = new char[1]; data[0] = '\0'; } // Constructor with one arguments String::String(char* s) { if (s == nullptr) { data = new char[1]; data[0] = '\0'; } else { data = new char[strlen(s) + 1]; // Copy character of s[] // using strcpy strcpy(data, s); data[strlen(s)] = '\0'; std::cout << data << "\n"; } } // Copy Constructor String::String(const String& source) { data = new char[strlen(source.data) + 1]; strcpy(data, source.data); data[strlen(source.data)] = '\0'; } // Move Constructor String::String(String&& source) { data = source.data; source.data = nullptr; } unsigned String::len ( ) const { return length; } String& String::operator+= (const String& s) { unsigned len = length + s.len(); char* str = new char[len]; for (unsigned j=0; j < length; j++) str[j] = data[j]; for (unsigned i=0; i < s.len(); i++) str[length+i] = s[i]; delete data; length = len; data = str; return *this; } int main() { // Constructor with no arguments String a; // Convert string literal to // char array char temp[] = "Hello world."; // Constructor with one argument std::cout << "s1: "; String s1{ temp }; // Copy constructor String s11{ a }; char temp1[] = "Goodbye!"; std::cout << "s2: "; String s2{ temp1 }; String s3 = String s1 + String s2; return 0; } Another way of writing main function: int main() { String s1("Hello World."); String s2("Goodbye!"); std::cout << "s1: " << s1 << std::endl; std::cout << "s2: " << s2 << std::endl; String s3 = s1 + s2; std::cout << "s3: " << s3 << std::endl; std::cout << "The last char of s3: " << s3[s3.size()-1] << std::endl; return 0; } Expected result: s1: Hello World. s2: Goodbye! s3: Hello World.Goodbye! The last char of s3: ! How can I modify my code to get s3 and last char of s3 correctly?
In many of your constructors, you do not set length which leaves it with an indeterminate value - and reading such values makes the program have undefined behavior. So, first fix that: #include <algorithm> // std::copy_n // Constructor with no arguments String::String() : data{new char[1]{'\0'}}, length{0} {} // Constructor with one argument String::String(const char* s) { // note: const char* if (s == nullptr) { data = new char[1]{'\0'}; length = 0; } else { length = std::strlen(s); data = new char[length + 1]; std::copy_n(s, length + 1, data); } } // Copy Constructor String::String(const String& source) : data{new char[source.length + 1]}, length{source.length} { std::copy_n(source.data, length + 1, data); } // Move Constructor String::String(String&& source) : String() { std::swap(data, source.data); std::swap(length, source.length); } In operator+= you are trying to use the subscript operator, String::operator[], but you haven't added such an operator so instead of s[i], use s.data[i]: String& String::operator+=(const String& s) { unsigned len = length + s.length; char* str = new char[len + 1]; for (unsigned j = 0; j < length; j++) str[j] = data[j]; for (unsigned i = 0; i < s.length; i++) str[length + i] = s.data[i]; str[len] = '\0'; delete[] data; // note: delete[] - not delete length = len; data = str; return *this; } If you want to be able to use the subscript operator on String objects, you would need to add a pair of member functions: class String { public: char& operator[](size_t idx); char operator[](size_t idx) const; }; char& String::operator[](size_t idx) { return data[idx]; } char String::operator[](size_t idx) const { return data[idx]; } And for String s3 = s1 + s2; to work, you need a free operator+ overload: String operator+(const String& lhs, const String& rhs) { String rv(lhs); rv += rhs; return rv; } Also, to support printing a String like you try in your alternative main function, you need an operator<< overload. Example: class String { friend std::ostream& operator<<(std::ostream& os, const String& s) { os.write(s.data, s.length); return os; } }; Full demo
72,506,759
72,508,650
How to convert std::chrono::duration to boost duration
I have two time_point objects in my code and I need to use Boost condition variable for the difference: template<class Clock, class Dur = typename Clock::duration> class Time { std::chrono::time_point<Clock, Dur> a; std::chrono::time_point<Clock, Dur> b; } .... boost::condition_variable var; .... var.wait_for(lock, b - a, [](){ /* something here */}); //<---boost cond var .... How can I convert b - a to something usable with boost?
I'd do what I always do: avoid duration_cast by using arithmetic with UDL values. You have to select a resolution for this, let's choose microseconds: #include <boost/thread.hpp> #include <chrono> #include <iostream> using namespace std::chrono_literals; template <class Clock, class Dur = typename Clock::duration> // struct Time { std::chrono::time_point<Clock, Dur> a = Clock::now(); std::chrono::time_point<Clock, Dur> b = a + 1s; boost::mutex mx; void foo() { //.... boost::condition_variable var; //.... boost::unique_lock<boost::mutex> lock(mx); std::cout << "Waiting " << __PRETTY_FUNCTION__ << "\n"; auto s = var.wait_for(lock, boost::chrono::microseconds((b - a) / 1us), [] { /* something here */ return false; }); //<---boost cond var assert(!s); //.... } }; int main() { Time<std::chrono::system_clock>{}.foo(); Time<std::chrono::steady_clock>{}.foo(); std::cout << "\n"; } Prints (1 second delay each): Waiting void Time<Clock, Dur>::foo() [with Clock = std::chrono::_V2::system_clock; Dur = std::chrono::duration<long int, std::ratio<1, 1000000000> >] Waiting void Time<Clock, Dur>::foo() [with Clock = std::chrono::_V2::steady_clock; Dur = std::chrono::duration<long int, std::ratio<1, 1000000000> >] I must say I can't fathom a scenario where the wait time for a condition would be specified as the difference between absolute time points, but I guess that's more of a "your problem" here :)
72,506,834
72,506,928
What is the different of ::std::cout and std::cout
There is a simple code with the different aspects of usage of :: operation. namespace test{ int add(int x, int y){ return x + y; } } int main(){ int x=3, y=5; int r = ::test::add(x,y); r = test::add(x,y); } or in another example ::std::cout << "Hello"; std::cout << "Hello"; The functionality of these codes (I mean the usage of :: before statement) is not different. Then why is it (::) used before statements?
The difference is that one is a fully qualified name, and the other is not a fully qualified name. Whether the fully qualified name is used or not doesn't make a practical difference in these examples. It could make a difference in another context. See the further down for an example. To understand the concept it may help if you are familiar with other cases of qualified names. Consider for example the UNIX/LINUX filesystem. The path separator is / in contrast to C++ namespaces whose separator is ::. The root of the filesystem is / while the global namesoace is ::. At the root is a file named foo. Current working directory is the root. What is the difference between the paths /foo and foo? They both refer to the same file, but the first is an absolute (i.e. fully qualified) while the other is relative (unqualified). Now consider changing working directory to /bar. In this context, the relative path now refers to /bar/foo and no longer refers to the same file as /foo. Another, similar analogy is the web. Let's say you are on page bar.org. What is the difference between urls http://bar.org/foo, bar.org/foo, //foo, /foo, and foo? They all refer to the same entity. The first is fully qualified, the last is unqualified, and the others have various levels of qualification. If you browse to bar.org/baz or perhaps zap.org, the relative URL change meaning while the absolute do not. C++ name lookup is more complex than these analogous examples in that it can match relative names to parent namespaces of the active namespace while filesystem paths and URLs generally don't. This difference has no effect in your example cases. A simple example here qualification of a name does make a difference: int foo = 1; namespace bar { int foo = 2; void baz() { std::cout << foo; std::cout << ::foo; } }
72,506,840
72,506,958
C++ problem adding elements to a std::list
I'm working on a project in which I have to assign missions to timetables. Timetables are divided in three classes : Semaine, Journee and Mission.Each class contains a list of elements of the lower level. Here's the definition of each class : class Mission{} class Journee{ list<Mission> missions; bool addMission(Mission& m); } class Semaine{ list<Journee> jours; bool addMission(Mission& m); } I want to add a Mission to an element of the list jours using Semaine::addMission(). However, when I try doing so, the added element doesn't appear, whereas it appears when I use Journee::addMission(). Here's the code of each addMission() function: bool Semaine::addMission(Mission& m){ if(!isInWeek(m.date)) return false; for(Journee j : jours){ if(j.addMission(m)){ initMemory(); // not important here return true; } return false; } bool Journee::addMission(Mission& m){ if(m.date==date){ missions.push_back(m); missions.sort(); initMemory(); // same return true; } return false; } // Alternative tries : change return types to Journee/Semaine and Journee&/Semaine& Each call to these functions from the main file: Semaine s = Semaine(); for(Mission m : missions) s.addMission(m); cout << s; // Printed as if no mission was added Semaine j = Journee(); for(Mission m : missions) j.addMission(m); cout << j; // Printed with added missions I understood that this kind of problem can occur when copy constructors are missing or bad, so I implemented one for each class, here they are (attributes of standard types copied with = operator): Mission(const Mission& m){} Semaine::Semaine(const Semaine& s){jours = list<Journee>(s.jours);} Journee::Journee(const Journee& j){missions = list<Mission>(j.missions);} //Alternative tries : std::copy, list::insert Constructors used : Journee::Journee(){missions = list<Mission>();} Semaine::Semaine(){Semaine(1);} Semaine::Semaine(int dateLundi){ this->dateLundi = dateLundi; jours = list<Journee>(); for(int i = 0; i < 7; i++){ jours.push_back(Journee(dateLundi+i)); } } Do you have any idea why is it not working/how to fix it?
I think the problem is in for(Journee j : jours){ This gives you a copy of Journee. Using a reference instead, i.e. for(Journee& j : jours){ should solve the problem Similarly for for(Mission m : missions) s.addMission(m); That should rather be: for(Mission& m : missions) s.addMission(m); or even better: for(auto& m : missions) s.addMission(m);
72,507,367
72,507,434
Why can't I create Tree using the code below?
It's a function to bulid a binary tree,but it can't work,can someone tell me what's wrong with my code typedef struct treeNode* BT; struct treeNode { int val; treeNode* left; treeNode* right; }; BT createTree(BT root) { int data = 0; cin >> data; if (data == -1) { return nullptr; } root = new treeNode; root->val = data; createTree(root->left); createTree(root->right); return root; }
You're ignoring the result of createTree(root->left); and createTree(root->right); What's more, in your implementation the argument root is meaningless. You're not using it at all. Code below should work. BT createTree() { int data = 0; BT root; cin >> data; if (data == -1) { return nullptr; } root = new treeNode; root->val = data; root->left = createTree(); root->right = createTree(); return root; }
72,508,057
72,508,866
Can .gch files generated from CMake's target_precompile_headers be shared across targets?
My initial attempt at incorporating precompiled header files in my project resulted in very large (~200MB) and nearly identical .gch files for each target directory. I tried the following approach, which I was hoping would produce a single .gch file generated and shared among targets. However, CMake still generated separate .gch files for each target. add_library(pch INTERFACE) target_precompile_headers(pch INTERFACE project.hpp) add_executable(target1 src1.cpp) target_link_libraries(target1 PRIVATE pch) add_executable(target2 src2.cpp) target_link_libraries(target2 PRIVATE pch) Is it possible to share a CMake generated .gch file across multiple targets?
You need to use target_precompile_headers per each target you want PCHs for. With one producer you use like you did and then the consumers should look like this: target_precompile_headers(target1 REUSE_FROM pch) And you do not need to link against your pch "library". Docs actually have the section for it.
72,508,842
72,608,223
Can't build Qt-Widgets Application using CMake
I am trying to setup a CMake Project building a Qt-Widgets application but can't compile it properly. My project structure is as follows: include/ mainwindow.hpp resources/ mainwindow.ui src/ main.cpp mainwindow.cpp CMakeLists.txt CMakeLists.txt cmake_minimum_required(VERSION 3.10) find_package(Qt5 COMPONENTS Widgets REQUIRED) project(Test VERSION 0.1 LANGUAGES CXX) set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) set(CMAKE_AUTOUIC ON) set(CMAKE_AUTOMOC ON) set(CMAKE_AUTOUIC_SEARCH_PATHS resources) add_executable(App src/mainwindow.cpp src/main.cpp resources/mainwindow.ui) target_include_directories(App PRIVATE include) target_link_libraries(App PRIVATE Qt5::Widgets) mainwindow.hpp #ifndef MAINWINDOW_HPP_ #define MAINWINDOW_HPP_ #include <QMainWindow> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class Test : public QMainWindow { Q_OBJECT public: Test(QWidget *parent = nullptr); ~Test(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_HPP_ mainwindow.cpp #include "mainwindow.hpp" #include "ui_mainwindow.h" Test::Test(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow){ ui->setupUi(this); } Test::~Test(){ delete ui; } main.cpp #include "mainwindow.hpp" #include <QApplication> int main(int argc, char *argv[]){ QApplication a(argc, argv); Test w; w.show(); return a.exec(); } When I'm trying to build the project: cmake -Bbuild -DCMAKE_BUILD_TYPE=Debug cmake --build build --target all I get the following linker error: [ 20%] Automatic MOC and UIC for target App [ 20%] Built target App_autogen [ 40%] Building CXX object CMakeFiles/App.dir/App_autogen/mocs_compilation.cpp.o [ 60%] Building CXX object CMakeFiles/App.dir/src/mainwindow.cpp.o [ 80%] Building CXX object CMakeFiles/App.dir/src/main.cpp.o [100%] Linking CXX executable App /usr/bin/ld: CMakeFiles/App.dir/src/mainwindow.cpp.o: in function `Test::Test(QWidget*)': .../src/mainwindow.cpp:4: undefined reference to `vtable for Test' /usr/bin/ld: .../src/mainwindow.cpp:4: undefined reference to `vtable for Test' /usr/bin/ld: CMakeFiles/App.dir/src/mainwindow.cpp.o: in function `Test::~Test()': .../src/mainwindow.cpp:8: undefined reference to `vtable for Test' /usr/bin/ld: .../src/mainwindow.cpp:8: undefined reference to `vtable for Test' collect2: error: ld returned 1 exit status make[2]: *** [CMakeFiles/App.dir/build.make:132: App] Error 1 make[1]: *** [CMakeFiles/Makefile2:84: CMakeFiles/App.dir/all] Error 2 make: *** [Makefile:91: all] Error 2 Looking at cmakes generated link.txt, it seems that the required object files are linked properly /usr/bin/c++ \ -g CMakeFiles/App.dir/App_autogen/mocs_compilation.cpp.o \ CMakeFiles/App.dir/src/mainwindow.cpp.o \ CMakeFiles/App.dir/src/main.cpp.o \ -o App \ /usr/lib/libQt5Widgets.so.5.15.4 \ /usr/lib/libQt5Gui.so.5.15.4 \ /usr/lib/libQt5Core.so.5.15.4 Im not really sure, why the vtable references are undefined. What am I doing wrong here?
The solution to this is, adding include/mainwindow.hpp to the sources. add_executable(App src/mainwindow.cpp src/main.cpp include/mainwindow.hpp resources/mainwindow.ui) This seems to be required for the generated ui_mainwindow.h to see the vtable entries of the MainWindow class.
72,508,862
72,574,124
QT OCI driver isn't working with MSVC compiler
QT version 6.2.x I have compiled the oci driver for MinGW and MSVC. It works with MinGW compiler but not with MSVC. When I use MSVC compiler in my project I get the error "QOCI driver not loaded". The driver is compiled according to the instructions: qt-cmake.bat -G Ninja F:\Qt\6.2.0\Src\qtbase\src\plugins\sqldrivers -DCMAKE_INSTALL_PREFIX=F:\Qt\6.2.0\msvc2019_64 -DOracle_INCLUDE_DIR="C:\oracle\sdk\include" -DOracle_LIBRARY="C:\oracle\sdk\lib\msvc\oci.lib" cmake --build . cmake --install .
The problem has been fixed by using the VS Command Prompt.
72,509,401
72,509,457
Template specialization with only one parameter
If you have a class template such as this: template <typename T, unsigned CAPACITY> class Collection { T m_array[CAPACITY]{}; T m_dummy{}; unsigned m_size{}; } public: void display(std::ostream& ostr = std::cout) const { ostr << "----------------------" << std::endl; ostr << "| Collection Content |" << std::endl; ostr << "----------------------" << std::endl; } And I wanted to create specialization depending on the type used, but not the CAPACITY, is this possible? I have this, which works: void Collection<Pair, 50u>::display(std::ostream& ostr) const { ostr << "----------------------" << std::endl; ostr << "| This is a Pair |" << std::endl; ostr << "----------------------" << std::endl; } When it is called as: Collection<Pair, 50> colDictionary; But this only works if the type is Pair, as well as the exact CAPACITY is 50. This is what I had in mind, allowing for type to be Pair and CAPACITY to be anything: void Collection<Pair>::display(std::ostream& ostr) const { ostr << "----------------------" << std::endl; ostr << "| This is a Pair |" << std::endl; ostr << "----------------------" << std::endl; } But this causes a "too few arguments for class template" error. Any way to do this without changing the actual class template itself?
It's called a partial template specialization: template <class T, unsigned Capacity> struct Collection { }; template <unsigned Capacity> struct Collection<Pair, Capacity> { // Specialize }; One thing to note is that you cannot partially specialize a single function. You have to specialize the whole class template, which is irritating if the class template is long. Another quick-and-dirty way of doing this if you want to specialize a single function would be to just use a "compile-time if": #include <type_traits> template <class T, unsigned Capacity> struct Collection { void display() const { if constexpr (std::is_same_v<T, Pair>) { // pair implementation } else { // general implementation } } }; Or, as a more clean solution, try moving the whole thing out of the class and add a simple overload: // Free-standing overloads: template <class T, unsigned Capacity> void diplay(Collection<T, Capacity> const& c) { /* ... */ } template <unsigned Capacity> void display(Collection<Pair, Capacity> const& c) { /* ... */ } // The member function delegates the work to // the overloaded functions. No template specialization // is involved: template <class T, unsigned Capacity> struct Capacity { void display() const { display(*this); // calls the correct overload. } };
72,509,526
72,509,912
Deducing variadic template arguments with default arguments
I am trying to create a basic logger. Here is a small example. template<typename ...str> struct log { log( str &&...args, const char *file = __builtin_FILE(), const char *func = __builtin_FUNCTION(), const size_t line = __builtin_LINE() ) { std::cout << "[" << file << "] [" << func << "] [" << line << "] "; ((std::cout << args << " "), ...); std::cout << std::endl; } }; template<typename ...str> log(str &&...args) -> log<str ...>; I want the ability to receive caller information along with a variable number of arguments. With the above example, I can create an instance like this. log inst("THIS WORKS", "ASD", "ASD"); >>> [.../main.cpp] [main] [10] THIS WORKS ASD ASD I also want the ability to specify logging levels. This is where the trouble begins. Say I have an enum with the following logging levels, and I want to make it a template argument for the logger. The following is how I thought this would work. enum logging_level { INFO, }; template<logging_level level, typename ...str> struct log { ... }; template<logging_level level, typename ...str> log(str &&...args) -> log<level, str ...>; log<INFO> inst("THIS DOESN'T WORK", "ASD", "ASD"); The error I get here is that the arguments are passed into the default arguments, not the variadic arguments. >>> error: invalid conversion from ‘const char*’ to ‘size_t’ {aka ‘long unsigned int’} [-fpermissive] >>> 33 | log<INFO> inst("THIS DOESN'T WORK", "ASD", "ASD"); >>> | ^~~~~ >>> | | >>> | const char* This is getting well above my C++ template knowledge. An easy solution is to ditch the variadic template and just pass in a string but I wanted to see if this could work. Does anyone know how to make this compile? Thanks.
You cannot use CTAD on some arguments, but not on the others. You could make a similar syntax work though using tag dispatch. You need to move the specification of the log level to the argument list to accomplish this. Note that in the following example I'm using std::source_location (C++20) to be compiler independent: enum class LogLevel { INFO }; template<LogLevel logLevel> struct LogLevelInfoTag { constexpr operator LogLevel() { return logLevel; } }; constinit LogLevelInfoTag<LogLevel::INFO> INFO; template<LogLevel logLevel, typename ...str> struct log { log( LogLevelInfoTag<logLevel>, str &&...args, std::source_location location = std::source_location::current() ) { std::cout << "[" << location.file_name() << "] [" << location.function_name() << "] [" << location.line() << "] "; ((std::cout << args << " "), ...); std::cout << std::endl; } }; template<LogLevel logLevel, typename ...str> log(LogLevelInfoTag<logLevel>, str &&...args) -> log<logLevel, str ...>; // log<INFO> inst("THIS DOESN'T WORK", "ASD", "ASD"); // (desired syntax) log inst(INFO, "THIS DOESN'T WORK", "ASD", "ASD");
72,509,832
72,509,979
Changing inherited class' member variables
Background I've been reading about inheritance and messing around with some code, and I'm trying to better understand how to implement virtual functions, and more broadly, how to change member variables in derived classes. Here's what I've got so far: Code #include <iostream> class Base { private: int m_value {}; public: Base(int value = 5): m_value {value} { } int getValue() { return m_value; } virtual void add(int addend) { m_value = m_value + addend; } }; class Derived: public Base { private: int m_value {}; public: Derived(int value = 5): m_value {value} { } virtual void add(int addend) { m_value = m_value + addend; } }; int main() { Derived derived {}; std::cout << derived.getValue() << "\n"; derived.add(2); std::cout << derived.getValue() << "\n"; return 0; } Problem I want the inherited class to change its member variable when add() is called. Specifically, I was expecting derived.add(2) to make derived.m_value equal to 7 as opposed to 5. However, despite my efforts, I can't get derived.m_value to change. What I've Tried I reviewed a post that asked a similar question (Member function of inherited class won't change inherited base class variable), and so I added an overloaded assignment operator like this: class Derived: public Base { private: int m_value {}; public: Derived(int value = 5): m_value {value} { } Derived& operator=(const Derived& derived) { m_value = derived.m_value; return *this; } void add(int addend) { m_value = m_value + addend; } }; However, this addition and some other variations I tried still didn't work. It seems like I don't understand how inherited member functions interact with their member variables as well as I thought.
Please find below your sample working the way you want. I'll explain below the code. #include <iostream> class Base { protected: // HERE change n°1 int m_value; public: Base(int value = 5) : m_value{ value } { } int getValue() { return m_value; } virtual void add(int addend) { m_value = m_value + addend; } }; class Derived : public Base {// HERE change n°2 : no more Derived::m_value which shadows the Base::m_value (this is due to the members of same name) public: Derived(int value = 5) : Base{ value } // HERE change n°3 : we build the parent class by calling it's constructor so Base::m_value is initialized { } void add(int addend) noexcept override // HERE change n°4 { m_value = m_value + addend; } }; int main() { Derived derived{}; std::cout << derived.getValue() << "\n"; derived.add(2); std::cout << derived.getValue() << "\n"; return 0; } Change n°1 : by setting the visibility of the member m_value to protected, it means we now have access to it in the child class. This is what you'd like to have in order to have common patterns/behaviour and stuff between class in an OOP point of view. If you set it private in your parent class, you'll NOT have access to it in the child class. This statement is valid for members and methods. For example, you may want to hide some internal management performed by the parent class. Change n°2 : remove the declaration of m_value in the child class being given it shadows the Base::m_value as explained by Olaf. Change n°3 : finally, we call the constructor of the Base class in the init list of the child class constructor, so the base instance is well constructed when you declare a derived variable in your main. Change n°4 : you can add the override keywoard to the virtual methods you inherit. This is a tips to the compiler so it'll check the method signature is the same than the one in the parent class. This way, if you write a wrong method signature, or if you change your method in the parent class, you'll get an error/warning. Hope it helps
72,510,149
72,510,381
Appending line from a file into char array
char wordList[200]; ifstream wordListFile ("wordlist.txt"); for(std::string line; getline(wordListFile, line); ) { wordListFile >> wordList; } This code currently returns the line at the end of the wordListFile (wordlist.txt), is there any way to append the lines to wordList? because when I use the append() function it returns an error.
In the loop for(std::string line; getline(wordListFile, line); ) { wordListFile >> wordList; you are reading one line of input with getline(wordListFile, line);, but not doing anything with that line. Instead, you are reading the first word of the next line with wordListFile >> wordList;. This does not make sense. If you want to append the line contents to wordList, then you could initialize wordList as an empty string and then use std::strcat: #include <iostream> #include <fstream> #include <string> #include <cstring> int main() { char wordList[200] = ""; std::ifstream wordListFile( "wordlist.txt" ); for ( std::string line; std::getline(wordListFile, line); ) { std::strcat( wordList, line.c_str() ); } std::cout << wordList << '\n'; } For the input This is line 1. This is line 2. this program has the following output: This is line 1.This is line 2. As you can see, the lines were correctly appended. However, this code is dangerous, because if the file is too large for the array wordList, then you will have a buffer overflow. A safer and more efficient approach would be to make wordList of type std::string instead of a C-style string: #include <iostream> #include <fstream> #include <string> int main() { std::string wordList; std::ifstream wordListFile( "wordlist.txt" ); for ( std::string line; std::getline(wordListFile, line); ) { wordList += line; } std::cout << wordList << '\n'; } This program has the same output: This is line 1.This is line 2.
72,510,195
72,510,453
What is the effective way to replace all occurrences of a character with every character in the alphabet?
What is the effective way to replace all occurrences of a character with every character in the alphabet in std::string? #include <algorithm> #include <string> using namespace std; void some_func() { string s = "example *trin*"; string letters = "abcdefghijklmnopqrstuvwxyz"; // replace all '*' to 'letter of alphabet' for (int i = 0; i < 25; i++) { //replace letter * with a letter in string which is moved +1 each loop replace(s.begin(), s.end(), '*', letters.at(i)); i++; cout << s; } how can i get this to work?
You can just have a function: receiving the string you want to operate on, and the character you want to replace, and returning a list with the new strings, once the replacement has been done; for every letter in the alphabet, you could check if it is in the input string and, in that case, create a copy of the input string, do the replacement using std::replace, and add it to the return list. [Demo] #include <algorithm> // replace #include <fmt/ranges.h> #include <string> #include <string_view> #include <vector> std::vector<std::string> replace(const std::string& s, const char c) { std::string_view alphabet{"abcdefghijklmnopqrstuvwxyz"}; std::vector<std::string> ret{}; for (const char l : alphabet) { if (s.find(c) != std::string::npos) { std::string t{s}; std::ranges::replace(t, c, l); ret.emplace_back(std::move(t)); } } return ret; } int main() { std::string s{"occurrences"}; fmt::print("Replace '{}': {}\n", 'c', replace(s, 'c')); fmt::print("Replace '{}': {}\n", 'z', replace(s, 'z')); } // Outputs: // // Replace 'c': ["oaaurrenaes", "obburrenbes", "oddurrendes"...] // Replace 'z': [] Edit: update on your comment below. however if I wanted to replace 1 character at a time for example in occurrences there are multiple "C" if i only wanted to replace 1 of them then run all outcomes of that then move onto the next "C" and replace all of them and so on, how could that be done? In that case, you'd need to iterate over your input string, doing the replacement to one char at a time, and adding each of those new strings to the return list. [Demo] for (const char l : alphabet) { if (s.find(c) != std::string::npos) { for (size_t i{0}; i < s.size(); ++i) { if (s[i] == c) { std::string t{s}; t[i] = l; ret.emplace_back(std::move(t)); } } } } // Outputs: // // Replace 'c': ["oacurrences", "ocaurrences", "occurrenaes"...] // Replace 'z': []
72,510,236
72,511,114
How to define class with overloaded methods for each std::variant alternative?
I have some std::variant classes, each with several alternatives, and I would like to define a visitor class template that takes a variant as its template parameter and will automatically define a pure virtual void operator()(T const&) const for each alternative T in the variant. This way, I can define subclasses that inherit from instantiations of these visitor template classes, and will be forced to override each method, defined as pure virtual in its respective base class. e.g. #include <variant> using VarA = std::variant<A1, A2, /* ... more alternatives ... */>; using VarB = std::variant<B1, B2, /* ... more alternatives ... */>; struct VarAVisitor : Visitor<VarA> { // Must override 'void operator()(T const&) const' for each alternative type 'T' in VarA }; struct VarBVisitor : Visitor<VarB> { // Must override 'void operator()(T const&) const' for each alternative type 'T' in VarB }; Basically, I am asking how would I implement the Visitor class template in the above example?
After some some googling and lots of trial and error, I managed to come up with something that does what I want. I'm sharing the solution here for anyone else who comes across the same issue. Here is a proof of concept. #include <iostream> #include <variant> template <typename> class Test { }; using Foo = std::variant< Test<struct A>, Test<struct B>, Test<struct C>, Test<struct D> >; using Bar = std::variant< Test<struct E>, Test<struct F>, Test<struct G>, Test<struct H>, Test<struct I>, Test<struct J>, Test<struct K>, Test<struct L> >; template <typename T> struct DefineVirtualFunctor { virtual int operator()(T const&) const = 0; }; template <template <typename> typename Modifier, typename... Rest> struct ForEach { }; template <template <typename> typename Modifier, typename T, typename... Rest> struct ForEach<Modifier, T, Rest...> : Modifier<T>, ForEach<Modifier, Rest...> { }; template <typename Variant> struct Visitor; template <typename... Alts> struct Visitor<std::variant<Alts...>> : ForEach<DefineVirtualFunctor, Alts...> { }; struct FooVisitor final : Visitor<Foo> { int operator()(Test<A> const&) const override { return 0; } int operator()(Test<B> const&) const override { return 1; } int operator()(Test<C> const&) const override { return 2; } int operator()(Test<D> const&) const override { return 3; } }; struct BarVisitor final : Visitor<Bar> { int operator()(Test<E> const&) const override { return 4; } int operator()(Test<F> const&) const override { return 5; } int operator()(Test<G> const&) const override { return 6; } int operator()(Test<H> const&) const override { return 7; } int operator()(Test<I> const&) const override { return 8; } int operator()(Test<J> const&) const override { return 9; } int operator()(Test<K> const&) const override { return 10; } int operator()(Test<L> const&) const override { return 11; } }; int main(int argc, char const* argv[]) { Foo foo; Bar bar; switch (argc) { case 0: foo = Foo{ std::in_place_index<0> }; break; case 1: foo = Foo{ std::in_place_index<1> }; break; case 2: foo = Foo{ std::in_place_index<2> }; break; default: foo = Foo{ std::in_place_index<3> }; break; } switch (argc) { case 0: bar = Bar{ std::in_place_index<0> }; break; case 1: bar = Bar{ std::in_place_index<1> }; break; case 2: bar = Bar{ std::in_place_index<2> }; break; case 3: bar = Bar{ std::in_place_index<3> }; break; case 4: bar = Bar{ std::in_place_index<4> }; break; case 5: bar = Bar{ std::in_place_index<5> }; break; case 6: bar = Bar{ std::in_place_index<6> }; break; default: bar = Bar{ std::in_place_index<7> }; break; } std::cout << std::visit(FooVisitor{ }, foo) << "\n"; std::cout << std::visit(BarVisitor{ }, bar) << "\n"; return 0; } As you can see, the Visitor class template accepts a std::variant type as a template parameter, from which it will define an interface that must be implemented in any child classes that inherit from the template class instantiation. If, in a child class, you happen to forget to override one of the pure virtual methods, you will get an error like the following. $ g++ -std=c++17 -o example example.cc example.cc: In function ‘int main(int, const char**)’: example.cc:87:41: error: invalid cast to abstract class type ‘BarVisitor’ 87 | std::cout << std::visit(BarVisitor{ }, bar) << "\n"; | ^ example.cc:51:8: note: because the following virtual functions are pure within ‘BarVisitor’: 51 | struct BarVisitor final : Visitor<Bar> | ^~~~~~~~~~ example.cc:29:17: note: ‘int DefineVirtualFunctor<T>::operator()(const T&) const [with T = Test<J>]’ 29 | virtual int operator()(T const&) const = 0; | ^~~~~~~~ This is much easier to understand than the error messages that the compiler usually generates when using std::visit().
72,510,589
72,510,732
A temporary object in range-based for-loop
In Range-based for loop on a temporary range, Barry mentioned that the following is not affected by the destroyed temporary object, and I tested member v indeed exists throughout the for-loop (as the destructor ~X didn't get called throughout the for-loop). What is the explanation? struct X { std::vector<int> v; ~X() { } }; X foo() { return X(); } for (auto e : foo().v) { // ok! }
This is an obscure form of temporary lifetime extension. Normally you have to bind the temporary directly to the reference for it to work (e.g. for (auto x : foo())), but according to cppreference, this effect propagates through: parentheses ( ) (grouping, not a function call), array access [ ] (not overloaded; must use an array and not a pointer), member access ., .*, ternary operator ? :, comma operator , (not overloaded), any cast that doesn't involve a "user-defined conversion" (presumably uses no constructors nor conversion operators) I.e. if a.b is bound to a reference, the lifetime of a is extended.
72,510,636
72,524,194
Parametrized tests with parametrized SetUp()/TearDown()
I have a test fixture that shares most of the test code. The variations are mostly from a parameter value. I would like to create SetUp() / TearDown() for them, but they (obviously) can't be called with a parameter. What would the best strategy to use SetUp() / TearDown() mechanisms while avoiding code duplication? This is my original code : class FileToolsTest : public testing::Test { protected: void TestReadAndWrite(const wstring& filename, const wstring& content) { FileTools::RemoveFile(filename); // Test code there ok = FileTools::RemoveFile(filename); ASSERT_EQ(true, ok); } }; //------------------------------------------------------------------------- TEST_F(FileToolsTest, ReadAndWrite_case1) { const wstring testFilename = L"testfile"; const wstring testContent = L"This\nis\ndummy\ndata"; TestReadAndWrite(testFilename, testContent); } TEST_F(FileToolsTest, ReadAndWrite_case2) { const wstring testFilename = L"testfíle"; const wstring testContent = L"This\nis\ndummy\n\nuníc@de datã éééé"; TestReadAndWrite(testFilename, testContent); } TEST_F(FileToolsTest, Write_case3) { const wstring testFilename = L"Micka\x00ebl/fileWithUnicodeFolderInPath2.txt"; if (FileTools::FileExists(testFilename)) { const bool ok = FileTools::RemoveFile(testFilename); ASSERT_TRUE(ok); } // Test code there FileTools::RemoveFile(testFilename); } As you can see, ::RemoveFile() is duplicated between TestReadAndWrite() and Write_case3(), both at test start and test end.
The example of Value-Parameterized Test. #include <string> #include <gtest/gtest.h> struct FileTools { static bool RemoveFile(const std::wstring&); }; struct FileToolsTestParam { const std::wstring testFilename; const std::wstring testContent; } kFileToolsTestParam[] = { { L"testfile", L"This\nis\ndummy\ndata" }, { L"testfíle", L"This\nis\ndummy\n\nuníc@de datã éééé" } }; class FileToolsTest : public testing::TestWithParam<FileToolsTestParam> { protected: void SetUp() override { const auto& param = GetParam(); FileTools::RemoveFile(param.testFilename); } void TearDown() override { const auto& param = GetParam(); const bool ok = FileTools::RemoveFile(param.testContent); ASSERT_EQ(true, ok); } }; INSTANTIATE_TEST_SUITE_P(FileTools, FileToolsTest, testing::ValuesIn(kFileToolsTestParam)); TEST_P(FileToolsTest, ReadAndWrite) { // Test code there }
72,510,822
74,018,151
Cannot load Qt5Compat.GraphicalEffects module in Qt 6.3
I'm using the Qt 5 Core Compatibility APIs in my Qt 6 applications. In particular, I need the QtGraphicalEffects module in my Qt Quick Scene. This is the full code of my main.qml file: import QtQuick import QtQuick.Window import Qt5Compat.GraphicalEffects Window { width: 640 height: 480 visible: true title: qsTr("Hello World") Item { width: 300 height: 300 Image { id: bug source: "images/bug.jpg" sourceSize: Qt.size(parent.width, parent.height) smooth: true visible: false } Image { id: mask source: "images/butterfly.png" sourceSize: Qt.size(parent.width, parent.height) smooth: true visible: false } OpacityMask { anchors.fill: bug source: bug maskSource: mask } } } This runs fine with Qt 6.2.4 (installed via the Qt Maintenance Tool). However with Qt 6.3.0, I get the following error: QQmlApplicationEngine failed to load component qrc:/main.qml:3:1: Cannot load library C:\Qt\6.3.0\msvc2019_64\qml\Qt5Compat\GraphicalEffects\qtgraphicaleffectsplugind.dll: The specified procedure could not be found. I verified that the file C:\Qt\6.3.0\msvc2019_64\qml\Qt5Compat\GraphicalEffects\qtgraphicaleffectsplugind.dll actually exists and made sure that the Qt 5 Compatibility module is installed for my Qt version. I've also tried to upgrade to the Qt 6.4.0 alpha release (again making sure that the compatibility module is installed) and with that I get a slightly different error: QQmlApplicationEngine failed to load component qrc:/main.qml:31:9: Type OpacityMask unavailable qrc:/qt-project.org/imports/Qt5Compat/GraphicalEffects/OpacityMask.qml:41:1: Cannot load library C:\Qt\6.4.0\msvc2019_64\qml\Qt5Compat\GraphicalEffects\private\qtgraphicaleffectsprivateplugind.dll: The specified module could not be found. What could be the cause of this issue? Has anything changed since Qt 6.3.0 regarding the compatibility module?
As this thread said, You need install Shader tools module after Qt 6.4. Install it by MaintenanceTool, then it will be ok.
72,511,182
72,511,228
Error while loading shared libraries when running executable
When I make the Makefile everything works fine, I get a library in the directory dir. And when I run "Make test" I get a testfile that I want to run. But when I want to run this file I get this weird error: ./programma: error while loading shared libraries: libprogramma.so: cannot open shared object file: No such file or directory. I have tried running the program on both WSL and Linux, but nothing makes this error go away. Can anyone help me? Here I have my Makefile which makes the library and the executable: INC_DIR = include SRC_DIR = src SOURCES = $(sort $(shell find $(SRC_DIR) -name '*.cc')) OBJECTS = $(SOURCES:.cc=.o) DEPS = $(OBJECTS:.o=.d) TARGET = programma CXX = g++ CFLAGS = -Wall -Wextra -Wpedantic -std=c++11 CPPFLAGS = $(addprefix -I, $(INC_DIR)) .PHONY: all clean debug release release: CFLAGS += -O3 -DNDEBUG release: all debug: CFLAGS += -O0 -DDEBUG -ggdb3 debug: all all: $(TARGET) clean: rm -f $(OBJECTS) $(DEPS) lib/*.so programma *.d $(TARGET): $(OBJECTS) $(CXX) $(CFLAGS) $(CPPFLAGS) -fPIC -shared -o lib/lib$@.so $^ -include $(DEPS) %.o: %.cc $(CXX) $(CFLAGS) $(CPPFLAGS) -fPIC -MMD -o $@ -c $< test: $(CXX) $(CFLAGS) -L./lib $(CPPFLAGS) -MMD -o programma tests/main.cc -l$(TARGET)
Executables on Linux don't look for shared libraries in the directory they're located in, at least by default. You can either fix that at link-time, by passing -Wl,-rpath='$ORIGIN', or at runtime, by setting LD_LIBRARY_PATH env variable to the directory with the library. (LD_LIBRARY_PATH=path/to/lib ./programma)
72,511,203
72,512,191
How to convert an arbitrary length unsigned int array to a base 10 string representation?
I am currently working on an arbitrary size integer library for learning purposes. Each number is represented as uint32_t *number_segments. I have functional arithmetic operations, and the ability to print the raw bits of my number. However, I have struggled to find any information on how I could convert my arbitrarily long array of uint32 into the correct, and also arbitrarily long base 10 representation as a string. Essentially I need a function along the lines of: std::string uint32_array_to_string(uint32_t *n, size_t n_length); Any pointers in the right direction would be greatly appreciated, thank you.
You do it the same way as you do with a single uint64_t except on a larger scale (bringing this into modern c++ is left for the reader): char * to_str(uint64_t x) { static char buf[23] = {0}; // leave space for a minus sign added by the caller char *p = &buf[22]; do { *--p = '0' + (x % 10); x /= 10; } while(x > 0); return p; } The function fills a buffer from the end with the lowest digits and divides the number by 10 in each step and then returns a pointer to the first digit. Now with big nums you can't use a static buffer but have to adjust the buffer size to the size of your number. You probably want to return a std::string and creating the number in reverse and then copying it into a result string is the way to go. You also have to deal with negative numbers. Since a long division of a big number is expensive you probably don't want to divide by 10 in the loop. Rather divide by 1'000'000'000 and convert the remainder into 9 digits. This should be the largest power of 10 you can do long division by a single integer, not bigum / bignum. Might be you can only do 10'000 if you don't use uint64_t in the division.
72,511,217
72,511,247
How Can I instantiate a class template without a cast
I would like to run the first instantiation instead of the second, but the compiler takes the arguments as integers and returns errors. Note that the use of optional is to allow the object to receive a boost::none (C++ version of python's None). #include <boost/multiprecision/cpp_int.hpp> #include <boost/optional.hpp> using namespace boost::multiprecision; template<class T> struct Point { explicit Point(T x, T y): x (x), y (y){} T x; T y; }; typedef boost::optional<int128_t> oint128_t; int main(){ // Point<oint128_t> P(90, 5); // this fails Point<oint128_t> Q((oint128_t) 91, (oint128_t) 31); // this works }
You can always put the explicit casts inside of the Point constructor. template<typename S> explicit Point(S x, S y): x(T(x)), y(T(y)) {} But I suspect that doing so will introduce more confusing type errors in the long run. My recommendation is to explicitly call the boost::optional constructor like you're supposed to. T is not meant to be an instance of boost::optional<T>. The cast you're invoking is actually calling a converting constructor and making a new object; you're just making it look like a conversion is taking place.
72,511,236
72,511,237
DirectSound crashes due to a read access violation when calling IDirectSoundBuffer8::Play (inside LFQueuePut, a dsound.dll internal function)
I am working on a game, and am sporadically observing crashes inside of dsound.dll. This happens right after creating a IDirectSoundBuffer8 audio buffer, when calling the Play method on it. At this point I haven't written to the buffer or done anything to the sound system besides creating the audio device, setting the cooperative level, creating the audio buffer and starting to play. All values returned by DirectSound indicate success, and even when I explicitely query the buffer for things like DSERR_BUFFERLOST, no sign of error is indicated. This is the callstack:
After hunting this bug down by process of elimination, it seems to be a Windows/Driver issue. In short: DirectSound may crash your application if you reserve 10 TiB of address space. I'm using this address space for a debug allocator that helps hunting down use-after frees, and for some reason DirectSound seems to interact with this allocation. I was able to produce the following repro, that crashes about every other execution (although I have also seen crash rates as low as 5% in my application). I was able to reproduced this on 2 PCs, and one other person who tried it was also able to reproduce. You have to execute this code in a debugger though, because otherwise you won't be able to distinguish a crash due to access violation from the execution finishing normally: #include "dsound.h" #include "assert.h" //link against user32.lib, dsound.lib and dxguid.lib LRESULT CALLBACK WindowProc(HWND handle, UINT message, WPARAM wParam, LPARAM lParam){ return DefWindowProcW(handle, message, wParam, lParam); } void main(){ VirtualAlloc(nullptr, 10llu * 1024 * 1024 * 1024 * 1024, MEM_RESERVE, PAGE_NOACCESS); //if you comment this out, it won't crash auto application_instance = GetModuleHandle(NULL); WNDCLASSEXW window_class; ZeroMemory(&window_class, sizeof(window_class)); window_class.cbSize = sizeof(window_class); window_class.style = CS_HREDRAW|CS_VREDRAW; window_class.lpfnWndProc = WindowProc; window_class.hInstance = application_instance; window_class.lpszClassName = L"TEST_WINDOW_CLASS"; if(RegisterClassExW(&window_class) == 0) assert(false); auto window_handle = CreateWindowExW(0, window_class.lpszClassName, L"smashing", WS_OVERLAPPEDWINDOW|WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, 100, 100, 0, 0, application_instance, 0); IDirectSound8* active_device = nullptr; IDirectSoundBuffer8* active_buffer = nullptr; if(DirectSoundCreate8(NULL, &active_device, NULL) != DS_OK) assert(false); if(active_device->SetCooperativeLevel(window_handle, DSSCL_PRIORITY) != DS_OK) assert(false); WAVEFORMATEX format_description; format_description.wFormatTag = WAVE_FORMAT_PCM; format_description.nChannels = 2; format_description.nSamplesPerSec = 44100; format_description.nAvgBytesPerSec = 44100 * 4; format_description.nBlockAlign = 4; format_description.wBitsPerSample = 16; format_description.cbSize = 0; DSBUFFERDESC buffer_description; buffer_description.dwSize = sizeof(buffer_description); buffer_description.dwFlags = DSBCAPS_GETCURRENTPOSITION2; buffer_description.dwBufferBytes = 44100 * 4; buffer_description.dwReserved = 0; buffer_description.lpwfxFormat = &format_description; buffer_description.guid3DAlgorithm = DS3DALG_DEFAULT; LPDIRECTSOUNDBUFFER buffer_before_cast = nullptr; if(active_device->CreateSoundBuffer(&buffer_description, &buffer_before_cast, NULL) != DS_OK) assert(false); if(buffer_before_cast->QueryInterface(IID_IDirectSoundBuffer8, (void **)&active_buffer) != S_OK) assert(false); if(active_buffer->Play(0, 0, DSBPLAY_LOOPING) != DS_OK) //this is the place where it crashes more often than not assert(false); } I have not found a solution to this issue, and since there is no real way to report such a bug to microsoft with any hopes of it actually getting fixed, I decided to put this on Stackoverflow so that other people hopefully don't waste as much time on it as I have. I will probably try using WASAPI instead next.
72,511,490
72,521,236
c++ statically assert that a function is never called
For some complicated reasons I want to create default constructor (alongside my normal constructors) that always throws. I want it to be there, but I also want it never to be called. It is pretty obvious that during runtime I can check for that thrown exception and for example terminate program when I catch it, but the ideal solution would be to have it checked during compilation. So my question is: can I statically assert somehow that a function will never be called? I've looked at functions in <type_traits> but I don't see anything there that would help me. Is there some c++ dark magic that I could use to achieve my goal? I don't have a code example, because what would even be in there? PS. Yes. I am sure that I want to have a function and disallow everybody of calling it. As I stated previously reasons for that are complicated and irrelevant to my question. EDIT. I can't delete this constructor or make it private. It has to be accessible for deriving classes, but they shouldn't call it. I have a case of virtual inheritance and want to "allow" calling this constructor by directly virtually derived classes (they won't call it, but c++ still requires it to be there), but no in any other classes deeper in inheritance chain. EDIT 2. As requested I give a simplified example of my code. #include <stdexcept> class Base { protected: Base() { throw std::logic_error{"Can't be called"}; } Base(int); // proper constructor private: // some members initialized by Base(int) }; class Left: virtual public Base { protected: Left(int) {} // ^ initialize members of Left, but does not call Base()! // Though it seems that it implicitly does, Base() is never actually called. }; class Right: virtual public Base { protected: Right(int) {} // The same as in Left }; class Bottom: public Left, public Right { public: Bottom(int b, int l, int r): Base{b}, Left{l}, Right{r} {} // ^ Explicitly calling constructors of Base, Left, Right. // If I forget about calling Base(int) it silently passes // and throws during runtime. Can I prevent this? }; EDIT 3. Added body to Left's and Right's constructors, so that they implicitly "call" Base().
As you've stated in your comments that you never want to instatiate Base, Left or Right object, then you should make them abstract, even by some empty method: class Base { private: // ... virtual void DefineIfNonAbstract() = 0; }; class Bottom: public Left, public Right { void DefineIfNonAbstract() final {}; // ... }; Trust your compiler. When it sees that DefineIfNonAbstract is private and none of its parents implemented it, it's not going to put it into a vtable. You're Bottom class is already 16 bytes in your example for both gcc and clang (likely a pointer for each virtual inheritance). Adding the abstract method doesn't change that. In the comments you expressed concern that this might not be safe, and sent me a link to CppCoreGuidelines: I.25: Prefer empty abstract classes as interfaces to class hierarchies Reason Abstract classes that are empty (have no non-static member data) are more likely to be stable than base classes with state. They're referring to design choices here, not whether it causes undefined behaviour or something. In our case we're actually enforcing your design, not changing it. The whole thing likely needs a serious rework in design. Inheritance in general is rarely a good choice - virtual inheritance even rarer.
72,511,624
72,511,653
C++ error: "pointer being freed was not allocated"
I never invoke free in my code, so I don't know why I'm getting this error. I wrote a program to find integer partitions of a number. It worked fine. Then I decided I wanted to try and use a pointer to the vector to avoid unnecessarily copying my std::vector<ints>'s between iterations of a loop. It compiles (using g++ -std=c++11 -o main main.cpp). When I execute the program, I get this error message: main(5629,0x115dcfe00) malloc: *** error for object 0x7ffed1c05a30: pointer being freed was not allocated main(5629,0x115dcfe00) malloc: *** set a breakpoint in malloc_error_break to debug Why am I getting this error? Thank you in advance. Here's my code: #include <stdexcept> #include <iostream> #include <vector> #include <algorithm> #include <numeric> using std::cout; using std::endl; using std::vector; typedef vector<int> ints; void print_ints(vector<int>); void print_ints_vec(vector<vector<int>>); void int_part(int, vector<vector<int>>&); int main() { vector<vector<int>> partition; int_part(5, partition); print_ints_vec(partition); return 0; } void int_part(int sum, vector<vector<int>>& res) { vector<int> init_xs = vector<int>{sum}; vector<int>* xs = &init_xs; // POINTER INITIALIZED TO vector<int> int current_sum = sum; while (true) { current_sum = accumulate(xs->begin(), xs->end(), 0); // if (current_sum == sum) { res.push_back(*xs); // vector<int> next_xs; vector<int>::iterator it = find(xs->begin(), xs->end(), 1); // if (it == xs->begin()) return; // copy(xs->begin(), it, back_inserter(next_xs)); // next_xs[next_xs.size() - 1] -= 1; // xs = &next_xs; // POINTER REASSIGNED TO ANOTHER vector<int> } else { int tail = xs->back(); // int diff = sum - current_sum; int m = std::min(tail, sum - tail); int next_tail = current_sum + m > sum ? diff : m; xs->push_back(next_tail); // } } } void print_ints(ints v) // PRINT UTILITY { cout << "[ "; for (const int& n : v) { cout << n << "; "; } cout << "]" << endl; } void print_ints_vec(vector<ints> v) // PRINT UTILITY { cout << "[ \n"; for (const vector<int>& xs : v) { cout << " "; print_ints(xs); } cout << "]" << endl; }
if (current_sum == sum) { // ... vector<int> next_xs; As you can see here: next_xs is declared inside the if statement. When the if statement finishes, next_xs gets destroyed. That's how locally-declared object, in automatic scope, work. xs = &next_xs; A pointer to this object is saved here. Immediately afterwards the if statement ends, and next_xs gets destroyed. You end up with a pointer to a destroyed object. Subsequent code attempts to dereference it, and access the destroyed object. This results in undefined behavior, and that's the reason for the crash.
72,511,754
72,511,972
Safely type punning POD-like structures in-place in C++20?
There have been multiple questions asking about mmap and accessing structures in the shared memory while not invoking UB by breaking the strict aliasing rule or violating object lifetimes. mmap and C++ strict aliasing rules Dealing with undefined behavior when using reinterpret_cast in a memory mapping How to properly access mapped memory without undefined behavior in C++ With consensus that this is not generally possible without copying the data. More generally, over the years here, I have seen countless code snippets involving reinterpret_cast (or worse) for (de)serialization, breaking those rules. I always recommended std::memcpy while claiming that the compiler will elide those copies. Can we do better now? I would like to clarify what is the correct approach to simply interpret a bunch of bytes as another POD type w̲i̲t̲h̲o̲u̲t̲ copying the data in C++20? There was a proposal P0593R6 which to my knowledge got accepted into C++20. Based on reading that, I believe the following code is safe: template <class T> T* pune(void* ptr) { // Guaranteed O(1) initialization without overwritting the data. auto* dest = new (ptr) std::byte[sizeof(T)]; // There is an implicitly created T, so cast is valid. return reinterpret_cast<T*>(dest); } #include <cstring> #include <array> #include <fmt/core.h> struct Foo { int x; float y; }; auto get_buffer() { Foo foo{.x = 10, .y = 5.0}; std::array<std::byte, sizeof(Foo)> buff; std::memcpy(buff.data(), &foo, sizeof(foo)); return buff; } int main() { // Imagine the buffer came from a file or mmaped memory, // compiler does not see the memcpy above. auto buff = get_buffer(); // There is alive Foo as long as buff lives and // no new objects are created in there. auto* new_foo = pune<Foo>(buff.data()); fmt::print("Foo::x={}\n", new_foo->x); fmt::print("Foo::y={}\n", new_foo->y); } Live demo godbolt. Is this really safe? Is pune really O(1)? EDIT Okay, how about using memmove and still rely on the compiler to do this in O(1)? template <class T> T* pune(void* ptr) { void* dest = new (ptr) std::byte[sizeof(T)]; auto* p = reinterpret_cast<T*>(std::memmove(dest,ptr,sizeof(T))); return std::launder(p); }
Guaranteed O(1) initialization without overwritting the data. Not so much. Indeed, P0593 explicitly mentions that this will not work: Symmetrically, when the float object is created, the object has an indeterminate value, and therefore any attempt to load its value results in undefined behavior. [basic.indent] contains the details: When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced Placement new "obtains storage" for the object. Since no initialization is performed, it has an "indeterminate value". Attempting to read that will yield undefined behavior. As of yet, there is no mechanism in C++ that allows you to take memory which had one object in it and read its values as another object. However, mmap could be considered (by the implementation) to implicitly create objects in the storage it returns. As such, you could just cast such a pointer to an implicit lifetime type (not POD, which no longer exists as a category) and read the values from there.
72,511,936
72,512,047
Is there a value of type `double`, `K`, such that `K * K == 3.0`?
Is there a value of type double (IEEE 64-bit float / binary64), K, such that K * K == 3.0? (The irrational number is of course "square root of 3") I tried: static constexpr double Sqrt3 = 1.732050807568877293527446341505872366942805253810380628055806; static_assert(Sqrt3 * Sqrt3 == 3.0); but the static assert fails. (I'm guessing neither the next higher nor next lower floating-point representable number square to 3.0 after rounding? Or is the parser of the floating point literal being stupid? Or is it doable in IEEE standard but fast math optimizations are messing it up?) I think the digits are right: $ python >>> N = 1732050807568877293527446341505872366942805253810380628055806 >>> N * N 2999999999999999999999999999999999999999999999999999999999996\ 607078976886330406910974461358291614910225958586655450309636 Update I've discovered that: static_assert(Sqrt3 * Sqrt3 < 3.0); // pass static_assert(Sqrt3 * Sqrt3 > 2.999999999999999); // pass static_assert(Sqrt3 * Sqrt3 > 2.9999999999999999); // fail So the literal must produce the next lower value. I guess I need to check the next higher value. Could bit-dump the representation maybe and then increment the last bit of the mantissa. Update 2 For posterity: I wound up going with this for the Sqrt3 constant and the test: static constexpr double Sqrt3 = 1.7320508075688772; static_assert(0x1.BB67AE8584CAAP+0 == 1.7320508075688772); static_assert(Sqrt3 * Sqrt3 == 2.9999999999999996);
Testing with Python is valid I think, since both use the IEEE-754 representation for doubles along with the rules for operations on same. The closest possible double to the square root of 3 is slightly low. >>> Sqrt3 = 3**0.5 >>> Sqrt3*Sqrt3 2.9999999999999996 The next available value is too high. >>> import numpy as np >>> Sqrt3p = np.nextafter(Sqrt3,999) >>> Sqrt3p*Sqrt3p 3.0000000000000004 If you could split the difference, you'd have it. >>> Sqrt3*Sqrt3p 3.0
72,511,999
72,524,080
Pass context through composed promises in KJ
Playing with the KJ library, I wrote a small TCP servers that reads a "PING" and responds a "PONG". I managed to compose the promises like this: char buffer[4]; kj::Own<kj::AsyncIoStream> clientStream; addr->listen()->accept() .then([&buffer, &clientStream](kj::Own<kj::AsyncIoStream> stream) { clientStream = kj::mv(stream); return clientStream->tryRead(buffer, 4, 4); }).then([&buffer, &clientStream](size_t read) { KJ_LOG(INFO, kj::str("Received", read, " bytes: ", buffer)); return clientStream->write("PONG", 4); }).wait(waitScope); I had to keep buffer out of the promises and pass a reference to it. This means that buffer has to stay in scope until the last promise finishes. That's the case here, but is there a solution in case it isn't? Same thing for clientStream: I had to declare it before, then wait until I receives it from accept(), and at this point move it outside and use the reference to it. Is there a better way to do it? Say like a way to pass some kind of context from promise to promise, always owned by the promises and therefore not having to stay "outside"?
It seems your problem is that your second lambda wants access to the scope of the first lambda, but the way you've organised things prevents that. You've worked around that by just adding variables to their shared "global" scope. Instead, you could put the second lambda inside the first, something like this: addr->listen()->accept() .then([](kj::Own<kj::AsyncIoStream> stream) { auto buffer = kj::heapArray<char>(4); auto promise = stream->tryRead(buffer.begin(),4,4); return promise.then([stream=kj::mv(stream), buffer=kj::mv(buffer)] (size_t read) mutable { KJ_LOG(INFO, kj::str("Received", read, " bytes: ", buffer)); return stream->write("PONG", 4); }); }).wait(waitScope);
72,512,383
72,512,448
Getting unhandled exception in double linked list in C++
I created a doubly-linked list in C++. Everything works great if I insert a node at the beginning of the list or if I just insert a node at the end of the list; but, when I insert a node at the beginning and then try to insert a node at the end, I get a null pointer error! Here is the code and the problem is in the InserAtEnd function #include <iostream> using namespace std; struct Node { int data; Node* prev; Node* next; }; struct MyList { Node* head; Node* tail; }; bool IsEmpty(MyList list) { if (list.head == nullptr) return true; else return false; } void Insert(MyList& list, int data) { Node* node = new Node(); node->data = data; node->prev = nullptr; node->next = list.head; //node->next points to NULL if (list.head == nullptr) { list.head = node; node->prev = nullptr; } else { //insert the new node at the beginning of the list list.head->prev = node; list.head = node; node->prev = nullptr; } } // Insert node at end of list void InsertAtEnd(MyList& list, int data) { Node* node = new Node(); node->data = data; node->next = nullptr; node->prev = nullptr; if (list.head == nullptr) { // Empty list list.head = node; list.tail = node; } else { list.tail->next = node; node->prev = list.tail; list.tail = node; } } //Traverse the list from the head void PrintAll(const MyList& list) { Node* temp = list.head; if (temp == nullptr) { cout << "list is empty" << endl; } else { while (temp != nullptr) { cout << temp->data << endl; temp = temp->next; } cout << "*************************************" << endl; } } Node* Search(const MyList& list, int key) { Node* temp = list.head; while (temp != nullptr && temp->data != key) { temp = temp->next; } return temp; } void Delete(MyList& list, int key) { Node* temp = Search(list, key); //call search() if (temp != nullptr) { if (temp->prev != nullptr) { temp->prev->next = temp->next; } else { list.head = temp->next; } if (temp->next != nullptr) { temp->next->prev = temp->prev; } } } int main() { MyList list; list.head = nullptr; //initialize the linked-list list.tail = nullptr; if (IsEmpty(list)) cout << "List is empty" << endl; Insert(list, 10); PrintAll(list); /* Insert(list, 20); Insert(list, 30); Insert(list, 40); */ // Insert at end cout << "Now insert at end" << endl; InsertAtEnd(list, 70); InsertAtEnd(list, 45); InsertAtEnd(list, 59); InsertAtEnd(list, 12); InsertAtEnd(list, 33); PrintAll(list); /* int x = 24; Node* result = Search(list, x); if (result == nullptr) cout << "Cannot find " << x << endl; else cout << "Found " << result->data << endl; Delete(list, 200); PrintAll(list); Delete(list, 10); PrintAll(list); Delete(list, 40); PrintAll(list); Delete(list, 20); PrintAll(list); Delete(list, 30); PrintAll(list); */ return 0; }
the problem is in the InserAtEnd function How do you know? In fact the problem isn't in InserAtEnd but in Insert: You never set list.tail. Tip: use Node **tail = &head; for a more efficient MyList and add member initializers and a Constructor. This is C++ with classes. Use member functions.
72,512,432
72,512,563
Is it possible to pass an object as a parameter to a function without copying it?
Look at this code #include <iostream> #include <vector> class Entity { public: Entity(int x, int y) : x(x), y(y) {std::cout << "DEFAULT\n";} Entity(const Entity& that) { std::cout << "COPY\n"; this->x = that.x; this->y = that.y; } Entity(Entity&& that) { std::cout << "MOVE\n"; this->x = that.x; this->y = that.y; } private: int x, y; }; class List { public: List(){vec.reserve(25);} void Add(Entity &&en) { vec.emplace_back(std::move(en)); //invokes the move constructor } void Add(int x, int y) { vec.emplace_back(x, y); } private: std::vector<Entity> vec; }; int main() { List L; L.Add(Entity(10, 20)); L.Add(100, 200); return 0; } I've defined a vector of type Entity inside the List class and provided a function Add() to access this vector. Using the Add(Entity&&) overload invokes the move constructor meanwhile using the other overload, Add(int, int) doesn't trigger anything but the default constructor of Entity. I know why Add(int, int) doesn't invoke copy or move constructors. Because std::vector::emplace_back() utilizes the placement new operator to create the object in-place. But I don't understand the behavior of the Add(Entity&&) function. Why is the object getting moved? Is it because it has been created outside of the stack frame of the calling function? If so and if it's possible, how to avoid moving the object? If I'm totally wrong, please clarify it for me. Thanks in advance.
When you call L.Add(Entity(10, 20)); the following operations happen: Entity(10, 20) creates a temporary List::add is called with temporary std::move() makes the temporary movable vector::emplace_back is called with the temporary vector resizes vector calls construct_at with the temporary construct_at calls placement new with the temporary placement new copies/moves the temporary into place Now the compiler elides all of that except these three things: Entity(10, 20) creates a temporary vector resizes placement new copies/moves constructs the temporary Unfortunately the compiler does not elide the copy/move construction in the new call. Unlike Entity(Entity(10, 20)), where the copy/move construct is optimized out, the new(addr) Entity(Entity(10, 20)) your code basically comes to does not collapse in the same way. It would be nice if the compiler would (could?) optimize the extra copy/move construct away but it's not defined for new to do that.
72,512,492
72,513,551
How to scale without changing object translated position
I have a problem to scale an object without changing translated position. I tried to apply translate and scaling using keybind for my car but when i click the keybind for scaling, only my body repositioned it self but the car's tire scaled at the fixed position i translated. Below is my code: #include <windows.h> #include <gl/glut.h> #include <stdlib.h> #include <math.h> #include <string.h> const float steps = 100; const float angle = 3.1415926 * 2.0 / steps; float m = 0; float s = 1; void wheel(float x, float y) { float w; glBegin(GL_POLYGON); glColor3ub(0, 0, 0); for (int i = 0; i < 360; i++) { w = (i*3.1416 / 180); glVertex2f(x + 0.04 * s * cos(w), y + 0.04 * s * sin(w)); } glEnd(); } void display() { glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_QUADS); glColor3ub(48, 51, 64); glVertex2f(-1, 1); glColor3ub(48, 51, 64); glVertex2f(1, 1); glColor3ub(11, 11, 16); glVertex2f(1, -0.1); glColor3ub(11, 11, 16); glVertex2f(-1, -0.1); glEnd(); //[2] Floor glBegin(GL_QUADS); glColor3ub(51, 25, 0); glVertex2f(-1, -0.1); glColor3ub(51, 25, 0); glVertex2f(1, -0.1); glColor3ub(102, 51, 0); glVertex2f(1, -1); glColor3ub(102, 51, 0); glVertex2f(-1, -1); glEnd(); //[3-1] Road glBegin(GL_QUADS); glColor3ub(26, 26, 26); glVertex2f(-1, -0.2); glColor3ub(26, 26, 26); glVertex2f(1, -0.2); glColor3ub(40, 40, 40); glVertex2f(1, -0.9); glColor3ub(40, 40, 40); glVertex2f(-1, -0.9); glEnd(); //[3-2] Road glBegin(GL_QUADS); glColor3ub(248, 210, 16); glVertex2f(-0.9, -0.52); glColor3ub(248, 210, 16); glVertex2f(-0.7, -0.52); glColor3ub(248, 210, 16); glVertex2f(-0.7, -0.58); glColor3ub(248, 210, 16); glVertex2f(-0.9, -0.58); glEnd(); //[4] Star glBegin(GL_POLYGON); glEnd(); //[5] Building glBegin(GL_POLYGON); glEnd(); //[6] Car glBegin(GL_POLYGON); glColor3ub(65, 105, 225); glVertex2f(m + (s * 0.50), s * -0.7); glVertex2f(m + (s * 0.52), s * -0.6); glVertex2f(m + (s * 0.80), s * -0.6); glVertex2f(m + (s * 0.86), s * -0.7); glVertex2f(m + (s * 0.86), s * -0.8); glVertex2f(m + (s * 0.44), s * -0.8); glVertex2f(m + (s * 0.44), s * -0.7); glVertex2f(m + (s * 0.50), s * -0.7); glEnd(); wheel(m + 0.52, -0.8); wheel(m + 0.76, -0.8); glFlush(); } void key(unsigned char key, int x, int y) { switch (key) { case 'A': case 'a': m = m - 0.1; break; case 'D': case 'd': m = m + 0.1; break; case 'Q': case 'q': s = s + 0.1; break; case 'E': case 'e': s = s - 0.1; break; } glutPostRedisplay(); } int main(int argc, char* argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(1000, 600); glutInitWindowPosition(0, 0); glutCreateWindow("Moving Car"); glutDisplayFunc(display); glutKeyboardFunc(key); glutMainLoop(); return 0; } I don't know how to make it scale at a fixed position after translating, I did try applying translate in the scaling part but it doesn't work.
Each glVertex is transformed by the current model view and projection matrix when it is specified. You have to scale the complete object (car and wheels) before any other transformation. Use glTranslatef and glScale to multiply the current matrix by a general scaling matrix, glPushMatrix to save the matrix on the matrix stack and glPopMatrix to restore the matrix from the matrix stack. e.g.: void wheel(float x, float y) { float w; glBegin(GL_POLYGON); glColor3ub(0, 0, 0); for (int i = 0; i < 360; i++) { w = (i*3.1416 / 180); glVertex2f(x + 0.04 * cos(w), y + 0.04 * sin(w)); } glEnd(); } glPushMatrix(); glTranslate(m, 0, 0); glScalef(s, s, 1); glBegin(GL_POLYGON); glColor3ub(65, 105, 225); glVertex2f(0.50, -0.7); glVertex2f(0.52, -0.6); glVertex2f(0.80, -0.6); glVertex2f(0.86, -0.7); glVertex2f(0.86, -0.8); glVertex2f(0.44, -0.8); glVertex2f(0.44, -0.7); glVertex2f(0.50, -0.7); glEnd(); wheel(0.52, -0.8); wheel(0.76, -0.8); glPopMatrix();
72,512,612
72,512,638
How to get pair from a map using key in C++
I have the following map: std::map<char, std::pair<int, int> > robots; I am using this function to populate the map given the input meets certain conditions: bool World::addRobot(int row, int col, char robot_name) { // This if block checks if the desired location is a valid 1 and keeps a track of all the robots already in the grid if (map_[row][col] == '1' && robots.find(robot_name) == robots.end()){ map_[row][col] = robot_name; robots.insert(make_pair(robot_name, std::make_pair(row, col))); } else{std::cout << "Invalid input" << std::endl;} return true; } Each robot name, which is just a single char, is saved with a pair of its location, which are just row/col coordinates. In the following function, I want to be able to retrieve & ethe location pairs given the robot name: std::pair<int, int> World::getRobot(char robot_name) { std::pair<int, int> location = robots.find(robot_name); return location; } But the name location is redlines with the following error message: No viable conversion from 'std::map<char, std::pair<int, int>>::iterator' (aka '_Rb_tree_iterator<std::pair<const char, std::pair<int, int>>>') to 'std::pair<int, int>' Where am I going wrong? How can I return the coordinate pairs from just the robot name?
An iterator for a map "points to" a std::pair<const KEY, VALUE>. For your map, the KEY is char and the VALUE is std::pair<int, int> So in your code, instead of: std::pair<int, int> location = robots.find(robot_name); you need to: std::pair<int, int> location = robots.find(robot_name)->second; Also, you need to check and see if the call to find fails to find the key you want. In that case the iterator will be equal to robots.end, and you'll have to deal with that: const auto it = robots.find(robot_name); if (it != robots.end()) { return it->second; } else { // Not found, do something else }
72,513,081
72,785,671
cv-qualifier propagation in structured binding
As quoted in dcl.struct.bind, Let cv denote the cv-qualifiers in the decl-specifier-seq. Designating the non-static data members of E as m 0 , m 1 , m 2 , ... (in declaration order), each v i is the name of an lvalue that refers to the member m i of e and whose type is cv T i , where T i is the declared type of that member; If I'm understanding correctly, the cv-qualifiers are propagated from the declartion of structured binding. Say I have a simple struct, struct Foo { int x; double y; }; Consider the two scenarios, const Foo f{1, 1.0}; auto& [x, y] = f; // static_assert(std::is_same<decltype(x), int>::value); // Fails! static_assert(std::is_same<decltype(x), const int>::value); // Succeeds Live Demo. Does the cv-qualifier of x come from the deduction auto? The second one, Foo f{1, 1.0}; const auto& [x, y] = f; const auto& rf = f; static_assert(std::is_same<decltype(x), const int>::value); // with const static_assert(std::is_same<decltype(rf.x), int>::value); // without const Live Demo. The result complies with the standard, which makes sense. My second question is is there any reason to propagate the cv-qualifiers, isn't it a kind of inconsistent (to the initialization a reference with auto)?
decltype has a special rule when the member of a class is named directly as an unparenthesized member access expression. Instead of producing the result it would usually if the expression was treated as an expression, it will result in the declared type of the member. So decltype(rf.x) gives int, because x is declared as int. You can force decltype to behave as it would for other expressions by putting extra parentheses (decltype((rf.x))), in which case it will give const int& since it is an lvalue expression and an access through a const reference. Similarly there are special rules for decltype if a structured binding is named directly (without parentheses), which is why you don't get const int& for decltype(x). However the rules for structured bindings take the type from the member access expression as an expression if the member is not a reference type, which is why const is propagated. At least that is the case since the post-C++20 resolution of CWG issue 2312 which intends to make the const propagation work correctly with mutable members. Before the resolution the type of the structured binding was actually specified to just be the declared type of the member with the cv-qualifiers of the structured binding declaration added, as you are quoting in your question. I might be missing some detail on what declared type refers to exactly, but it seems to me that this didn't actually specify x to have type const int& in your first snippet (and decltype hence also not const), although that seems to be how all compilers always handled that case and is also the only behavior that makes sense. Maybe it was another defect, silently or unintentionally fixed by CWG 2312. So, practically speaking, both rf.x and x in your example are const int lvalue expressions when you use them as expressions. The only oddity here is in how decltype behaves.
72,513,273
72,513,383
How can I trigger copy constructor of a parent templated class inside the child class
How can I call the copy constructor of the parent templated class inside the copy constructor of the child class? // Type your code here, or load an example. #include<vector> #include <iostream> template <typename T> class Parent { public: Parent() {}; const std::vector<T>& getDims() const { return m_dims; }; void setDims(const std::vector<T> dims) { m_dims = dims; }; Parent(const Parent& p) { m_dims = p.getDims(); }; private: std::vector<T> m_dims; }; template <typename T> class Child : public Parent<T> { public: Child() {}; const std::vector<T>& getCenter() const { return m_center; }; void setCenter(const std::vector<T> center) { m_center = center; }; Child(const Child& c) { m_center = c.getCenter(); // How can I trigger the copy constructor of the parent class // and copy m_dims instead of the following this->setDims(c.getDims()); } private: std::vector<T> m_center; }; int main(){ Child<int> child1; child1.setDims({3, 1, 1, 1}); // Parent function child1.setCenter({1, 2, 3, 4}); // Child function Child<int> child2 = child1; return 0; }
template <typename T> class Child : public Parent<T> { public: Child() {}; Child(const Child& c): Parent<T>(c) { m_center = c.getCenter(); } private: std::vector<T> m_center; }; Your base class is Parent<T> here.
72,513,282
72,513,306
Correlation Id and Message Id in IBM MQ
For a c++ and c program, I am trying to set a value for msgId or CorrelId for a particular message in IBM MQ, that will be later put to a topic. But there's an error of "Expression must be a modifiable L-value" for both the ids. I defined the ids as MQBYTE24 MsgId; MQBYTE24 CorrelId; and the MQMD is defined as default: MQMD md = {MQMD_DEFAULT}; I cannot use the #define directive as I am trying to single out a message to be put to a topic from the publisher's end. Receive all the messages for subscriber and check for the particular message. Is my approach of using correlIds or MsgIds correct or is there a better way for doing this?
I would expect you to have some code that looks like the following:- memcpy(md.CorrelId, CorrelId, MQ_MSG_ID_LENGTH); Please also remember that the message ID that you MQPUT to a topic does not end up at the subscribers. A new message ID is created for each copy of the published message that is given to each subscriber. You should use the Correlation ID instead to have it flow through to the subscriber, and ensure the subscribers are made correctly to receive the publishers correlation ID. Read IBM MQ Little Gem #31: Publisher's CorrelId for more information about this.
72,513,351
72,513,472
How to update values in C++ std::pair<int, int>
I have this function that returns the location of a robot (which is just a [row][col] pair of indices from a matrix): std::pair<int, int> World::getRobotLocation(char robot_name){ auto const & location = robots.find(robot_name); if (location == robots.end()) { std::cout << "Robot " << robot_name << " does not exist." << std::endl; } return location->second; } Below, I am trying to implement the move() function, which takes in the robot name, location and which direction to move and updates the position accordingly: std::string move(char robot, char direction) { // Get robot and its location std::pair<int, int> robot_location = std::pair<int, int> World::getRobotLocation(robot); // Get direction to move from user // if L, map_[row+1][col] // if D, map_[row][col+1] // if R, map_[row-1][col] // if U, map_[row][col+1] // According to user input, update the robot's location if (direction == 'L') { robot_location = robot_location[+1][] } else if (direction == 'D') { robot_location = robot_location[][-1] } else if (direction == 'R') { robot_location = robot_location[-1][] } else { robot_location = robot_location[][+1] } } In my variable robot_location, I am saving the location of that particular robot. How can I access the values of this std::pair<int, int> to be able to update them?
Your first function has a bug. It reports when a robot is not found, but still dereferences the end iterator, which causes undefined behavior. Instead, you should return a pointer, which is conditionally null: // Returns null if the robot is not found: std::pair<int, int>* World::getRobotLocation(char robot_name){ auto const location = robots.find(robot_name); if (location == robots.end()) { return nullptr; } return &location->second; } And in your other function, you check to see, if the pointer is not null, you update the value: // Returns true if move happens, // false otherwise. bool move(char robot, char direction) { auto const robot_location = World::getRobotLocation(robot); if (!robot_location) return false; switch (direction) { case 'L': { ++robot_location->first; } break; case 'D': { --robot_location->second; } break; case 'R': { --robot_location->first; } break; default: { ++robot_location->second; } break; } return true; }
72,513,631
72,516,141
Compile each cpp file in separate directory
The results for this topic strangely all did not work. Finally I found a variant that is logical for me and works from the same order. CC := g++ CFLAGS := -g -Wall objects = test helloworld all: $(objects) $(objects): %: %.cpp $(CC) $(CFLAGS) -o $@ $< I have tried a lot and probably fail to fully understand the line %: %.cpp. My interpretation is: I take from every object the dependency which in turn is based on a file which is then traceable to a .cpp file. My theory is test expects test.o and then test.cpp. How do I rewrite this to directory? I have already read some things with wildcards and a pattern replace. Like SRC_DIR := src OBJ_DIR := obj SRC_FILES := $(wildcard $(SRC_DIR)/*.cpp) OBJ_FILES := $(patsubst $(SRC_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(SRC_FILES)) LDFLAGS := ... CPPFLAGS := ... CXXFLAGS := ... main.exe: $(OBJ_FILES) g++ $(LDFLAGS) -o $@ $^ $(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp g++ $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $< But the behavior was not the expected. When 2 cpp files were in the folder the result was g++ -o helloworld.o helloworld.cpp g++ -o helloworld.o test.cpp Or vice versa that only the cpp file was always the same. I have the feeling to miss something extremely. Update: The make version is GNU Make 4.3 Built for aarch64-unknown-linux-android The Goal What I would like to achieve is src/ Test.cpp Helloworld.cpp Obj/ Make : Obj/ Helloworld.out Test.out
Try this: CXX := g++ CXXFLAGS := -g -Wall TARGETS=obj/test.out obj/helloworld.out all:$(TARGETS) obj/%.out:src/%.cpp $(CXX) $(CXXFLAGS) -o $@ $^ clean: rm obj/*
72,513,933
72,514,405
Why my logic is failing in certain test cases?
I am solving this problem on codeforces : https://codeforces.com/contest/1492/problem/C My code: #include <bits/stdc++.h> using namespace std; #define int long long int32_t main() { int n,m; cin>>n>>m; string str1,str2; cin>>str1; cin>>str2; int i=0; int p=0; vector<pair<int,int>>vec; while(i<n && p<m) { int j=i; int q=p; while(j<n-1 && str1[j+1]==str1[i]) j++; while(q<m-1 && str2[q+1]==str2[p]) q++; vec.push_back({i,i}); vec.push_back({i+q-p,j}); i=j+1; p=q+1; } int maxi=1; for(int i=0;i<vec.size()-1;i++) { maxi=max(maxi,vec[i+1].second-vec[i].first); } cout<<maxi<<endl; return 0; } My logic: For each character in t , I am finding the maximum and minimum valid indexes in s which are possible to be taken. Consider this example: s-->"aaaabbbbbc" t-->"aabc" so my vector would be [(0,0) , (1,3) , (4,8) ,(9,9)] However my code is failing in certain cases. Can someone point out the mistake?
Your code doesn't seem to be implementing your algorithm. In the loop you have vec.push_back({i,i}); vec.push_back({i+q-p,j}); So the resulting vector would be alternating pairs of equal indexes and (potentially) different indexes. But: [(0,0) , (1,3) , (4,8) ,(9,9)] The (4, 8) pair can't be produced by {i, i}. Further the first pair in your example doesn't fit your stated algorithm either, the first a can be (0, 2). Your code also seems to assume the letters in the strings are sorted. But what about this input? s = "aaabbbaaabbbccc"; t = "abc"; You would only match a with the first triplet of as and b with the first triplet of bs and break down on the c completely.
72,514,145
72,514,204
Address of an array different with the address of the first element?
As I know address of array a is the address of first element of this array. void func(int a[]) { cout << "address in func: " << &a << endl;; cout << "GT: " << &a[0] << endl; } int main () { int a[] = {0,1,2,3}; cout << "address in main: " << &a << endl; cout << "address in main a[0]: " << &a[0] << endl; func(a); } Output: address in main: 0x7ffef67d6790 address in main a[0]: 0x7ffef67d6790 address in func: 0x7ffef67d6778 GT: 0x7ffef67d6790 Why address of array a in func() difference with address of a[0]?
Why address of array a in func() difference with address of a[0]? Because you're calling the function func() passing a by value. This means the a inside the function func() is actually a copy of the original decayed pointer that you're passing to func() from main(). And since they're different variables, they have different addresses. Thus by writing cout << &a; you're printing the address of this separate local variable named a. If you want to print the original address, you should write inside func(): void func(int a[]) { //---------------------------------v---------->removed the & cout << "address in func: " << a << endl;; cout << "GT: " << &a[0] << endl; } Demo address in main: 0x7ffcfb0a4320 address in main a[0]: 0x7ffcfb0a4320 address in func: 0x7ffcfb0a4320 GT: 0x7ffcfb0a4320
72,514,271
72,514,696
Adding a char matrix as a function argument throws syntax error
I have a function that validates whether certain coordinates are within a matrix and returns true/false depending on the answer: bool validateNextLocation(char robot, int proposed_row, int proposed_col, char map[7][7]){ auto const robot_location = World::getRobotLocation(robot); int row = robot_location -> first; int col = robot_location -> second; if (map[proposed_row][col] != '1' || map[row][proposed_col] != '1'){return false;} else{return true;} } I am trying to use the function in my switch cases: switch (direction) { case 'L': { if (World::validateNextLocation(robot, ++robot_location->first, robot_location-> second, char a[7][7])){ ++robot_location->first; } else{return -1;} } break; case 'D': { if (World::validateNextLocation(robot, robot_location->first, --robot_location->second, char a[7][7])){ --robot_location->second; } else{return -1;} } break; case 'R': { if (World::validateNextLocation(robot, --robot_location->first, robot_location->second, char a[7][7])){ --robot_location->first; } else{return -1;} } break; default: { if (World::validateNextLocation(robot, robot_location->first, ++robot_location->second, char a[7][7])){ ++robot_location->second; } else{return -1;} } break; } But the char a[7][7] has a red underline where the error reads: Expected '(' for function style cast or type construction I know I'm not missing a bracket but where am I going wrong?
Just change if (World::validateNextLocation(robot, robot_location->first, ++robot_location->second, char a[7][7])){ to if (World::validateNextLocation(robot, robot_location->first, ++robot_location->second, a)){ Declaring an array, and using an array are two different things, you don't use the same syntax for both. I am assuming that somewhere in your code you do have a proper declaration for a. That said passing a 7x7 matrix from one function to another seems unlikely to be the right thing to do, but no doubt that will sort itself out in time.
72,514,475
72,556,597
In C++, how to pause and resume a thread from outside?
I want to pause and resume a thread from outside, and at any time (not at certain breakpoints, and thus wait and notify won't work). For example, we create a thread in foo(), and then it keeps running. (the Thread could be any thread class similar to std::thread) void A::foo() { this->th = Thread([]{ // This thread runs a time-consuming job with many steps // I hope to pause and resume it at any time outside ths thread (e.g. press a button) }); } I need to pause and resume the thread outside the thread, maybe by calling methods like this... void A::bar() { this->th->pause(); cout << "The thread is paused now" << endl; } void A::baz() { this->th->resume(); cout << "The thread is resumed now" << endl; } How can I implement this in C++?
@freakish said it can be done with pthread and signals, but no portable way. In Windows, I just found SuspendThread(t.native_handle()) and ResumeThread(t.native_handle()) (where t is of type std::thread) are available. These would solve my problem.
72,514,674
72,569,768
Why SQLite queries run slower in Windows [server] machine compared to Ubuntu & MacOS?
We have 3 machines: One has Windows server OS 2012-r2 installed with decent specs (12 GB RAM, 3.6 GHz, 4 cores, 600 GB hard disk). The others are home laptops with regular specs of Ubuntu 20.04 & MacOS. All are dealing with an SQLite DB. In a loop, simple 4000 SELECT - COUNT queries are run to calculate certain value of a table row. This is followed by an UPDATE of that calculated value in another table. We notice that: In MacOS, it takes 2-3 mins In Ubuntu, it takes 5 mins In Windows, it takes 3 hours 8 mins!!! Upon seeing logs, we noticed that every SELECT + UPDATE queries together take 1-3 seconds in Windows. Moreover Ubuntu uses a core with 100% CPU for our program, while Windows server utilizes only < 2% only. This is a very significant difference. All are running the same source code. Is there anything we can do to make the Windows server OS performing the queries on par with Linux & MacOS?
Turns out that the performance was worsening due to a Mutex lock every time before a SELECT + UPDATE. This was meant for the thread safety as the DB is expected to be accessed from the multiple threads. After changing the design where the DB is now accessed from the single thread, the performance improved manifold. In Ubuntu it became 5X faster and in Windows it became 10X faster!! @prapin's comments also has some merit. We are now executing all the UPDATEs within a single transaction. This speeds up at least the Windows performance by 2X.
72,514,822
72,517,366
How to make glog output not fill 0 before number?
When I use glog to print an Eigen matrix in console, I found the output format has difference when using std::cout against using LOG(INFO). Here is the source code, in which 'sophus_R' is a 3x3 matrix. LOG(INFO) << "using glog, sophus_R is:\n" << sophus_R.matrix(); std::cout << "using std::cout, sophus_R is:\n" << sophus_R.matrix() << std::endl; And here is the output: I0606 16:07:06.307516 122123 so3_test.cc:30] using glog, sophus_R is: 00000.696364 000-0.707107 00000.122788 00000.696364 00000.707107 00000.122788 000-0.173648 -2.08167e-17 00000.984808 using std::cout, sophus_R is: 0.696364 -0.707107 0.122788 0.696364 0.707107 0.122788 -0.173648 -2.08167e-17 0.984808 It seems glog will automatically fill '0' to the empty place before number. How can I make glog output format be same with std::cout(not fill 0)?
It seems the glog stream's fill character has been set to 0. I suggest explicitly setting it back to a space, ' ' using std::setfill: #include <iomanip> LOG(INFO) << "using glog, sophus_R is:\n" << std::setfill(' ') << sophus_R.matrix();
72,515,812
72,516,052
VS code c++ debugger setup using GDB does not work
So here's my problem. I have downloaded mingw g++ by using msys according to the official vs code website Here are my files: Now, when I try to build I get this error: > Executing task: g++ -std=c++14 -g -o myfile.exe myfile.cpp < cc1plus.exe: fatal error: myfile.cpp: No such file or directory compilation terminated. The terminal process "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command g++ -std=c++14 -g -o myfile.exe myfile.cpp" terminated with exit code: 1. And if I do have a .exe file: edit: I also started getting errors with #include <iostream>
I would make this a comment if I could. What is the name of the file where you have written #include <iostream>?* I think if you change the name of that file to "myfile.cpp", you might stop getting that error. You will probably get a different error saying that "main() cannot be found" or something like that, but that's an improvement from your current spot. *I see it's O3.cpp. Try changing that to myfile.cpp.
72,516,302
72,517,450
C++ skip template instantiation for cases that don't satisfy requires clause
I'm writing something like STL red-black tree for practicing coding. My TreeSet, TreeMap, TreeMultiSet, TreeMultiMap all share implementation of RedBlackTree, whose declaration is like this: template <Containable K, typename V, typename Comp, bool AllowDup> requires std::invocable<Comp, K, K> class RedBlackTree { // ... }; template <Containable K, typename Comp = std::less<K>> using TreeSet = RedBlackTree<K, K, Comp, false>; template <Containable K, typename Comp = std::less<K>> using TreeMultiSet = RedBlackTree<K, K, Comp, true>; template <Containable K, Containable V, typename Comp = std::less<K>> using TreeMap = RedBlackTree<K, std::pair<const K, V>, Comp, false>; template <Containable K, Containable V, typename Comp = std::less<K>> using TreeMultiMap = RedBlackTree<K, std::pair<const K, V>, Comp, true>; I have a problem when writing operator[], which should be instantiated only for TreeMap (this is the same as STL that provides operator[] only for std::map among four ordered associative containers) My declaration is like this: template <typename T> std::add_lvalue_reference_t<decltype(std::declval<V>().second)> operator[](T&& raw_key) requires (!std::is_same_v<K, V> && !AllowDup) But it fails to compile if RedBlackTree was instantiated as TreeSet (where V = K so !std::is_same_v<K, V> does not hold). The compiler's complain is that V = K = int (because I instantiated RedBlackTree as TreeSet<int>), so V does not have second. Why the compiler doesn't skip instantiation of this function? requires clause isn't satisfied... Compiler: MSVC 19.30
V is fixed by the class, so you cannot use SFINAE on it in member function. You might introduce extra template parameter as workaround: template <typename V2 = V, typename T> std::add_lvalue_reference_t<typename V2::second_type> operator[](T&& raw_key) requires (!std::is_same_v<K, V> && !AllowDup); or use auto/decltype(auto) template <typename V2 = V, typename T> auto& operator[](T&& raw_key) requires (!std::is_same_v<K, V> && !AllowDup);
72,516,333
72,517,467
Why is my code giving time-limit exceeded while a near identical code works just fine in LeetCode?
Ref: https://leetcode.com/problems/word-search/submissions/ Brief problem statement: Given a matrix of characters and a string, does the string exist in this matrix. Please refer the above link for details. Solution-1 Gives time-limit exceeded. class Solution { public: int n; int m; bool search(vector<vector<char>>& board, const char* w, int i, int j){ if(i < 0 || i >= m || j < 0 || j >= n || *w != board[i][j] || board[i][j] == '\0') return false; if(*(w+1) == '\0') return true; char t = board[i][j]; board[i][j] = '\0'; vector<vector<int>> dir = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; for(auto d: dir){ bool temp = search(board, w+1, i + d[0], j + d[1]); if(temp) return true; } board[i][j] = t; return false; } bool exist(vector<vector<char>>& board, string word) { m = board.size(); n = board[0].size(); for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(search(board, word.c_str(), i, j)) return true; } } return false; } }; Solution-2 Works fine. In fact faster than ~93 % of C++ submissions class Solution { public: int n; int m; bool search(vector<vector<char>>& board, const char* w, int i, int j){ if(i < 0 || i >= m || j < 0 || j >= n || *w != board[i][j] || board[i][j] == '\0') return false; if(*(w+1) == '\0') return true; char t = board[i][j]; board[i][j] = '\0'; if(search(board, w+1, i -1, j) || search(board, w+1, i+1, j) || search(board, w+1, i, j-1) || search(board, w+1, i, j+1)) return true; board[i][j] = t; return false; } bool exist(vector<vector<char>>& board, string word) { m = board.size(); n = board[0].size(); for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(search(board, word.c_str(), i, j)) return true; } } return false; } }; The only difference between these two solutions is the way I call the search function recursively within the search function. In the solution-1 it is: vector<vector<int>> dir = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; for(auto d: dir){ bool temp = search(board, w+1, i + d[0], j + d[1]); if(temp) return true; } In solution-2 it is: if(search(board, w+1, i -1, j) || search(board, w+1, i+1, j) || search(board, w+1, i, j-1) || search(board, w+1, i, j+1)) return true; I think the second solution is like loop unrolling and while this partly explains why the second one is faster than the first one. Isn't it faster by only a constant factor. I mean asymptotically they are similar. I am just surprised that loop unrolling is causing my solution to go from TLE to faster than 93% solutions. Basically, my question is, Is loop unrolling the only reason why the second solution is so fast, or am I missing something?
I am not sure about the time complexity of auto type! But if you remove the 2D vector construction from the recursive function, and instead of auto use the normal index-based loop to access the vector then you would pass the timelimit. class Solution { public: int n; int m; vector<vector<int>> dir = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; bool search(vector<vector<char>>& board, const char* w, int i, int j){ if(i < 0 || i >= m || j < 0 || j >= n || *w != board[i][j] || board[i][j] == '\0') return false; if(*(w+1) == '\0') return true; char t = board[i][j]; board[i][j] = '\0'; for(int r=0; r<4; r++){ bool temp = search(board, w+1, i + dir[r][0], j + dir[r][1]); if(temp) return true; } board[i][j] = t; return false; } bool exist(vector<vector<char>>& board, string word) { m = board.size(); n = board[0].size(); for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(search(board, word.c_str(), i, j)) return true; } } return false; } };
72,517,177
72,559,317
debug WINE 32bit C/C++ app in vscode using gdbserver
Problem Trying to debug win hello world app cross compiled using i686-w64-mingw32-g++-posix in VSCode. But VSCode fails to attach to dbgserver. Repo VSCode project repo is located HERE. Setup Cross compile win app on nix Compiler is configured to use i686-w64-mingw32-gcc-posix and i686-w64-mingw32-g++-posix for C and CXX code respectively. Building cmake project generates ./build/hello.exe which can be run using command wine ./build/hello.exe. Attach gdb to gdbserver As per suggestion running gdbserver using command wine Z:/usr/share/win32/gdbserver.exe localhost:3456 /workspace/build/hello.exe and attaching debugger using command /usr/bin/i686-w64-mingw32-gdb --eval-command='target remote 127.0.0.1:3456' /workspace/build/hello.exe. For convenience sh script /usr/bin/gdbserver was added launching wine Z:/usr/share/win32/gdbserver.exe $@. works fine. Debugger loads symbols, prints following output: ... Type "apropos word" to search for commands related to "word"... Reading symbols from /workspace/build/hello.exe...done. Remote debugging using 127.0.0.1:3456 Reading C:/windows/system32/ntdll.dll from remote target... warning: File transfers from remote targets can be slow. Use "set sysroot" to access files locally instead. Reading C:/windows/system32/kernel32.dll from remote target... Reading C:/windows/system32/kernelbase.dll from remote target... Reading C:/windows/system32/msvcrt.dll from remote target... 0x7bc51a41 in DbgBreakPoint@0 () from target:C:/windows/system32/ntdll.dll (gdb) At this point everything looks fine. Configure VSCode To set up VSCode debugger launch.json file was added with custom paths and parameters to run gdb and gdbserver as indicated HERE. Debugging using VSCode Launching debug configurations initiates a process but doesn't seem to progress to an expected debugging scenario. As soon as debug server launch timeout is reached Unable to start debugging. No process is associated with this object. message pops up and debugging stops. It is worth noting that before timeout is reached running /usr/bin/i686-w64-mingw32-gdb --eval-command='target remote 127.0.0.1:3456' /workspace/build/hello.exe attaches debugger to gdbserver process initiated by VSCode.
Some gdbserver configs were missing After changes dbgserver running wine app works fine. Boiler plate project for 32 bit wine app acn be found HERE.
72,517,940
72,518,049
Why are there so many zeros in the binary file?
Let me use this simple Hello world program as an example: #include <iostream> using namespace std; int main() { cout << "Hello world!"; } Compile using: g++ hello.cpp From quick inspection of the binary file in a text editor, it seems that about half of the resulting binary is only zeros, most of them in large blocks. I'm not worried about it but it seems odd that the compiler would waste a bunch of space. Is there a good reason for having these large unused blocks?
A program file consists of some metadata, executable code, read-only data, data. Each of those is aligned to the page size of your system so that they can be mapped into memory. Those "large unused blocks" are just padding to bring everything to alignment. It's only looks large because your program is basically nothing.
72,518,552
72,518,660
Send and receive uint32_t over a socket via iovec
I'm trying to send a uint_32t type variable over iovec sturct over unix domain socket. My iovec declaration: uint32_t request_id = 123456; struct iovec io = { .iov_base = &request_id, .iov_len = sizeof(uint32_t) }; on the receiving side: char dup[4]; struct iovec io = { .iov_base = dup, .iov_len = sizeof(dup) }; msg.msg_iov = &io; When I print msg.msg_iov[0].iov_base I get a different number every time. printf("msg.msg_iov[0].iov_base = %d\n", msg.msg_iov[0].iov_base); => 723905316 I guess something is off with bytes-to-uint32 conversion?
When I print msg.msg_iov[0].iov_base I get a different number every time. Yes, on the sending side it's the address of request_id and on the receiving side it's address of dup. These addresses do however not matter. They are only used to tell writev and readv where to read/write the data and they will often be different each time you start the programs. Example: Sender: uint32_t request_id = htonl(123456); // to network byte order from host byte order iovec io = { .iov_base = &request_id, .iov_len = sizeof(uint32_t) }; writev(fd, &io, 1); Receiver: uint32_t request_id; iovec io = { .iov_base = &request_id, .iov_len = sizeof(uint32_t) }; readv(fd, &io, 1); request_id = ntohl(request_id); // from network byte order to host byte order
72,518,792
72,520,174
Wrap a C header in C++
Suppose I have some C code that I want to wrap using C++ without exposing the C code to the user. My first attempt was to manually include all headers used in the C code before including the C headers inside a namespace, to hide them from the global scope. This seemed to initially work and compile, however, after trying to use some of the defined structures, I got compilation and linking errors since it couldn't find their definitions. So my question is, either how do I make the above work, or how else do I make my wrapper in a way not to expose the C code to the user of the C++ headers. I should mentioned, that I need the structures and other types in my declarations, so I can't include the header in the cpp file only, for example: class Wrapper { c_struct* _internal; public: void proxy() { c_function(this->_internal); } }
You could use the pimpl idiom to hide all the C headers and structs inside your .cpp file. Example .hpp file: #pragma once #include <memory> class Wrapper { public: Wrapper(); Wrapper(const Wrapper&); Wrapper(Wrapper&&) noexcept = default; Wrapper& operator=(const Wrapper&); Wrapper& operator=(Wrapper&&) noexcept = default; ~Wrapper() = default; void proxy(); private: struct internal_type; // forward declaration std::unique_ptr<internal_type> m_internal; // pointer to implementation }; Example .cpp file: #include "Wrapper.hpp" //#include the C header here. /* I assume it contains declarations like below: struct c_struct; struct c_struct* c_struct_create(); struct c_struct* c_struct_clone(struct c_struct*); // if it can be cloned void c_struct_destroy(struct c_struct*); void c_function(struct c_struct*); */ #include <utility> // the definition of Wrapper::internal_type may inherit from c_struct - or // use composition like below: struct Wrapper::internal_type { internal_type() : handle(c_struct_create()) {} internal_type(const internal_type& rhs) : handle(c_struct_clone(rhs.handle)) {} internal_type(internal_type&& rhs) noexcept : handle(std::exchange(rhs.handle, nullptr)) {} internal_type& operator=(const internal_type& rhs) { if(this == &rhs) return *this; if(handle) c_struct_destroy(handle); handle = c_struct_clone(rhs.handle); return *this; } internal_type& operator=(internal_type&& rhs) noexcept { std::swap(handle, rhs.handle); return *this; } ~internal_type() { if(handle) c_struct_destroy(handle); } void proxy() { c_function(handle); } private: c_struct* handle; }; // default constructor Wrapper::Wrapper() : m_internal(std::make_unique<internal_type>()) {} // copy constructor Wrapper::Wrapper(const Wrapper& o) : m_internal(std::make_unique<internal_type>(*o.m_internal)) {} // copy assignment operator Wrapper& Wrapper::operator=(const Wrapper& rhs) { *m_internal = *rhs.m_internal; return *this; } // the proxy functions just forward to the internal implementation // in internal_type: void Wrapper::proxy() { m_internal->proxy(); }
72,519,240
72,823,567
How to get Nokia S30+'s MRE vxp file to run on nokia 225?
The setup Ok let's me talk a bit about the setup: I have installed Visual Studio 2008 (the edition that let you try for 90 days), MRE SDK 3.0 from this Github issue, Sourcery Codebench Lite for ARM EABI and also ARM Realview Development suite 3.1 (but it requires license, and I am too lazy to cr@ck it, also I prefer the open source GCC to that commercial software). I set the compiler to Sourcery Codebench's GCC. I can compile and run vxp file on Mediatek's emulator without any problem. The problem After compile for ARM platform, here's the output in [project_dir]\arm: I tried copying the Default.vxp to my Nokia 255's SD card, then open that file on my phone, but the phone said Can't open this app at the moment. I also try creating an appmanager folder on my SD card, then my phone's internal storage, then copy the vxp file there, but in the app list, there is still no app other than stock apps, and the vxp file still not run. Other vxp files I downloaded some vxp files from http://shifat100.xtgem.com/, put to my SD card and run from it. Some will work, for example the Asphalt 6 Game, but some won't, for example the Gold rush game, they yelt Can't open this app at the moment. I checked the format of the Asphalt 6 game 's vxp with the file command, and it said data. But I check my Default.vxp, it was ELF. I think this is the problem, but don't know how to convert/pack ELF to vxp. Using binwalk with the Asphalt 6 game 's vxp, I get 2 zlib compressed files and 2 GIFs, which are icons of the game. The two compressed files, after unpack, one contain many names, for example splash_320x240.bsprite splash_menu_320x240_200k.bsprite splash_menu_split_320x240_200k.bsprite splash_title.bsprite hollywood_320x240_200k.bsprite new.png font_small.bsprite font_large.bsprite interface_font.bsprite copter.bsprite car_tourist.bsprite cars_fx.bsprite cars_shadow.bsprite so I think this is the resource file. The other might contain code, I found some exception strings in it, for example Unknown signal Invalid Operation Divide By Zero Overflow Underflow Inexact Result : Heap memory corrupted Abnormal termination Arithmetic exception: Illegal instruction Interrupt received Illegal address Termination request Stack overflow Redirect: can't open: Out of heap memory User-defined signal 1 User-defined signal 2 Pure virtual fn called C++ library exception and some (maybe) S30+ platform APIs, for example vm_get_mre_modules vm_get_mre_total_mem_size vm_get_mre_version So what might be the problem? Screen resolution? I changed it but still not work. SDK version? I also tried all 3 version, but no luck. File format? Compiler difference? (Note that I'm using GCC while most tutorial left on the internet suggest using RVCS) I don't know. Any ideas? Thanks! If you need to get any files, tell me and I will put it here.
Delivered from my answer at RE.SE First I want to say thanks to people at 4pda forum. See their thread here. Can you figure out informations about the MRE VXP format Well I haven't found yet, need further research how to get it signed Short answer: Step 1: Get your SIM 1's IMSI number (NOT IMEI, they are DIFFERENT!) You can do this in multiple ways, but the easiest way is to plug the SIM 1 in to an Android phone and read. I personally use ADB to read IMSI (worked on Android 6+ without root): adb shell service call iphonesubinfo 7 Step 2: Go to https://vxpatch.luxferre.top/ and input the IMSI number you got in step 1. Then select your VXP file, click 'Patch' and you should be able to download a patched version. or You can enter the IMSI number in the project setting, but REMEMBER TO ADD 9 BEFORE THE IMSI NUMBER Step 3: Move the patched version into a SD card and plug it in your phone Step 4: Find the vxp file and click open, your app should run now! Long answer: Some apps doesn't require specify the IMSI, they just work on any devices. That's because they use another way of signing, using RSA key. If you are interested, read here. The text is in Russian, so use Google Translate if you want to. I have tested with ADS 1.2 compiler (I cracked myself, if you want it then tell me) and GCC (Smaller size + work very well) and Nokia 225, will continue to test further! The apps in S30+ platform are written in C (and optionally C++), so you can port many apps to S30+ Again, a great thanks to people at 4pda forum! An image of the app running after signing: