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
70,627,623
70,627,880
Problem with a variable with the same value in different functions (C ++)
Do you know if there is any way to save the value of an assigned variable in one function to use it in another function? In this case, I have a program that asks me to enter the name of the variable nombre in the function registro(); to register a plant. For example, if I enter Maguey de sol, the program prints: ¿Quieres continuar con el registro de Maguey de sol? So far everything works fine. The problem appears when I press any key to continue. The program should print: La planta es Maguey de sol But it only prints: La planta es I know that a solution is to include the code of the function registro(); in main();, but it is not a viable option, because in my program I use more functions. This is the code: #include <iostream> #include <locale.h> // Español #include <string> // Cadenas #include <fstream> // Ficheros using namespace std; bool registro(); int main(){ setlocale(LC_CTYPE, "Spanish"); // Español string nombre; registro(); cout << "La planta es " << nombre << endl; return 0; } bool registro(){ string nombre; cout << "\n \t Ingresa el nombre de la planta" << endl; cout << "\t (Máximo 15 caracteres) \n \n" << endl; cin.clear(); fflush(stdin); while (getline(cin, nombre)){ if (nombre.size() <= 15){ cout << "\n \t ¿Quieres continuar con el registro de " << nombre << "?\n" << endl; system("pause"); break; }else{ cout << "\n \t ¡El nombre debe tener un máximo de 15 caracteres! \n" << endl; } } } Thanks for your help.
Not sure about what you're trying to achieve, but to elaborate on Stephen Newell 's comment, here is a modified version of your code. Although your nombre variables have the same name, they are technically different variables, and therefore have different values, in each of their respective scope. Learn more here: https://www.geeksforgeeks.org/scope-of-variables-in-c/ #include <iostream> #include <locale.h> // Español #include <string> // Cadenas #include <fstream> // Ficheros using namespace std; string registro(); int main() { setlocale(LC_CTYPE, "Spanish"); // Español string nombre; nombre = registro(); cout << "La planta es " << nombre << endl; return 0; } string registro() { string nombre; cout << "\n \t Ingresa el nombre de la planta" << endl; cout << "\t (Máximo 15 caracteres) \n \n" << endl; cin.clear(); fflush(stdin); while (getline(cin, nombre)) { if (nombre.size() <= 15) { cout << "\n \t ¿Quieres continuar con el registro de " << nombre << "?\n" << endl; // system("pause"); break; } else { cout << "\n \t ¡El nombre debe tener un máximo de 15 caracteres! \n" << endl; } } return nombre; }
70,627,806
70,628,107
Negating expression in if statement inside macro gives odd results
I've run into a somewhat strange issue. It makes me feel like the answer is blaringly obvious and I'm just not seeing something because the code is so simple. I basically have a macro called "ASSERT" that makes sure a value isn't false. If it is, it writes a message to the console and debug breaks. My issue is that when asserting that the index returned from std::string::find_first_of(...) is not equal to std::string::npos, the assert doesn't seem to work at all. Every time, the assertion fails. I have verified that the values are not equal when the debug break occurs, so I don't see how the assertion is failing. In my original code, it reads data from a file to a string, but the issue still seems to be present in the example below with nothing but a const std::string. I'm working on a much bigger project, but here's a minimal example that reproduces the bug (I'm using Visual Studio 2022 and C++17 by the way): #include <iostream> #include <string> #define ASSERT(x, msg) {if(!x) { std::cout << "Assertion Failed: " << msg << "\n"; __debugbreak(); } } int main() { const std::string source = "Some string that\r\n contains the newline character: \r\n..."; size_t eol = source.find_first_of("\r\n", 0); ASSERT(eol != std::string::npos, "Newline not present!"); // Other code... return 0; } Please note that the exact same thing happens even when only one newline character ("\r\n") is present in the string. What's interesting is that "eol" seems to have the correct value in every test case that I've run. The only thing that's wrong is the assertion, so if I ignore it and continue, everything runs exactly how I expect it to. I also found this issue that seems related, but no answer or conclusion was reached: std::string::find_first_of does not return the expected value
This is the unexpected consequence of the by-design simple stupidity of the preprocessor's macro substitution engine. An expression supplied to the macro is not evaluated as it would be with a function, the text is inserted directly during substitution. Given #define ASSERT(x, msg) {if(!x) { std::cout << "Assertion Failed: " << msg << "\n"; __debugbreak(); } } the line ASSERT(eol != std::string::npos, "Newline not present!"); will be transformed into {if(!eol != std::string::npos) { std::cout << "Assertion Failed: " << "Newline not present!" << "\n"; __debugbreak(); } } and the ! is only applied to the eol, changing the expected behaviour of the macro to something nonsensical. Adding the extra brackets recommended in the comments #define ASSERT(x, msg) {if(!(x)) { std::cout << "Assertion Failed: " << msg << "\n"; __debugbreak(); } } results in {if(!(eol != std::string::npos)) { std::cout << "Assertion Failed: " << "Newline not present!" << "\n"; __debugbreak(); } } and now the expression is being evaluated before applying the ! and tested. Because macros are "evil", and since the macro makes no use of any special, position dependent debugging macros like __FILE__ or __LINE__, this is a case where I would replace the macro with a function and count on the compiler's optimizations to inline it.
70,628,392
70,628,495
How do I implement an iterable structure?
I want to write a structure through which I can loop. For this I added two methods begin and end which would return begin, end values of an already existing vector. What return type should I specify, and will these two methods be enough to make MATCH structure work in my context? Here's what I've got so far: typedef std::pair<std::string, std::string> combo; struct MATCH { std::vector<combo> matches; ? begin() { return matches.begin(); } ? end() { return matches.end(); } }; int main() { MATCH m = { ... }; for (const combo& i : m) ...; }
I think the type you're looking for is std::vector<combo>::iterator. Example: typedef std::pair<std::string, std::string> combo; struct MATCH { std::vector<combo> matches; std::vector<combo>::iterator begin() { return matches.begin(); } std::vector<combo>::iterator end() { return matches.end(); } }; int main() { MATCH m = { { {"something", "something"} } }; for (const combo& i : m) cout << i.first << " " << i.second << std::endl; return 0; }
70,628,435
70,628,679
How to configure cmake to recompile a target when a non .cpp source file is modified
If we look at the minimal example below, cmake_minimum_required(VERSION 3.20) project(example) add_executable(${PROJECT_NAME} main.cpp test.txt) Once the executable target is built, it will only rebuild if main.cpp is modified. If test.txt is modified, it wouldn't rebuild because eventhough test.txt is included as a source for the executable target, it isn't used to compile the executable. Is there any way that we can configure cmake so that when test.txt is modified, it will trigger a rebuild? The real use case for my application is I have a metal file that is associated with an executable target (e.g. add_executable(${PROJECT_NAME} main.cpp mylib.metal)) and I want to generate mylib.metallib along with the example executable when the target is build. I have something like add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD COMMAND "the command to compile .metal into .metallib") but this add_custom_command will only be invoked during the first compilation of the executable target, or whenever main.cpp is modified, I want this add_custom_command to be invoked also when mylib.metal is modified. How can this be done?
One way is to create a custom target and add a custom command to it that will generate your mylib.metallib cmake_minimum_required(VERSION 3.20) project(custom_file_target VERSION 1.0.0) add_executable(main main.cpp) # main target add_custom_target( custom DEPENDS ${CMAKE_BINARY_DIR}/mylib.metallib ) add_custom_command( OUTPUT ${CMAKE_BINARY_DIR}/mylib.metallib COMMAND echo your command that will create mylib.metallib DEPENDS ${CMAKE_SOURCE_DIR}/mylib.metal ) add_dependencies(main custom) You can swap main and custom in the last line depending on what dependency ordering you want (main depends on custom or the other way round). See also my other answer here: https://stackoverflow.com/a/70626372/8088550 If mylib.metallib is actually linkable you can also think about creating an imported library that depends on your custom target, i.e. cmake_minimum_required(VERSION 3.20) project(custom_file_target VERSION 1.0.0) add_executable(main main.cpp) # main target add_custom_target( custom DEPENDS ${CMAKE_BINARY_DIR}/mylib.metallib ) add_custom_command( OUTPUT ${CMAKE_BINARY_DIR}/mylib.metallib COMMAND echo your command that will create mylib.metallib DEPENDS ${CMAKE_SOURCE_DIR}/mylib.metal ) add_library(mylib STATIC IMPORTED) set_property( TARGET mylib PROPERTY IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/mylib.metallib ) add_dependencies(mylib custom) target_link_libraries(main PRIVATE mylib)
70,628,471
70,628,558
clang-tidy: `Loop variable is copied but only used as const reference; consider making it a const reference` - does it really matter?
I'm working on code that clang-tidy is flagging all over the place with Loop variable is copied but only used as const reference; consider making it a const reference Current code: for (auto foo : collection) { ... } What clang-tidy suggests I use: for (const auto &foo : collection) { ... } I can certainly see where a const reference would be more efficient than actually copying the value, but I'm wondering if the compiler will just optimize it that way anyway? I'd hate to dig in and change hundreds of loops all for nothing.
Constructors can have side-effects beyond constructing the new object. The semantics of the two versions could therefore differ. Even if that is not the case, the compiler might not be able to determine that during compilation. For example if the copy constructor of the foo type is not defined in the same translation unit and no link-time optimization is used, the compiler wouldn't be able to optimize away the copy, since it might have side-effects that are unknown at compilation time of the current translation unit. Similarly the loop body might call functions for which the compiler cannot prove that they don't modify foo, in which case the copy can also not be optimized away. (This is by the way harder for the compiler to prove than it is for clang-tidy to give you the warning, since even a function taking a const reference of foo is technically still allowed to modify it. And even if the foo object itself is const-qualified (e.g. const auto), functions may depend on the address of the foo object being different than that of the container's foo object through other program paths.) Even if everything is visible in the translation unit and the observable behavior doesn't depend on the copy, the operations might be too complex for the compiler to optimize the copy away. Example: auto f(const std::vector<std::string>& x) { std::size_t n = 0; for(auto y : x) n += y.size(); return n; } Both GCC and Clang with -O3 and libstdc++ don't optimize the copies away (see the operator new/operator delete/memcpy calls in the assembly): https://godbolt.org/z/d66ac617M Also compare to the same code with references instead: https://godbolt.org/z/Tdc3GhcEv However, in the above example there might still be a visibility issue with the standard library implementation of std::string. Here is maybe a better example in which all definitions are probably visible in the current translation unit: struct A { int a[64]; }; auto f(const std::vector<std::vector<A>>& x) { std::size_t n = 0; for(auto y : x) n += y.size(); return n; } In this case, GCC still doesn't optimize the copy away, while Clang does, although it still leaves some allocation size check in there for some reason: https://godbolt.org/z/8KWPTx4o5 But if the type is made more complex there will probably be a point at which neither compiler will be able to optimize away the copy even though everything is visible. If you know that the type of foo is simple, e.g. a scalar like on a std::vector<int> container, then it doesn't really matter in terms of performance, assuming the observable behavior is the same. You might still want to use the const reference, more specifically the const part, for the purpose of keeping const-correctness throughout your code. How necessary that is, probably goes into opinion-based territory though.
70,628,591
70,629,590
SDL_CreateWindow Error: windows not available
When calling SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_SHOWN); the window is not created and calling SDL_GetError returns an error that reads exactly as shown in the title. I had set my SDL_VIDEODRIVER to 'windows' at one point, but changing this, rebuilding my application, and attempting to run again did not change the error. I did not find any documentation about the error, even in a couple of directories listing SDL error codes. I am on Eclipse C++ and my compiler is cygwin. Why am I getting this error, and how do I solve it? Is there any other information I need to provide to get to the bottom of this? Edit: Here is the minimum reproducible example: #define SDL_MAIN_HANDLED #include <iostream> #include <SDL.h> using namespace std; int main() { //This if statement's condition is not met. I left it here in its full form to //show that SDL_Init() is not causing the error. if( SDL_Init(SDL_INIT_VIDEO) < 0 ) { cout << "SDL_Init Error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } //It seems as though win is being set to nullptr here. SDL_Window *win = SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_SHOWN); //This if statement's condition is met. The error is written to the console from this cout statement. if (win == nullptr){ cout << "SDL_CreateWindow Error: " << SDL_GetError(); SDL_Quit(); return 1; } return 0; }
The answer is very simple, you are not running the test with the X server running from mintty: $ g++ prova.cc -o prova -lSDL2 -I/usr/include/SDL2 $ ./prova.exe SDL_Init Error: No available video device now we start the X server $ startxwin Welcome to the XWin X Server Vendor: The Cygwin/X Project Release: 1.21.1.2 ... and a XTerm now from the XTerm $ ./prova.exe $ echo $? 0 the program completed without errors but so fast to not see the window. Add to the code #include <unistd.h> and sleep(20); before return 0. The Window will show up with the "Hello World" in the title bar. See Cygwin/X User's Guide https://x.cygwin.com/docs/ug/cygwin-x-ug.html
70,628,865
70,629,051
Can't access private member in templated overloaded operator
In this code, why is it not possible to access the private field of my class in the operator overload ? (Note that this is only a MRE, not the full code) template <typename T> class Frac template <typename T, typename U> Frac<T> operator+ (Frac<T> lhs,const Frac<U>& rhs); template <typename T, typename U> bool operator==(const Frac<T>& lhs, const Frac<U>& rhs); template <typename T> class Frac { template<typename> friend class Frac; friend Frac operator+ <>(Frac lhs,const Frac& rhs); friend bool operator== <>(const Frac& lhs, const Frac& rhs); private: T numerator, denominator; }; template <typename T, typename U> Frac<T> operator+(Frac<T> lhs,const Frac<U>& rhs) { lhs.denominator += rhs.denominator; return lhs; } template <typename T, typename U> bool operator==(const Frac<T>& lhs, const Frac<U>& rhs) { return (lhs.numerator == rhs.numerator && lhs.denominator == rhs.denominator); } When I compile the compiler tells me that it is not possible to access the denominator and numerator fields because they are private. However the overload is indicated as friendly. The class is also indicated as friendly so that all instances of the class whatever the type are friendly. Could someone explain me what the problem is and how to solve it?
To make each instance of template <typename T, typename U> bool operator==(const Frac<T>& lhs, const Frac<U>& rhs); a friend, you need to be just as verbose in your friend declaration. Copy this declaration and stick "friend" in it. There are two quirks. First, template has to come before friend, so you'll be adding the keyword in the middle of the declaration. Second, T is already being used as the template parameter to the class, so you should choose a different identifier to avoid shadowing (I'll use S). template <typename S, typename U> // ^^^ friend bool operator==(const Frac<S>& lhs, const Frac<U>& rhs); // ^^^^^^ ^^^ Without this change, you are saying that the friend of Frac<T> is an operator that takes two Frac<T> parameters (the same T).
70,628,926
70,629,021
Usage of for range in Vectors in order to add elements
A lot of questions related to for range has been asked around here, but I cannot find the version I need. So, I was reading this book called C Primer 5th edition, and while reading about Vectors I read a line which stated, we cannot use a range for if the body of the loop adds elements to the vector. But just before this line there was a code part written to add elements in the vectors during the run time, i.e., vector<int> v2; // empty vector for (int i = 0; i != 100; ++i) v2.push_back(i); // append sequential integers to v2 // at end of loop v2 has 100 elements, values 0 . . . 99 All I want to ask is that how can they both contradict to one another? Or are they completely different and not related to one another? If the second one is the condition can you explain me how this works? And if the former is correct can you please explain me why do the code part and the statement contradicted to one another?
The reason that (amongst other things) a range-based for loop shouldn't append elements is because behind the curtains, a range-based for loop is just a loop that iterates over the container's iterators from begin to end. And std::vector::push_back will invalidate all iterators: If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated. Contrary to using iterators, however, the same cannot be said when indexing the vector, because even if push_back invalidats iterators, vec[3] will always refer to the element at position 3 (assuming size() > 3). Furthermore, the loop you show does not even iterate over the vector's elements. It just adds more elements to an existing vector, and it is not a range-based for loop. To be clear, a construct that would be a problem would be the following: std::vector<int> vec(10); // 10 times a zero vec[0] = 1; for (int k: vec) if (k == 1) vec.push_back(2); // invalidates iterators! While this, equivalent looking code, is legal: std::vector<int> vec(10); // 10 times a zero vec[0] = 1; for (std::size_t i = 0; i < std::size(vec); ++i) if (vec[i] == 1) vec.push_back(2);
70,628,987
70,629,018
01 number input for date not giving output on system
I can't enter 01 into my c++ input, it will return with empty result but when i type other date such as 12 and 11 it does show in the system. string month; cin.ignore(1, '\n'); cout << "Please Enter Month For Example 01 for January:"; getline(cin, month); string search_query = "SELECT DATE(OrderDate), SUM(TotalPrice) FROM order1 WHERE MONTH(OrderDate) like '%" + month + "%' GROUP BY DATE(OrderDate)"; const char* q = search_query.c_str(); qstate = mysql_query(conn, q); DATABASE This is what happen if I enter "01" This is what happen when I enter "11" This is when I type "12" it successfully show
The problem is that you are using the LIKE operator in MySQL, which checks to see if the pattern specified on the right occurs in the string specified on the left. The pattern "01" probably doesn't occur in the value on the left, since the string on the left should be "1" for January orders, and that doesn't have a "0" in it. I also imagine that if you type "1" you would actually see all orders from January, October, November, and December since all those months have "1" in them. Try using something like MONTH(OrderDate) = 1 instead. To be more explicit: try changing the line in your program that defined search_query to this: std::string search_query = "SELECT DATE(OrderDate), SUM(TotalPrice) FROM order1 WHERE MONTH(OrderDate) = " + month + " GROUP BY DATE(OrderDate)"; By the way, for a more robust program, you should also make sure you turn the user-supplied month number into an integer before adding it to the query string; right now you are letting users insert arbitrary strings into your query, which could be dangerous.
70,629,120
70,647,297
Windows __try/__except doesn't catch raised exceptions
So I was trying to write something that dereferences an unknown pointer and returns the status of the operation, like this: int n; __try { n = *(int*)(addr); // The unknown address. } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { printf("Exception caught!\n"); } Now this code didn't even catch the exception in the first place, so the VS debugger caught it instead. So I got curious and did a simple dry run: __try { RaiseException(EXCEPTION_ACCESS_VIOLATION, NULL, NULL, nullptr); } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { printf("Exception caught!\n"); } This yielded the same result as the other block of code did. I've written the upper block of code hundreds of times though and I'm really unsure about why __try would suddenly just pretend like it doesn't exist at all. And yes I've checked my compiler settings. They are set to compile with /RTC1.
As @Hans Passant said, the process's debugger can catch the exception prior to a frame-based exception handler(I checked). The RaiseException lists an exception handler sequence. The system first attempts to notify the process's debugger, if any. If the process is not being debugged, or if the associated debugger does not handle the exception, the system attempts to locate a frame-based exception handler by searching the stack frames of the thread in which the exception occurred. The system searches the current stack frame first, then proceeds backward through preceding stack frames. If no frame-based handler can be found, or no frame-based handler handles the exception, the system makes a second attempt to notify the process's debugger. If the process is not being debugged, or if the associated debugger does not handle the exception, the system provides default handling based on the exception type. For most exceptions, the default action is to call the ExitProcess function.
70,629,277
70,629,296
Calling constructor with :: operator fails
I am implementing a class using singleton for logging purposes. Log *Log::getInstance(){ if(!Log::log) Log::log = new Log::Log(); return Log::log; } Here, Log::log is a pointer to an object of Log class. This snnipet of code generates the error "expected type-specifier" on new Log::Log(), but if I ommit the scope resolution operator, it works fine. Why?
Log is the class type. Log::Log is a syntax construct that in certain contexts refers to Log's constructor. However it doesn't generally name it as in the names of other functions (e.g. for the purpose of address-taking). new expects a type name. That is simply the syntax. Log(...) in a new-expression like new Log(...) will call the constructor according to the arguments ... implicitly to construct the new object, even though Log is its type name, not referring to its constructor. This is consistent with the syntax for non-class types, such as new int(1). Therefore, remove ::Log from Log::Log. Constructors are never called explicitly in C++. You only have syntax of the form type(...) or type{...} which implicitly call constructors for class types to construct new objects. The only case where it might make sense to informally talk about "calling" a constructor might be deferred construction, in which one constructor "calls" another constructor in its member-initializer-list. I should add that you should not implement a singleton this way. You have no way of destroying the object you created in the new expression automatically at program end and the initialization is not thread-safe. See e.g. this question and others for C++ singleton designs.
70,629,382
70,629,418
Using return vs no return in recursion?
Here is code to reverse an array using recursion Using return rev(arr,++start,--end); #include <iostream> using namespace std; void rev(int arr[],int start,int end) { if(start >= end) { return; } int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; return rev(arr,++start,--end); } void reverse(int arr[],int size) { rev(arr,0,size-1); } Using rev(arr,++start,--end); void rev(int arr[],int start,int end) { if(start >= end) { return; } int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; rev(arr,++start,--end); } void reverse(int arr[],int size) { rev(arr,0,size-1); } They both give same output 7 6 5 4 3 2 1 What is the difference between using return and not using return with rev here?
There is no difference. From 9.6.3 [stmt.return]: A return statement with no operand shall be used only in a function whose return type is cv void, a constructor (15.1), or a destructor (15.4). A return statement with an operand of type void shall be used only in a function whose return type is cv void. [...] Flowing off the end of a constructor, a destructor, or a function with a cv void return type is equivalent to a return with no operand. Because the type of the function call expression is the cv-qualified return type of the function as defined in its signature, and because your function is defined to return void, then the three that follow are equivalent: void f() { //stuff f(); return; } void g() { //same stuff return g(); } void h() { //same stuff h(); }
70,629,518
70,629,541
Pass a vector as a range to std::sort - C++17
I wrote this code in order to simplify the use of std::for_each when I need to go through an entire collection: namespace ranges { template<typename Range, typename Function> Function for_each(Range &range, Function f) { return std::for_each(std::begin(range), std::end(range), f); } } So that I can use it like this: ranges::for_each(a, foo); This had worked for me and since I also have to sort entire collections, I thought it would be a good idea to implement the same process with std::sort, just like this: namespace ranges { template<typename Range, typename Function> Function for_each(Range &range, Function f) { return std::for_each(std::begin(range), std::end(range), f); } template<typename Range, typename Function> Function sort(Range &range, Function f) { return std::sort(std::begin(range), std::end(range), f); } } When I add that code to my namespace, the compiler throws me the following error message: error: void value not ignored as it ought to be Is there a way to achieve what I want to do? I'm using the C++17 standard and g++.exe (Rev1, Built by MSYS2 project) 11.2.0 to compile.
Your implementation of for_each works, because the definition of std::for_each you're using is defined as follows: namespace std { template <class Iterator, class Function> Function for_each(Iterator begin, Iterator end, Function f); }; However, std::sort as invoked is defined as follows: namespace std { template <class Iterator, class Function> void sort(Iterator first, Iterator last, Function comp); }; In your definition of sort, you cannot return the result of the call to std::sort, because the return types for the two functions are distinct.
70,629,559
70,629,581
For loop should not execute
In this code std::vector<int> vec; for (int i = 0; i < vec.size() - 1; i++) { std::cout << "Print" << std::endl; } Though vec has no input members so the for loop should not execute at all since i will be more than the condition for execution which is vec.size() - 1. But still the loop is executing.
vec.size() returns an unsigned type. Now vec.size() is 0, but vec.size() - 1 will cause an wrap around, so that's why you see std::cout << "Print" << std::endl; executed
70,630,371
70,630,632
What type is used by std::allocate_shared to allocate memory?
From https://en.cppreference.com/w/cpp/memory/shared_ptr/allocate_shared: template< class T, class Alloc, class... Args > shared_ptr<T> allocate_shared( const Alloc& alloc, Args&&... args ); The storage is typically larger than sizeof(T) in order to use one allocation for both the control block of the shared pointer and the T object. ... All memory allocation is done using a copy of alloc, which must satisfy the Allocator requirements. What type is then used to allocate the aforementioned storage? In other words, what should be Alloc::value_type, one of the Allocator requirements?
The actual type used depends on the implementation. By Allocator requirements and with the help of std::allocator_traits traits class template, any allocator can be rebinded to another type via std::allocator_traits<A>::rebind_alloc<T> mechanism. Suppose you have an allocator template<class T> class MyAlloc { ... }; If you write: std::allocate_shared<T>(MyAlloc<T>{}); it doesn't mean that MyAlloc<T> will be used to perform allocations. If internally we need to allocate an object of another type S, we can get an appropriate allocator via std::allocator_traits<MyAlloc<T>>::rebind_alloc<S> It is defined such that if MyAlloc itself doesn't provide rebind<U>::other member type alias, the default implementation is used, which returns MyAlloc<S>. An allocator object is constructed from that passed to std::allocate_shared() (here, MyAlloc<T>{}) by an appropriate MyAlloc<S>'s converting constuctor (see Allocator requirements). Let's take a look at some particular implementation - libstdc++. For the line above, the actual allocation is performed by MyAlloc<std::_Sp_counted_ptr_inplace<T, Alloc<T>, (__gnu_cxx::_Lock_policy)2> which is reasonable: std::allocate_shared() allocates memory for an object that contains both T and a control block. _Sp_counted_ptr_inplace<T, ...> is such an object. It holds T inside itself in the _M_storage data member: __gnu_cxx::__aligned_buffer<T> _M_storage; The same mechanism is used in many other places. For example, std::list<T, Alloc> employs it to obtain an allocator that is then used to allocate list nodes, which in addition to T hold pointers to their neighbours. An interesting related question is why allocator is not a template template parameter, which might seem a natural choice. It is discussed here.
70,630,463
70,687,323
Using fstream::getline in VS2019 Is Giving Me Different Results Than Using It With VSCode
So I've been learning about steams and have been experimenting on my own. I was attempting to write a simple program to read the first line of a file only. But I've noticed an issue in Visual Studio 2019. Below is the code snippet. #include <iostream> #include <fstream> #include <string> int main() { std::ifstream in("Test.txt", std::ios::binary); if (in) { std::string store; std::getline(in, store, '\n'); std::cout << store; } return 0; } The test.txt file reads: This Is A Test In VS19 the output to the console is just " his". In VSCode the output is "This" as it should be. Am I doing anything wrong in VS19 as far as possible configuration? Is it a bug? It was driving me crazy until I tried a different IDE, can't figure out why it would be doing that. Note: It isn't ignoring the first character of the string, it is replacing it with whitespace. Hex of Test.txt for VS2019 00000000 54 68 69 73 0D 0A 49 73 0D 0A 41 0D 0A 54 65 73 00000010 74 And VSCode 00000000: 54 68 69 73 0A 49 73 0A 41 0A 54 65 73 74
You are opening your input file in binary mode. This means that getline will read the following bytes (it will discard the newline character): 54 68 69 73 0D This corresponds to the following string: "This\r" The last character is the carriage-return character. In the comments section of the question, you stated that you experienced the same problem when you simply wrote std::cout << "This\r"; to the console. In that case, the character T was also being overwritten. This probably means that this is simply the way that your console handles the carriage-return character. The best way to fix this problem is to open the text file in text mode, instead of binary mode. That way, the "\r\n" line endings will automatically be converted to "\n" line endings, and you won't have to deal with any carriage-return characters. Therefore, I suggest that you change the line std::ifstream in("Test.txt", std::ios::binary); to: std::ifstream in("Test.txt");
70,630,968
70,631,185
Pointer initialization with new keyword and without it
When I try to declare in another way a pointer I try to use the new keyword and give it a try: #include<iostream> using std::cin; using std::cout; using std::endl; int main () { int *p = new int; *p = 5; cout << *p << endl; return 0; } but when I try to declare the same pointer but without the new keyword it gives me an error like the code below: #include<iostream> using std::cin; using std::cout; using std::endl; int main () { int *p; *p = 5; cout << *p << endl; return 0; } So what is the reason for that error and what is the difference between the two ways?
You should know the differences. int *p; Here, p is just a variable on the stack. It hasn't been initialized so it does not point to a specific location on the memory. Thus when you dereference it and assign a value to the underlying location you are invoking some undefined behavior. In other words, you haven't yet allocated any space on the heap to store an int. So here: *p = 5; you are probably assigning the value 5 to a location that does not belong to your program. Now here: int *p = new int; *p = 5; this is fine. The new operator will reserve 4 bytes on the heap memory and return its address and that address gets stored in the p and now p contains an actual and legal address of a block of memory capable of storing an int. So it is safe to dereference p and assign a value to the underlying location. Important note: You should almost never deal with new/delete or new[]/delete[] operators and raw pointers. Instead, you should use smart pointers and stick to RAII as much as possible. Therefore, the correct way of doing the above would be like this: #include<iostream> #include<memory> using std::cin; using std::cout; using std::endl; int main () { std::unique_ptr<int> p { std::make_unique<int>( 5 ) }; cout << *p << endl; return 0; } However, using any type of pointers is wasteful in this case since you can also store small types on the stack: int num { 5 }; This is the preferred way of storing values unless you are desperate to use dynamic memory allocations (for some reason, like maybe you want an object to have dynamic storage duration, or maybe the object is large and won't fit on the stack).
70,631,149
70,634,898
Can I allocate a series of variables on the stack based on template arguments?
In a piece of code I'm writing, I receive packets as uint8_t * and std::size_t combination. I can register functions to call with these two parameters, based on which file descriptor the packet was received from. I use an std::map<int, std::function<void(const uint8_t *, std::size_t)> > handlers to keep track of which function to call. I would like to be able to (indirectly) register functions with arbitrary arguments. I already have a function like this to transform from the uint8_t * and std::size_t to separate variables: int unpack(const uint8_t *buf, std::size_t len) { return 0; } template <typename T, typename... Types> int unpack(const uint8_t *buf, std::size_t len, T &var1, Types... var2) { static_assert(std::is_trivially_copyable<T>::value, "unpack() only works for primitive types"); if (len < sizeof(T)) return -1; var1 = *reinterpret_cast<const T *>(buf); const auto sum = unpack(buf + sizeof(T), len - sizeof(T), var2...); const auto ret = (sum == -1) ? -1 : sum + sizeof(T); return ret; } My question is: Is it possible with C++20 to auto-generate a function that convers from uint8_t * and std::size_t to the arguments that a passed function needs? I would like to be able to do this: void handler(unsigned int i) { ... } int main(int argc, char ** argv) { /* some code generating an fd */ handlers[fd] = function_returning_an_unpacker_function_that_calls_handler(handler); edit: I realize I went a bit too short on my answer, as some mentioned (thanks!). I am wondering if it is possible (and if so, how?) to implement the function_returning_an_unpacker_function_that_calls_handler function. I started out doing something like this (written from memory): template<typename... Types> std::function<void(const uint8_t * buf, std::size_t)> function_returning_an_unpacker_function_that_calls_handler(std::function<void(Types...)> function_to_call) { const auto ret = new auto([fun](const uint8_t * buf, std::size_t len) -> void { const auto unpack_result = unpack(buf, len, list_of_variables_based_on_template_params); if(unpack_result == -1) return nullptr; function_to_call(list_of_variables_based_on_template_params); }; return ret; } This is also why I supplied the unpack function. The problem I'm encountering is that I'm struggling with the list_of_variables_based_on_template_params bit. I haven't found any way to generate a list of variables that I can repeat identically in two places. I also looked a little bit into using std::tuple::tie and friends, but I didn't see a solution there either.
This answer is very similar to the first one, but it leverages the use of CTAD and std::function to figure out the function signature. Creates a tuple based on the function signature, and passes both the argument types and the elements from the tuple on to unpack. #include <iostream> #include <tuple> #include <type_traits> #include <cstring> #include <functional> int unpack(const uint8_t *buf, std::size_t len) { return 0; } template <typename T, typename... Types> int unpack(const uint8_t *buf, std::size_t len, T &var1, Types&... var2) { static_assert(std::is_trivially_copyable<T>::value, "unpack() only works for primitive types"); if (len < sizeof(T)) return -1; var1 = *reinterpret_cast<const T *>(buf); std::cout << "In unpack " << var1 << "\n"; const auto sum = unpack(buf + sizeof(T), len - sizeof(T), var2...); const auto ret = (sum == -1) ? -1 : sum + sizeof(T); return ret; } template<typename T, typename R, typename... Args> std::function<void(const uint8_t * buf, std::size_t)> unpack_wrapper_impl(T function_to_call, std::function<R(Args...)>) { return [function_to_call](const uint8_t *buf, std::size_t len) -> void { std::tuple<std::decay_t<Args>...> tup; std::apply([&](auto&... args) { unpack(buf, len, args...); }, tup); std::apply(function_to_call, tup); }; } template<typename T> std::function<void(const uint8_t * buf, std::size_t)> unpack_wrapper(T&& function_to_call) { return unpack_wrapper_impl(std::forward<T>(function_to_call), std::function{function_to_call}); } void test(int a, int b) { std::cout << a << " " << b << "\n"; } int main() { int a= 5, b = 9; uint8_t* buf = new uint8_t[8]; std::memcpy(buf, &a, 4); std::memcpy(buf + 4, &b, 4); auto f = unpack_wrapper(test); f(buf, 8); }
70,631,288
70,631,385
Is int arr[ ] valid C++?
I am trying to understand if writing int arr[]; is valid in C++. So take for example: int a[]; //is this valid? extern int b[];//is this valid? int (*ptrB)[]; //is this valid? struct Name { int k[]; //is this valid? }; void func() { ptrB++; //is this valid? } int a[10]; int b[10]; void bar() { ptrB = &b;//is this valid? ptrB++; //is this valid? } int main() { int c[];//is this valid? extern int d[]; //is this valid? } int c[10]; int d[10]; I have read some comments on SO stating that int p[]; is not valid C++. So I wanted to know in what situations is this valid/invalid. For that I wrote the above snippet and want to understand through this example.
Let us look at each of the cases. Case 1 Here we have the statement int a[]; //this is a definition so size must be known This is not valid. Case 2 Here we have the statement: extern int b[];//this is a declaration that is not a definition This is valid. Here the type of b is incomplete. Also, b has external linkage. Case 3 Here we have: int (*ptrB)[]; This is valid. We say that ptrB is a pointer to an incomplete type. Case 4 Here we have: struct Name { int k[]; //NOT VALID }; This is not valid as from cppreference: Any of the following contexts requires type T to be complete: declaration of a non-static class data member of type T; Case 5 Here we have: void func() { ptrB++; //NOT VALID } This is not valid as from postfix increment's documentation: The operand expr of a built-in postfix increment or decrement operator must be a modifiable (non-const) lvalue of non-boolean (since C++17) arithmetic type or pointer to completely-defined object type. Case 6 Here we have: void bar() { ptrB = &b;//NOT VALID } This is not valid as from cppreference: The declared type of an array object might be an array of unknown bound and therefore be incomplete at one point in a translation unit and complete later on; the array types at those two points ("array of unknown bound of T" and "array of N T") are different types. Case 7 Here we have: void bar() { ptrB++; //NOT VALID This is not valid as from cppreferene: The type of a pointer to array of unknown bound, or to a type defined by a typedef declaration to be an array of unknown bound, cannot be completed. So we will get the same error as in case 5. Case 8 Here we have: int main() { int c[]; } This is not valid since this is a definition and so size must be known. Case 9 Here we have: int main() { extern int d[]; non-defining declaration } This is valid. d has external linkage.
70,631,823
70,632,330
Botan library - fastest digital signature verification
I am looking for the fastest algorithm, where I can verify a digital signature of a blob. The algorithm shouldn't necessarily be cryptographically secure, just make sure that it's not trivially fakable. Signing time neither counts in my case. Any suggestions? Also if possible, can you tell me what modules of botan do I need to use? (In order to only include them in my build!)
I've just found out that botan library has a cli. If you target this via --build-targets="static,cli" you can measure speed of different algorithms on your machine. Of course it will be specific to your computer, but for me this information was enough. You can check out different options of the botan cli at: https://botan.randombit.net/handbook/cli.html
70,631,878
70,658,383
Capturing a specific window using C++ returns old data
I'm currently working on a project that requires to take a screenshot a specific window. That's what I got so far: Main function int main() { LPCSTR windowname = "Calculator"; HWND handle = FindWindowA(NULL, windowname); while (!handle) { std::cout << "Process not found..." << std::endl; handle = FindWindowA(NULL, windowname); Sleep(100); } Mat img = captureScreenMat(handle); resetMat(); imwrite("test2.jpg", img); showInMovedWindow("IMG", img); waitKey(0); destroyAllWindows(); return 0; } winCapture Mat src; void showInMovedWindow(string winname, Mat img) { namedWindow(winname); moveWindow(winname, 40, 30); imshow(winname, img); } BITMAPINFOHEADER createBitmapHeader(int width, int height) { BITMAPINFOHEADER bi; bi.biSize = sizeof(BITMAPINFOHEADER); bi.biWidth = width; bi.biHeight = -height; bi.biPlanes = 1; bi.biBitCount = 32; bi.biCompression = BI_RGB; bi.biSizeImage = 0; bi.biXPelsPerMeter = 0; bi.biYPelsPerMeter = 0; bi.biClrUsed = 0; bi.biClrImportant = 0; return bi; } int getHeight(HWND hwnd) { RECT rect; GetWindowRect(hwnd, &rect); int height = rect.bottom - rect.top; return height; } int getWidth(HWND hwnd) { RECT rect; GetWindowRect(hwnd, &rect); int width = rect.right - rect.left; return width; } Mat captureScreenMat(HWND hwnd) { HDC hwindowDC = GetDC(hwnd); HDC hwindowCompatibleDC = CreateCompatibleDC(hwindowDC); SetStretchBltMode(hwindowCompatibleDC, COLORONCOLOR); int screenx = GetSystemMetrics(SM_XVIRTUALSCREEN); int screeny = GetSystemMetrics(SM_YVIRTUALSCREEN); int width = getWidth(hwnd); int height = getHeight(hwnd); src.create(height, width, CV_8UC4); HBITMAP hbwindow = CreateCompatibleBitmap(hwindowDC, width, height); BITMAPINFOHEADER bi = createBitmapHeader(width, height); //DEBUG cout << hbwindow << endl; cout << hwindowCompatibleDC << endl; cout << hwindowDC << endl; SelectObject(hwindowCompatibleDC, hbwindow); StretchBlt(hwindowCompatibleDC, 0, 0, width, height, hwindowDC, screenx, screeny, width, height, SRCCOPY); GetDIBits(hwindowCompatibleDC, hbwindow, 0, height, src.data, (BITMAPINFO*)&bi, DIB_RGB_COLORS); DeleteObject(hbwindow); DeleteDC(hwindowCompatibleDC); DeleteDC(hwindowDC); ReleaseDC(NULL, hwindowDC); return src; } void resetMat() { src.release(); } Most windows work really well with this approach, but there are some windows that are working the first time, I try to take a img of them, but every time I try to take another screenshot of the same process, it just gives me the first screenshot I took of it. It only works again after a restart of the process and even then It just works again for one screenshot and all after are the same. I thought it would be some kind of memory leak, but I'm deleting all the objects and releasing the handle. I think that something is wrong with the handle, but I couldn't figure out what. I'm not familiar with working with the windowsAPI and hope someone knowns more than me. Fixed: Process blocked creating handle.
When you call SelectObject you must save the previous-selected handle (available from the return value) and you MUST select it back before deleting or releasing the device context. Right now you are breaking a bunch of rules. Deleting a bitmap which is selected into a device context. Deleting a DC gotten from GetDC. Calling both DeleteDC and ReleaseDC on the same handle. Passing NULL as the first parameter of ReleaseDC, which should be the same HWND passed to GetDC. Deleting a DC without selecting the original bitmap back into it. These bugs royally mess up the window DC. If it was a transient DC, the system probably cleans up your mess immediately. But if the window class has the CS_OWNDC or CS_CLASSDC flags, you do permanent damage to the window. That's why your method appears to work with some windows and not others.
70,632,282
70,635,371
Install prebuilt static library dependency with the parent library
My project structure looks like this: Parent/ CMakeLists.txt file.cpp third_party/ dependency/ CMakeLists.txt lib/ dependency.lib Note that dependency.lib is a precompiled/prebuilt library: I don't even have sources for it. When I install Parent, I want it to go into a dist folder like this (within the previous tree structure but omitted for clarity): Parent/ dist/ Parent/ include/ bin/ lib/ cmake/ ParentTargets.cmake Parent.lib dependency.lib The idea here is to just get both the generated as well as the dependency libraries all in one place for easier install. Relevant parts of Parent's CMakeLists.txt look like this (omitting a lot of stuff like includes, etc.): cmake_minimum_required(VERSION 3.22) project(Parent VERSION 0.1.0 LANGUAGES C CXX) add_library(Parent) target_sources(Parent PRIVATE file.cpp) add_subdirectory("${CMAKE_SOURCE_DIR}/third_party/dependency") target_link_libraries(Parent PRIVATE dependency) # Manual copy of dependency.lib to install location install(DIRECTORY "${CMAKE_SOURCE_DIR}/third_party/dependency/lib/" DESTINATION lib FILES_MATCHING PATTERN "dependency.lib" ) # Install all targets to ParentTargets export set. # (omitting install dir variables, components, etc. for clarity) install( TARGETS Parent dependency EXPORT ParentTargets LIBRARY DESTINATION lib ARCHIVE DESTINATION lib ) # Write ParentTargets export set to targets file directly in install folder install(EXPORT ParentTargets FILE ParentTargets.cmake NAMESPACE Parent:: DESTINATION lib/cmake ) And this is what I have for the dependency's CMakeLists.txt: add_library(dependency INTERFACE) target_link_libraries(dependency INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/lib/dependency.lib> $<INSTALL_INTERFACE:${CMAKE_INSTALL_PREFIX}/lib/dependency.lib> ) This almost sort of works, the issue is that if you look at the generated ParentTargets.cmake, this is what CMake generates for the dependency target: # Create imported target Parent::dependency add_library(Parent::dependency INTERFACE IMPORTED) set_target_properties(Parent::dependency PROPERTIES INTERFACE_LINK_LIBRARIES "E:/absolute/path/Parent/dist/Parent/lib/dependency.lib" ) ...its a hard-coded absolute path to my installation directory. This is not great, and usually for built libraries CMake would have generated a path like ${_IMPORT_PREFIX}/lib/dependency.lib, which is what I wanted and important to have the install relocatable. Here are my questions: Is this the right way of doing this? I could never find a good reference on how to package dependency static libraries alongside your project, and CMake doesn't seem to do this "on its own" too eagerly (I even had to manually copy the .lib there as you can see); How do I get CMake to use ${_IMPORT_PREFIX} there? I can't just use that on my CMakeLists.txt as it would evaluate to the empty string during generation, and I can't escape it like \${_IMPORT_PREFIX} as it still places the escaped version in ParentTargets.cmake...
Is this the right way of doing this? I could never find a good reference on how to package dependency static libraries alongside your project, and CMake doesn't seem to do this "on its own" too eagerly (I even had to manually copy the .lib there as you can see); I think what you're doing is fine. If it were me, I would create and link to an IMPORTED STATIC target named Parent::ThirdParty::dependency for dependency.lib in both the main build and in the package config file, and set its IMPORTED_LOCATION property appropriately in each. The reason being that CMake will validate that anything you link to that contains a :: in its name is a CMake target. This tends to lead to fewer surprises on the link line and lets you attach things like include paths to the library. How do I get CMake to use ${_IMPORT_PREFIX} there? [...] Your issue is here: $<INSTALL_INTERFACE:${CMAKE_INSTALL_PREFIX}/lib/dependency.lib> CMAKE_INSTALL_PREFIX is set to E:/absolute/path/Parent/dist/Parent immediately and CMake has no chance to replace it with something like ${_IMPORT_PREFIX}. Fortunately, there is a generator expression for this. $<INSTALL_INTERFACE:$<INSTALL_PREFIX>/lib/dependency.lib> Try that instead.
70,632,495
70,634,303
How to build Apple's Metal-cpp example using CMake?
Recently, Apple has released a library to use Metal directly using C++. The example that I've found online (https://github.com/moritzhof/metal-cpp-examples), works if I copy the source code and follow the steps outlined by Apple (https://developer.apple.com/metal/cpp/) in Xcode. I don't use the included Xcode project files, to avoid any "hidden" settings. Now I'm trying to get the same example to build using CMake, with this CMakeLists.txt: cmake_minimum_required(VERSION 3.8) project(HelloWorld) set(CMAKE_CXX_STANDARD 17) include_directories(${PROJECT_SOURCE_DIR}/metal-cpp) set(SOURCE_FILES metal-cpp-test/main.cpp metal-cpp-test/metal_adder.cpp) add_executable(program ${SOURCE_FILES}) # specify which libraries to connect # target_link_libraries(program ${METAL}) # target_link_libraries(program ${FOUNDATION}) # target_link_libraries(program ${QUARTZCORE}) find_library(METAL Metal) find_library(FOUNDATION Foundation) find_library(QUARTZCORE QuartzCore) target_link_libraries(program stdc++ "-framework Metal" "-framework Foundation" "-framework QuartzCore" objc) It compiles successfully, but the line auto lib = _device->newDefaultLibrary(); Now seems to return a null-ptr. Any idea what the reason for this could be and how to solve this?
All .metal files in an Xcode project that builds an application are compiled and built into a single default library. _device->newDefaultLibrary() return a new library object that contains the functions from the default library. This method returns nil if the default library cannot be found. Since you are not using Xcode, you should manually compile Metal Shading Language source code and build a Metal library. Then, at runtime, call the newLibrary(filePath, &error) method to retrieve and access your library as a MTL::Library object. NS::String* filePath = NS::String::string("The full file path to a .metallib file", NS::UTF8StringEncoding); NS::Error* error; auto library =_device->newLibrary(filePath, &error); if(error) { }
70,632,532
70,633,380
How do I clear a stream in C++ for a nanoPB protocol buffer to use?
I'm using nanopb in a project on ESP32, in platformIO. It's an arduino flavored C++ codebase. I'm using some protobufs to encode data for transfer. And I've set up the memory that the protobufs will use at the root level to avoid re-allocating the memory every time a message is sent. // variables to store the buffer/stream the data will render into... uint8_t buffer[MESSAGE_BUFFER_SIZE]; pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); // object to hold the data on its way into the encode action... TestMessage abCounts = TestMessage_init_zero; Then I've got my function that encodes data into this stream via protobufs (using nanoPB)... void encodeABCounts(int32_t button_a, int32_t button_b, String message) { // populate our data structure... abCounts.a_count = button_a; abCounts.b_count = button_b; strcpy(abCounts.message, message.c_str()); // encode the data! bool status = pb_encode(&stream, TestMessage_fields, &abCounts); if (!status) { Serial.println("Failed to encode"); return; } // and here's some debug code I'll discuss below.... Serial.print("Message Length: "); Serial.println(stream.bytes_written); for (int i = 0; i < stream.bytes_written; i++) { Serial.printf("%02X", buffer[i]); } Serial.println(""); } Ok. So the first time this encode action occurs this is the data I get in the serial monitor... Message Length: 14 Message: 080110001A087370656369616C41 And that's great - everything looks good. But the second time I call encodeABCounts(), and the third time, and the forth, I get this... Message Length: 28 Message: 080110001A087370656369616C41080210001A087370656369616C41 Message Length: 42 Message: 080110001A087370656369616C41080210001A087370656369616C41080310001A087370656369616C41 Message Length: 56 Message: 080110001A087370656369616C41080210001A087370656369616C41080310001A087370656369616C41080410001A087370656369616C41 ...etc So it didn't clear out the buffer/stream when the new data went in. Each time the buffer/stream is just getting longer as new data is appended. How do I reset the stream/buffer to a state where it's ready for new data to be encoded and stuck in there, without reallocating the memory? Thanks!
To reset the stream, simply re-create it. Now you have this: pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); You can recreate it by assigning again: stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); Though you can also move the initial stream declaration to inside encodeABCounts() to create it every time, if you don't have any particular reason to keep it around after use. The stream creation is very lightweight, as it just stores the location and size of the buffer.
70,632,731
70,633,654
Add a QTreeView in QML
I would like to register a QTreeView c++ object to QML. I tried to register it like this: main.cpp: qmlRegisterType<QTreeView>("com.MyApp.QTreeView", 1, 0, "QTreeView"); relevant code in main.qml import com.MyApp.QTreeView 1.0 QWindow { QTreeView{ headerHidden: true } } Result: it compiles. headerHidden property is found so it is registered correctly. However I have an error at runtime: ASSERT: "!d->isWidget" in file kernel\qobject.cpp, line 2090
QWidgets are not directly compatible with QML such that they can be embedded in a QML view. They are two different UI technologies and cannot be used together in that fashion. You can however embed a QML view inside of a QWidget hierarchy: https://www.ics.com/blog/combining-qt-widgets-and-qml-qwidgetcreatewindowcontainer Or just use the QML TreeView component instead: https://doc.qt.io/qttreeview/qml-treeview.html
70,632,917
70,633,001
c++ pass parameters to thread as reference not working
I wrote a code that create thread and send to him parameters as reference, but I get an red underline under the function name like I cant call it. Someone know what went wrong in my code my code: #include "getPrimes.h" void getPrimes(const int& begin, const int& end, std::vector<int>& primes) { int i = 0, j = 0; for (i = begin; i <= end; i++) { if (i > 1) { for (j = 2; j <= i / 2; j++) { if (i % j != 0) { primes.push_back(i); } } } } } std::vector<int> getPrimes(const int& begin, const int& end) { std::vector<int> vector; std::thread thread(getPrimes, std::ref(begin), std::ref(end), std::ref(vector)); // I get the red underline here } the error I get
Since getPrimes is overloaded, you'll need to help the compiler with the overload resolution. Example: std::vector<int> getPrimes(const int& begin, const int& end) { std::vector<int> vector; std::thread thread( // see static_cast below: static_cast<void(*)(const int&, const int&, std::vector<int>&)>(getPrimes), std::cref(begin), std::cref(end), std::ref(vector)); // ... thread.join(); return vector; } A simplified example: void foo(int) {} void foo(int, int) {} int main() { // auto fp = foo; // same problem - which foo should fp point at? // same solution: auto fp = static_cast<void(*)(int)>(foo); }
70,632,986
70,638,172
Store float with exactly 2 decimal places in C++
I would like to take a decimal or non-decimal value and store it as a string with exactly 2 decimal places in C++. I want to do this to show it as a monetary value, so it is always $10.50 or $10.00 rather than $10.5 or $10. I don't just want to print this, I want to store it, so I don't believe setprecision will work here. I'm doing this in a Qt application, so if there is a way to do it using Qt I can use that as well. For example: int cents = 1000; std::string dollars; //should get value from cents formatted to 10.00 UPDATE: It seems I don't have the vocabulary yet as I am just beginning to learn C++ to articulate what I am trying to do. Here is what I want to do using Python: str_money = '$ {:.2f}'.format(num) In this example, num can be a decimal or not (10 or 10.5 for example) and str_money is a variable that is assigned the value of num as a decimal with exactly 2 numbers after the decimal (in this example, str_money would become 10.00 or 10.50). I want it to store this in a string variable, and I don't need it to store the '$' with the value. Can I do this in C++?
Your decision to store monetary amounts as integer number of cents is a wise one, because floating-point data types (such as float or double) are generally deemed unsuitable for dealing with money. Also, you were almost there by finding std::setprecision. However, it needs to be combined with std::fixed to have the expected effect (because std::setprecision means different things depending on which format option is used: the default, scientific or fixed). Finally, to store the formatting result in an std::string instead of directly printing it to the console, you can use a string-based output stream std::ostringstream. Here is an example: #include <iomanip> #include <iostream> #include <sstream> #include <string> std::string cents_to_dollars_string(const int cents) { static constexpr double cents_per_dollar{ 100. }; static constexpr int decimal_places{ 2 }; std::ostringstream oss; oss << std::fixed << std::setprecision(decimal_places) << cents / cents_per_dollar; return oss.str(); } int main() { const int balance_in_cents{ -420 }; const std::string balance_in_dollars{ cents_to_dollars_string(balance_in_cents) }; std::cout << "Your balance is " << balance_in_dollars << '\n'; } Here, we first define the function cents_to_dollars_string, which takes the amount in cents as an int and returns an std::string containing the formatted amount of dollars. Then, in main we call this function to convert an amount (in cents) stored in an int variable balance_in_cents to a string and store it into an std::string variable balance_in_dollars. Finally, we print the balance_in_dollars variable to the console.
70,633,075
70,641,425
Get pointer to overloaded function that would be called
Please refer to the following: struct functorOverloaded { void operator()(const int& in_, ...) const {} void operator()(short in_) {} }; // helper to resolve pointer to overloaded function template <typename C, typename... OverloadArgs> auto resolve_overload( std::invoke_result_t<C, OverloadArgs...> (C::* func)(OverloadArgs..., ...) const ) { return func; }; int main(int argc, char **argv) { using C = const functorOverloaded; // works with exact function type using myT = decltype(resolve_overload<C, const int&>(&C::operator())); // can call with something convertible to const int& static_assert(std::is_invocable_v<C,int>, "!!!"); // how to get the pointer to the overload that would be called when passed int (or double)? // the next line doesn't compile (error C2672: 'resolve_overload': no matching overloaded function found) using myT2 = decltype(resolve_overload<C, int>(&C::operator())); return 0; } The above code allows retrieving a pointer to a specific overload of a function (operator() in this case), see here. One must know the exact argument type (const int&) in this case to get the pointer, even though i can just call the specific overload with a plain int, or even double. Is it possible to get a pointer to the overload that would be called with the specific argument (assuming the call is resolvable / not ambiguous)? Edit: adding context: I am writing a invocable_traits library for introspecting a callable. E.g., given a Callable, it will tell you the return type, arity and argument types, amongst some other properties. To support functors (including lambdas) with overloaded (or templated) operator(), the API of invocable_traits allows specifying call arguments to disambiguate which overload is to be used (or to instantiate the template). However, one must know the exact argument type (const int& in the example above), simply specifying int won't do in that case as there is no function with signature R operator()(int). Ideally, I'd like to allow discovering the signature of the exact overload/instantiation that gets called given the provided input argument types, ideally even taking into account any implicit conversions that are applied. Is this possible?
There is no way to get the function of an overload-set which would be called with the given arguments, unless you already know its signature. And if you know, what's the point? The problem is that for any given arguments, taking into account implicit conversions, references, cv-qualifiers, noexcept, old-style vararg, default arguments, and maybe also literal 0 being a null pointer constant, there are an infinite number of function-signatures which would match. And there is currently no facility for "just" listing all candidates.
70,633,179
70,633,232
Shorthand for using multiple names from the same C++ namespace
I'm writing a chess program and I've defined the classes I've created under the chess namespace. To shorten the code in files that use those classes, I preface it with using chess::Point, chess::Board, chess::Piece and so on. Is there a way to specify that I'm bringing in scope multiple elements from the same namespaces like in Rust? (Such as use chess::{Point,Board,Piece}.)
No. But you can bring them all at once, using: using namespace chess; // then use Point instead of chess::Point, Board instead of chess::Board, etc
70,633,339
70,633,381
Why std::equal crashes if second vector empty
I am using std::equals defined in <algorithm> to check if two vectors are equal. It crashes when second vector is empty. I could avoid crash by checking if second vector is empty, but is there a reason to not include the check in equal function itself ? Sample code: std::vector<int> a; for (int i = 0; i < 3; ++i) a.emplace_back(i); std::vector<int> b; for (int i = 0; i < 0; ++i) b.emplace_back(i); std::equal(a.begin(), a.end(), b.begin());
You call std::equal with 3 arguments, which in https://en.cppreference.com/w/cpp/algorithm/equal says: Returns true if the range [first1, last1) is equal to the range [first2, first2 + (last1 - first1)), and false otherwise which will cause undefined behavior in you case Use std::equal with 4 arguments instead: std::equal(a.begin(), a.end(), b.begin(), b.end()); which will do: Returns true if the range [first1, last1) is equal to the range [first2, last2), and false otherwise. which is what you want. Or, you can just use operator ==. std::vector overloads one: a == b;
70,634,034
70,635,514
Libcurl - CURLSHOPT_LOCKFUNC - how to use it?
Please tell me the nuances of using the option CURLSHOPT_LOCKFUNC ? I found an example here. I can't quite understand, is there an array of mutexes used to block access to data? --Here is this part of the code from the example: static pthread_mutex_t lockarray[NUM_LOCKS]; Is it an array of mutexes ? //..... static void lock_cb(CURL *handle, curl_lock_data data, curl_lock_access access, void *userptr) { (void)access; (void)userptr; (void)handle; pthread_mutex_lock(&lockarray[data]); } That is, from this section of code - I can conclude that different mutexes are used to lock CURLSHOPT_LOCKFUNC ? I don't understand how it is? Isn't there more than one mutex needed to synchronize threads to access data? And this part of the code is also not clear: pthread_mutex_lock(&lockarray[data]); What kind of variable is data ? The documentation says: https://curl.se/libcurl/c/CURLSHOPT_LOCKFUNC.html The data argument tells what kind of data libcurl wants to lock. Make sure that the callback uses a different lock for each kind of data. What means: "what kind of data libcurl wants to lock" ?? I can't understand.
Yes, the code is using an array of mutexes. curl_lock_data is an enum that is defined in curl.h and specifies the different types of data that curl uses locks for: /* Different data locks for a single share */ typedef enum { CURL_LOCK_DATA_NONE = 0, /* CURL_LOCK_DATA_SHARE is used internaly to say that * the locking is just made to change the internal state of the share * itself. */ CURL_LOCK_DATA_SHARE, CURL_LOCK_DATA_COOKIE, CURL_LOCK_DATA_DNS, CURL_LOCK_DATA_SSL_SESSION, CURL_LOCK_DATA_CONNECT, CURL_LOCK_DATA_LAST } curl_lock_data; Since the values are sequential, the code is using them as indexes into the array. So, for example, when multiple threads are accessing shared cookie data, they will lock/unlock the CURL_LOCK_DATA_COOKIE mutex. curl_lock_access is another enum defined in curl.h, which specifies why a given lock is being obtained: /* Different lock access types */ typedef enum { CURL_LOCK_ACCESS_NONE = 0, /* unspecified action */ CURL_LOCK_ACCESS_SHARED = 1, /* for read perhaps */ CURL_LOCK_ACCESS_SINGLE = 2, /* for write perhaps */ CURL_LOCK_ACCESS_LAST /* never use */ } curl_lock_access; The difference between these reasons doesn't matter for a mutex, which has only a notion of exclusive access, meaning only 1 thread at a time can hold the lock. That is why the code is not using the access parameter. But, other types of locks, for instance a RW (reader/writer) lock, do have a concept of shared access (ie, multiple threads can hold the lock at the same time) vs exclusive access. When multiple threads want to access the same shared data for just reading only, it makes sense for them to not block each other. Only when a thread wants to modify the shared data should other threads then be blocked from accessing that data, for reading or writing, until the modification is finished. For example: const int NUM_LOCKS = CURL_LOCK_DATA_LAST + 1; static pthread_rwlock_t lockarray[NUM_LOCKS]; ... static void lock_cb(CURL *handle, curl_lock_data data, curl_lock_access access, void *userptr) { (void)handle; (void)userptr; switch (access) { case CURL_LOCK_ACCESS_SHARED: pthread_rwlock_rdlock(&lockarray[data]); break; case CURL_LOCK_ACCESS_ SINGLE: pthread_rwlock_wrlock(&lockarray[data]); break; } } static void unlock_cb(CURL *handle, curl_lock_data data, curl_lock_access access, void *userptr) { (void)handle; (void)access; (void)userptr; pthread_rwlock_unlock(&lockarray[data]); }
70,635,056
70,635,296
C++: Is accessing values in pairs so much more efficient than accessing array elements?
Suppose we have an array of doubles x and an array of indices y, and we want to sort these indices by the respective values in x (so, sort [i in y] by x[i] as key). We can then create an array of pairs, with one component being the key value and one being the index, and for example do something like this: boost::sort::spreadsort::float_sort(sortdata, sortdata + n, [](const std::pair<double, int> &a, const unsigned offset) -> boost::int64_t { return boost::sort::spreadsort::float_mem_cast<double, boost::int64_t>(a.first) >> offset; }, [](const std::pair<double, int> &a, const std::pair<double, int> &b) -> bool { return a.first < b.first; }); This costs quite a bit of memory, so instead we can omit the creation of this array of pairs and directly use the data like this: boost::sort::spreadsort::float_sort(y, y + n, [x](const int a, const unsigned offset) -> boost::int64_t { return boost::sort::spreadsort::float_mem_cast<double, boost::int64_t>(x[a]) >> offset; }, [x](const int a, const int b) -> bool { return x[a] < x[b]; }); Now, when using this on very large data (let’s say 50000000 entries), the second method takes more than twice as long as the first. As far as I know, a std::pair is simply a struct. So, can it really be that an array access is so much less efficient than a struct access? Or, am I doing something wrong here? Here is a full example for comparisation: #include <cstdlib> #include <ctime> #include <boost/sort/spreadsort/spreadsort.hpp> #include <iostream> int main() { int n = 50000000; double *x = new double[n]; int *y = new int[n]; std::pair<double, int> *sortdata = new std::pair<double, int> [n]; for (int i=0; i < n; i++) { x[i] = ((double) std::rand()) / ((double) std::rand()); sortdata[i].first = x[i]; y[i] = i; sortdata[i].second = i; } std::time_t t = std::time(0); boost::sort::spreadsort::float_sort(sortdata, sortdata + n, [](const std::pair<double, int> &a, const unsigned offset) -> boost::int64_t { return boost::sort::spreadsort::float_mem_cast<double, boost::int64_t>(a.first) >> offset; }, [](const std::pair<double, int> &a, const std::pair<double, int> &b) -> bool { return a.first < b.first; }); std::cout << std::time(0)-t << "\n"; t = std::time(0); boost::sort::spreadsort::float_sort(y, y + n, [x](const int a, const unsigned offset) -> boost::int64_t { return boost::sort::spreadsort::float_mem_cast<double, boost::int64_t>(x[a]) >> offset; }, [x](const int a, const int b) -> bool { return x[a] < x[b]; }); std::cout << std::time(0)-t << "\n"; } Running this with g++ -O2 gives 3 seconds for the first and 9 seconds for the last on my system.
Not an expert, but here is what I think is going on: Jumping around in memory is a costly operation, no matter the programming language. This has to do with the caching architecture of your CPU. In pairs the data is stored interleaved in memory. There is no class boundary or anything like that. It looks like this: value0 index0 value1 index1 value2 index2 ... Now when you store data in two arrays your data will look like this: value0 value1 value2 ......... index0 index1 index2 ..... Ok, now let's see what happens when the sorting algorithm tries to figure out whether the data at index 46 should go before or after the data at index 47: In the case of pairs: 1. ask ram for value46 (expensive!) because of how cachelines work ~ 64bytes of data will be pulled. that is: value46 index46 value47 index47 are pulled, maybe a bit more. 2. ask ram for value47 (cheap, it's already cached) In the case of two arrays: 1. ask ram for index46 (expensive) this will pull index46,index47,... 2. ask ram for index47 (cheap) 3. ask ram for x[index46] (expensive) this will pull x[index46],x[index46+1...] 4. ask ram for x[index47] (should be next to x[index46]? not sure... could be cheap, could be expensive) Well, I'm not sure about that last memory fetch, but the point is that you're jumping around in memory around two to three times as much, and I'm pretty sure that's why you're measuring a roughly twice as long runtime. Here is a final example to get this point across: int N = 100000; float data[N] = {... random data...}; int idx_1[N] = {0,1,....}; int idx_2[N] = {... random permutation of 0,...N-1}; // this will be very fast. // the cache predictor always gets it right. float sum_1 = 0; for(int i = 0; i < N; i++) sum_1 += data[idx_1[i]]; // this will be very slow. // the cache predictor always gets it wrong. float sum_2 = 0; for(int i = 0; i < N; i++) sum_2 += data[idx_2[i]];
70,635,531
70,635,779
How to print the remaining set of numbers in C++?
Say there is a set U = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} and I created a C++ program and I, using some logic printed the numbers { 1, 3, 6, 7, 9} (let's call it set A), so the remaining numbers are {2, 4, 5, 8, 1} (let's call it set B) and U = A + B Is there a direct way to print out set B numbers (B = U - A)? (Without actually reversing the logic from which I printed numbers of Set A) Like if I printed even numbers, then the remaining are odd numbers and I can easily code to display odd numbers. But I am asking if there is another "direct" way of doing it? Similarly, if I printed all prime numbers from 1-100 then I can kind of reverse the logic and print the numbers which were NOT printed (here, which were NOT prime), but I am NOT asking for that, I am asking is there a direct way to print the remaining set of numbers? PS: I only know basic C++ and I have NOT yet started DSA (Data Structures and Algorithms) still any level answers are welcome, I will try hard to interpret it :)
Anytime you hear "find the missing elements" or "find the duplicate elements" type problem, you should immediately think "hash table". Do an internet search for Hash Table, but the wikipedia article has the basics. std::unordered_map and std::unordered_set are collection classes in C++ that are traditionally based on hash tables. Given a set U: unordered_set<int> U = { 1,2,3,4,5,6,7,8,9,10 }; And a set A that is a subset of U: unordered_set<int> A = { 1,3,5,7,9 }; Then B = U - A can be computed as unordered_set<int> B; for (int u : U) // for each item u in set U { if (A.find(u) == A.end()) // if u is not in "A" { B.insert(u); // add it to "B". } } for (int b : B) { cout << b << endl; } If you need the output to be sorted, change the declaration of B from std::unordered_set to just std::set.
70,635,676
70,635,967
How to use range projection in a sorting algorithm?
I'm trying to wrap my bonehead around the ranges. So decided to implement some basic sort procedures as a range algorithm and like in the std::ranges::sort(). I peeked its implementation but didn't understand how to make use of projection: #include <iterator> #include <functional> #include <ranges> namespace sort { namespace ranges { struct insertion_fn { template <std::random_access_iterator I, std::sentinel_for<I> S, typename Comp = std::ranges::less, typename Proj = std::identity> requires std::sortable<I, Comp, Proj> constexpr I operator()(I first, S last, Comp comp = {}, Proj proj = {}) const { if (first == last) return first; std::size_t N = std::ranges::distance(first, last); I last_iter = std::ranges::next(first, last); for (std::size_t i = 1; i < N; ++i) { for (std::size_t j = i; j > 0 && comp(*(first + j), *(first + j - 1)); --j) { std::iter_swap(first + j, first + j - 1); } } return last_iter; } template <std::ranges::random_access_range R, class Comp = std::ranges::less, class Proj = std::identity> requires std::sortable<std::ranges::iterator_t<R>, Comp, Proj> constexpr std::ranges::borrowed_iterator_t<R> operator()(R &&r, Comp comp = {}, Proj proj = {}) const { return (*this)(std::ranges::begin(r), std::ranges::end(r), std::move(comp), std::move(proj)); } }; inline constexpr insertion_fn insertion; } // namespace ranges } // namespace sort This test fails: TEST_CASE("Insertion: Make use of range projection") { namespace stdr = std::ranges; using person = std::pair<std::string, std::string>; std::vector<person> people{ {"tintin", "detective"}, {"snowy", "lifeguard"}, {"haddock", "captain"}}; auto expected = people; stdr::sort(expected, std::less{}, &person::first); auto test = people; sort::ranges::insertion(people, std::less{}, &person::first); REQUIRE_EQ(test, expected); } My question is how to where to handle projection into the this implementation. Sorry for the long code snippets.
The point of the projection in sort is to change the comparison being used. For example: std::vector<std::string> words = {"a", "quick", "brown", "fox"}; // sorts by normal lexicographic order, so you get [a, brown, fox, quick] std::ranges::sort(words); // same, but reversed, so [quick, fox, brown, a] std::ranges::sort(words, std::greater()); // sorts words in increasing order by size, so [a, fox, brown, quick] // (or quick, brown) std::ranges::sort(words, std::less(), std::ranges::size); Your code is simply comparing the elements directly: comp(*(first + j), *(first + j - 1)) Which itself is a long form of: comp(first[j], first[j-1]) Instead of comparing the elements directly, you need to compared the projected elements: comp(proj(first[j]), proj(first[j-1])) A different way of thinking about it is that a projection is a convenient way of alternating part of the comparison - so you can keep the < part (the Comp parameter) but just change which part you're <-ing (the Proj parameter).
70,635,683
70,635,809
What should `foo.template bar()` do when there's both a template and a non-template overload?
A coworker shared this code with me: run on gcc.godbolt.org #include <iostream> struct A { void foo() {std::cout << "1\n";} template <typename T = int> void foo() {std::cout << "2\n";} }; int main() { A x; x.template foo(); } GCC prints 1, Clang prints 2, and MSVC complains about missing template arguments. Which compiler is correct?
[temp.names]/5 says that a name prefixed by template must be a template-id, meaning that it must have a template argument list. (Or it can refer to a class/alias template without template argument list, but this is deprecated in the current draft as a result of P1787R6 authored by @DavisHerring.) There is even an example almost identical to yours under it, identifying your use of template as ill-formed. The requirement and example comes from CWG defect report 96, in which the possible ambiguity without the requirement is considered. Open GCC bug report for this is here. I was not able to find a Clang bug report, but searching for it isn't that easy. Its implementation status page for defect reports however does list the defect report as unimplemented.
70,636,347
70,637,145
c++ beginner needs help inputing & outputing data! what am i doing wrong?
so this code is for a car garage, filling info of the accepted cars to be repaired everyday. and print the result for each car in a line. i have two problems with my code. first is, starting the second time the "do...while... " loop runs, i cant have an input for "enter car name" second is the final output, i want it in straight neat lines but can't ! I'll be so grateful if someone gives me the edited and fixed version of my code! #include <iostream> using namespace std; int D; //are you done? int main() { int i = 0; //counting cars string cars[10][7] = {}; string C = cars[i][1]; //car name string N = cars[i][2]; //owner name string Y = cars[i][3]; //car production year string R = cars[i][4]; //car color string K = cars[i][5]; //car life in km string M = cars[i][6]; //car problem string H = cars[i][7]; //time of arrival do { i++; cout << endl; cout << " enter car name "; getline(cin, cars[i][1]); cout << endl; cout << " enter owner name "; getline(cin, cars[i][2]); cout << endl; cout << " enter production year "; getline(cin, cars[i][3]); cout << endl; cout << " enter car color "; getline(cin, cars[i][4]); cout << endl; cout << " enter car life in km "; getline(cin, cars[i][5]); cout << endl; cout << " enter car problem "; getline(cin, cars[i][6]); cout << endl; cout << " enter time of arrival "; getline(cin, cars[i][7]); cout << endl; cout << "this was car :" << i << endl; cout << endl; cout << "type '1' to continue. type '2' if you are done." << endl; cin >> D; } while (D == 1); cout << endl << "ended ! here is today's list of cars :"; cout << endl; cout << endl; for (i = 0; i < 20; i++) { for (int j = 0; j < 7; cout << "\t" << cars[i][j] && j++); { } cout << endl; } return 0; }
Here is the fixed code you're looking for: #include <iostream> #include <string> #include <array> int main( ) { std::size_t idx { }; // counting cars constexpr std::size_t maxCarCount { 20 }; constexpr std::size_t carAttributesCount { 7 }; std::array< std::array<std::string, carAttributesCount>, maxCarCount > cars { }; char isDone { }; // are you done? do { std::cout << "\n enter car name: "; std::getline( std::cin, cars[idx][0] ); std::cout << "\n enter owner name: "; std::getline( std::cin, cars[idx][1] ); std::cout << "\n enter production year: "; std::getline( std::cin, cars[idx][2] ); std::cout << "\n enter car color: "; std::getline( std::cin, cars[idx][3] ); std::cout << "\n enter car life in km: "; std::getline( std::cin, cars[idx][4] ); std::cout << "\n enter car problem: "; std::getline( std::cin, cars[idx][5] ); std::cout << "\n enter time of arrival: "; std::getline( std::cin, cars[idx][6] ); std::cout << "\nThis was car #" << idx + 1 << '\n'; std::cout << "\nType '1' to continue, type '2' if you are done.\n"; std::cin >> isDone; std::cin.ignore( ); // this solves one of your issues ++idx; } while ( isDone == '1' ); std::cout << "\nEnded! Here is today's list of cars:\n\n"; for ( std::size_t carIdx { }; carIdx < idx; ++carIdx ) { for ( std::size_t carAttributeIdx { }; carAttributeIdx < carAttributesCount; ++carAttributeIdx ) { std::cout << "\t" << cars[carIdx][carAttributeIdx]; } std::cout << '\n'; } } Keep in mind that if the info for more than 20 cars is entered then the cars will overflow and cause undefined behavior. It has space for only 20 cars. If you want to remove this limitation then switch to std::vector< std::vetor<std::string> > cars( 20, std::vector<std::string>(7) );. Sample input/output: enter car name: 911 enter owner name: John enter production year: 1999 enter car color: Yellow enter car life in km: 3100 enter car problem: broken enter time of arrival: 12:06 This was car #0 Type '1' to continue, type '2' if you are done. 1 enter car name: 718 enter owner name: Kate enter production year: 2021 enter car color: Red enter car life in km: 465 enter car problem: broken headlight enter time of arrival: 13:45 This was car #1 Type '1' to continue, type '2' if you are done. 2 Ended! Here is today's list of cars: 911 John 1999 Yellow 3100 broken 12:06 718 Kate 2021 Red 465 broken headlight 13:45
70,636,358
70,637,734
can't change Skeletal Mesh in UE4
Actually, I was trying to change the skeletal mesh of car in UE4, in the wheeled vehicle demo project which comes in ue4 c++ API. Firstly I inherited blueprint from ue4 wheeled vehicle c++ class. Then I opened blueprint editor and replaced default skeletal mesh to my skeletal mesh. I assigned bone names correctly. Then everything was in its place(according to me) Then I recompiled. Then I placed blueprint in level and possess it. But when I clicked W,A,S,D keys it doesn't work. And the car doesn't move at all. If I am doing any mistake, please guide me through steps and how can I resolve it.
The animation blueprint is also tied to a specific Skeleton. If your new skeletal mesh uses a different skeleton than the one currently assigned to your skeletal mesh component, then you will need to create a new corresponding animation blueprint to use with it.
70,636,962
70,637,034
Multiplying and adding float numbers
I have a task to convert some c++ code to asm and I wonder if what I am thinking makes any sense. First I would convert integers to floats. I would like to get array data to sse register, but here is problem, because I want only 3 not 4 integers, is there way to overcome that? Then I would convert those integers to floats using CVTDQ2PS and I would save those numbers in memory. For the const numbers like 0.393 I would make 3 vectors of floats and then I would do same operation three times so I will think about sepiaRed only. For that I would get my converted integers into sse register and I would multiply those numbers which would give me the result in xmm0 register. Now how can I add them together? I guess my two questions are: how can I get 3 items from array to sse register, so that I can avoid any problems. And then how can I add three numbers in xmm0 register together. tmpGreen = (float)pixels[i + 1]; tmpRed = (float)pixels[i + 2]; tmpBlue = (float)pixels[i]; sepiaRed = (int)(0.393 * tmpRed + 0.769 * tmpGreen + 0.189 * tmpBlue); //red sepiaGreen = (int)(0.349 * tmpRed + 0.686 * tmpGreen + 0.168 * tmpBlue); //green sepiaBlue = (int)(0.272 * tmpRed + 0.534 * tmpGreen + 0.131 * tmpBlue); //blue
You can't easily horizontally add 3 numbers together; Fastest way to do horizontal SSE vector sum (or other reduction) What you can efficiently do is map 4 pixels in parallel, with vectors of 4 reds, 4 greens, and 4 blues. (Which you'd want to load from planar, not interleaved, pixel data. struct of arrays, not array of structs.) You might be able to get some benefit for doing a single pixel at once, though, if you just load 4 ints with movdqu and use a multiplier of 0.0 for the high element after cvtdq2ps. Then you can do a normal horizontal sum of 4 elements instead of having to adjust it. (Hmm, although doing 3 would let you do the 2nd shuffle in parallel with the first add, instead of after.) Using SIMD inefficiently loses some of the benefit; see guides in https://stackoverflow.com/tags/sse/info especially https://deplinenoise.wordpress.com/2015/03/06/slides-simd-at-insomniac-games-gdc-2015/ re: how people often try to use one SIMD vector to hold one x,y,z geometry vector, and then find that SIMD didn't help much.
70,637,008
70,637,105
memory leak and I don't know why
My first question is that the object A(v) that added the the map, it should be deleted automatically when exit the scope? My second question is what would happen to the object added into the map, when program exits? I believe when I do a_[name] = A(v);, a copy is stored to the map. Also, do I need to provide a copy constructor? void B::AddA(std::string name, int v) { a_[name] = A(v); } My last question is that I did not create any object with "new", I shouldn't need to delete any. I don't understand where the leak come from. I appreciate any help. Thank you. full code #include <map> #include <string> #include <iostream> class A { public: int vala_; A(); ~A(); A(int v); }; A::A() { vala_ = 0; } A::~A() {} A::A(int v) { vala_ = v; } class B { public: int valb_; std::map<std::string, A> a_; B(); ~B(); void AddA(std::string name, int v); }; B::B() { valb_ = 0; } B::~B() { } void B::AddA(std::string name, int v) { a_[name] = A(v); } int main() { B b; b.AddA("wewe", 5); std::cout << b.a_["wewe"].vala_ << std::endl; exit(0); } valgrind I replaced the number ==????==, to ==xxxx==. I guess it was the process id. ==xxxx== Memcheck, a memory error detector ==xxxx== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al. ==xxxx== Using Valgrind-3.16.1 and LibVEX; rerun with -h for copyright info ==xxxx== Command: ./a.out --leak-check=full -s ==xxxx== 5 ==xxxx== ==xxxx== HEAP SUMMARY: ==xxxx== in use at exit: 72 bytes in 1 blocks ==xxxx== total heap usage: 3 allocs, 2 frees, 73,800 bytes allocated ==xxxx== ==xxxx== LEAK SUMMARY: ==xxxx== definitely lost: 0 bytes in 0 blocks ==xxxx== indirectly lost: 0 bytes in 0 blocks ==xxxx== possibly lost: 0 bytes in 0 blocks ==xxxx== still reachable: 72 bytes in 1 blocks ==xxxx== suppressed: 0 bytes in 0 blocks ==xxxx== Rerun with --leak-check=full to see details of leaked memory ==xxxx== ==xxxx== For lists of detected and suppressed errors, rerun with: -s ==xxxx== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
==xxxx== in use at exit: 72 bytes in 1 blocks ==xxxx== still reachable: 72 bytes in 1 blocks These only mean that when the program exited there was still live memory for which you still had references. The memory wasn't lost completely, which is what normally is referred to as memory leak in the strict sense and would be listed under definitely lost or indirectly lost and possibly lost. When the program ends it doesn't really matter whether there is still unfreed memory. However, this can still be a sign of a problem, for example if objects that should be destroyed and have destructors with side effects are not run. In your case the problem is the exit(0) call. Calling std::exit ends the program right there with some cleanup. Cleanup includes destruction of objects with static storage duration, but not objects with automatic storage duration that would normally be destroyed when their scope is left. In your case B b;, including all the elements it stores, would normally be destroyed at the } or return statement of main, but because you call exit beforehand, it will never be destroyed. In this particular situation that is not a problem, but if e.g. b was an object with destructor that is supposed to perform some operations with side-effect visible outside the program, it might be. You should not call exit(0) to exit the program from main. Just use return 0; or leave it out entirely, because for main specifically no return statement is equivalent to return 0;. Sidenote: You shouldn't explicitly declare/define destructors that don't do anything and aren't virtual, such as A::~A() {}. If you don't declare a destructor at all in the class, the compiler will generate this for you automatically and will behave exactly the same. Declaring the destructor manually anyway has consequences for other implicit generation of special member functions, that may impact the peformance of the program and it also makes it more difficult to consistently follow the rule of 0/3/5. My first question is that the object A(v) that added the the map, it should be deleted automatically when exit the scope? A(v) is a temporary object and will be destroyed at the end of the full expression a_[name] = A(v). Also, do I need to provide a copy constructor? No, one is implicitly declared by the compiler if you don't declare one manually (same as with the destructor) and it will be defined to simply copy each member, assuming that this is possible. This is usually what you want anyway. My last question is that I did not create any object with "new", I shouldn't need to delete any. Yes, that is exactly correct.
70,637,984
70,654,919
Forbid an alignment of consecutive comments in VSCode auto formating for C++
VSCode auto formatting in C++ programs produces this code by aligning consecutive comments: if (true) { // if begin // if inner part int x = 3; int a = 1; // some inner calculations } // if end // some outer calculations int b = 1; How can I forbid comment alignment to get the code bellow? if (true) { // if begin // if inner part int x = 3; int a = 1; // some inner calculations }// if end // some outer calculations int b = 1; I can only prevent it by adding empty lines.
The Microsoft C/C++ extension for VS Code uses clang-format by default as the formatting tool. clang-tidy is a static analysis tool, and is also good to use in its own right, but it's not the tool that answers this question. clang-format style options: https://clang.llvm.org/docs/ClangFormatStyleOptions.html The option you want is AlignTrailingComments, you'll set it to false. If you just want to change some parameters, but otherwise be based on a style, dump that style using something like clang-format -style=LLVM --dump-config > .clang-format in the root of your project. That command assumes a POSIX or close-enough shell (bash, fish, zsh, etc.). It might work in Windows as well, I've just never tried it there. After dumping the config, keep the first two lines (Language, and uncomment BasedOnStyle) and then you can delete any option you don't want to change. Keep the options you want to change, change them, save, quit, etc. Change VS Code to look for the file style first by default (which I believe is the default), and you should be good to go. Here's a bare bones example of a .clang-format file as described above: --- Language: Cpp BasedOnStyle: LLVM AlignTrailingComments: true
70,638,231
70,638,305
Why does this code snippet print 10 infinitely in c++11?
Why does the following C++ code snippet keep printing 10 indefinitely? int num = 10; while (num >= 1) cout << num << " "; num--;
Your snippet is the equivalent of this when using braces: int num = 10; while (num >= 1) { cout << num << " "; } num--; Meaning only the printing statement is part of the loop. What you want is this: int num = 10; while (num >= 1) { cout << num << " "; num--; }
70,638,662
70,656,968
Is it possible to use the standard C++17 <filesystem> facilities with Zig in C++ compiler mode?
I am just getting started with the Zig. I am using Zig 0.9.0 on Windows 10. One of the features that attracts me is using Zig as a C or C++ compiler or cross-compiler. I have used Zig successfully for some toy programs, but my luck ran out when I tried to use C++17's standard library filesystem facilities. Here is a minimal example; #include <stdio.h> #include <filesystem> int main( int argc, char *argv[] ) { std::string s("src/zigtest.cpp"); std::filesystem::path p(s); bool exists = std::filesystem::exists(p); printf( "File %s %s\n", s.c_str(), exists ? "exists" : "doesn't exist" ); return 0; } If I attempt to build this with the following command; zig c++ -std=c++17 src\zigtest.cpp I get the following link error; lld-link: error: undefined symbol: std::__1::__fs::filesystem::__status(std::__1::__fs::filesystem::path const&, std::__1::error_code*) >>> referenced by ... Incidentally, for a long time I didn't get this far, it turned out I needed to apply the -std=c++17 flag, until then I had this compile error rather than a link error; src\zigtest.cpp:7:10: error: no member named 'filesystem' in namespace 'std' Finally I'll note that (after some googling) I tried passing a -lstdc++fs flag, with no luck either. In that case I get; error(link): DLL import library for -lstdc++fs not found error: DllImportLibraryNotFound
Should be solved in this PR. Jakub and Spex worked on it immediately after I linked them this question :^) https://github.com/ziglang/zig/pull/10563
70,638,947
70,639,474
Why does my function for inputting a string not work?
#include <iostream> void main() { using namespace std; char sentence[2000]; for (int i = 0; i <= 2000; i++) { char Test; cin >> Test; if (Test != '\r') sentence[i] == Test; else break; } for (int i = 0; i <= 2000; i++) { cout << sentence[i]; } } Why does my function for inputting a string not work? I wrote this program that is supposed take in input from the user and display the sentence back when the user hits enter. I know there are functions in C++ to do this but I want to write such a program myself. I am a beginner so please keep the answer beginner friendly. I want to know why this doesn't work and also how to make it work. What happens when I run this program is that the input keeps going even thought I hit enter. EDIT: 2 Alright so after reading the comments. I edited my code to this: #include <iostream> int main() { using namespace std; char sentence[2000]; for (int i = 0; i < 2000; i++) { char ch; cin >> ch; if (ch != '\n') sentence[i] = ch; else break; } for (int i = 0; i <= 2000; i++) { cout << sentence[i]; } return 0; } What is expected: The sentence just entered gets outputted back when hitting the enter key. What happens: The cursor goes to the next line asking for more input. EDIT: 3 I changed the 2000 to 5 and noticed the behavior. The problem is that the char declaration for ch doesn't detect anything like whitespaces or newlines and therefore the program will only output once 'i' has cycled through fully and we exit the for loop. However I do not know how to fix this. How do I detect the white spaces and newlines?
You can change it (here). Try this: #include<iostream> using namespace std; int main(int argc, char * argv[]) { char sentence[2000]; char ch; for (int i = 0; i < 2000; i++) { cin >> noskipws >> ch; if (ch != '\n') sentence[i] = ch; else { sentence[i] = '\0'; break; } } for (int i = 0; sentence[i]; i++) { cout << sentence[i]; } return 0; } The noskipws method of stream manipulators in C++ is used to clear the showbase format flag for the specified str stream. This flag reads the whitespaces in the input stream before the first non-whitespace character.
70,639,419
70,639,511
How does use of make_unique prevent memory-leak, in C++?
fn(unique_ptr<A>{new A{}},unique_ptr<B>{new B{}}); is troublesome as A or B gets leaked if an exception is thrown there. fn(make_unique<A>(),make_unique<B>()); on the other hand is considered exception-safe. Question: Why? How does use of make_unique prevent memory-leak? What does make_unique do that the default unique_ptr does not? Kindly help me out, please. Thank you.
How does use of make_unique prevent memory-leak, in C++? std::make_unique doesn't "prevent" memory-leak in the sense that it's still possible to write memory leaks in programs that use std::make_unique. What does std::make_unique is make it easier to write programs that don't have memory leaks. A or B gets leaked if an exception is thrown there. Why? Pre C++17: Because if you allocate A, then call constructor of B before constructing the std::unique_ptr that was supposed to own A, and the constructor of B throws, then A will leak (or same happens with A and B reversed). Since C++17: There's no leak since the scenario described above cannot happen anymore in the shown example. What does make_unique do that the default unique_ptr does not? std::make_unique allocates memory, and either successfully returns a valid std::unique_ptr, or throws an exception without leaking memory. std::unique_ptr(T*) accepts a pointer that was allocated separately. If an exception is thrown before the constructor is called, then there will never have been a unique pointer owning the allocation. It's possible to fix the (pre-C++17) bug without using std::make_unique: auto a = std::unique_ptr<A>{new A{}}; auto b = std::unique_ptr<B>{new B{}}; fn(std::move(a), std::move(b)); But if you always use std::make_unique, then you won't accidentally make the mistake of writing leaky version. Furthermore, std::make_unique lets you avoid writing new which allows you to use the rule of thumb "write exactly one delete for each new". 0 new -> 0 delete.
70,639,548
70,640,383
C++ linear access to 3 dimensional array
Hello as far as I understand when I allocate 3 dimensional array I truly get linear memory that is just interpreted as 3 dimensional by defining stride. So I want to access using linear index the 3 dimensional array, but how can I get first element using linear index - it should be possible in principle for example given int32 in order to get 11th element I should move 320 bits from beginin f the array take next 32 and interpret those bits as int - seems to be far more performant than calculate the 3 d indicies from linear index as it would require multiple divisions... Below I tried dereferncing but still I do it incorrectly as I am here as far as I get get dereferncing to 0th element of second array not what I intend to C++ code int intsss[3][3][3] = { { {1,2, 3}, {4, 5, 6}, {7,8, 9} }, { {10,11, 12}, {13, 14, 15}, {16,17, 18} }, { {19,20, 21}, {22, 23, 24}, {25,26, 27} } }; std::cout << intsss[0][0][1] << std::endl; std::cout << **intsss[1] << std::endl; output 2 10
**intsss[1] is the same as **(intsss[1]). If you want to express intsss[0][0][1] in a different way, use (**intsss)[1] (but in my opinion, it's pointless). To address your multidimensional array in a linear way, first get a pointer to the first element: &intsss[0][0][0]. Then use it like a normal pointer: int* p = &intsss[0][0][0]; std::cout << p[1]; There are a few other equivalent ways to get a pointer to the first element: intsss[0][0] or **intsss. If you use these, you should be careful and make sure you understand how exactly pointer decay works, and make sure you get a pointer to int and not a pointer to an array. For example: intsss[0] is a 2-D array, which decays to a pointer to an array of 3 ints. Doing arithmetic on this pointer jumps 3 ints at once — probably not what you want. Strictly speaking, such linear addressing is illegal (undefined behaviour) if you go past the end of the innermost array. But in practice, it works.
70,639,626
70,639,961
How does the compiler know which virtual function to call in this situation?
I'm studying for an exam and I have this code given to me: #include <iostream> #include <string> #include <cmath> using namespace std; class Expression { public: Expression() = default; Expression(const Expression&) = delete; Expression& operator=(const Expression&) = delete; virtual ~Expression() {} virtual double eval()const = 0; virtual void print(ostream& out)const = 0; friend ostream& operator<<(ostream& out, const Expression& e) { // cout << "@"; e.print(out); return out; } }; class BinaryExpression : public Expression { Expression* _e1, * _e2; char _sign; virtual double eval(double d1, double d2)const = 0; public: BinaryExpression(Expression* e1, Expression* e2, char sign) : _e1(e1), _e2(e2), _sign(sign) {} ~BinaryExpression() override { delete _e1; delete _e2; } virtual double eval()const override { cout << "BE eval" << endl; return eval(_e1->eval(), _e2->eval()); } virtual void print(ostream& out)const override { out << '(' << *_e1 << _sign << *_e2 << ')'; } }; class Sum : public BinaryExpression { virtual double eval(double d1, double d2)const override { cout << "Sum private eval" << endl; return d1 + d2; } public: Sum(Expression* e1, Expression* e2) : BinaryExpression(e1, e2, '+') {} }; class Exponent : public BinaryExpression { virtual double eval(double d1, double d2)const override { cout << "E private eval" << endl; return std::pow(d1, d2); } public: Exponent(Expression* e1, Expression* e2) : BinaryExpression(e1, e2, '^') {} }; class Number : public Expression { double _d; public: Number(double d) : _d(d) {} virtual double eval()const override { cout << "Num eval" << endl; return _d; } virtual void print(ostream& out)const override { out << _d; } }; int main() { Expression* e = new Sum( new Exponent( new Number(2), new Number(3)), new Number(-2)); cout << *e << " = " << e->eval() << endl; delete e; } I used the debugger to see which lines are executed but I'm still wondering how to the compiler knew which function to call each time in the main() where we call e->eval() Output: BE eval Num eval BE eval Num eval Num eval E private eval Sum private eval ((2^3)+-2) = 6 Given every class has an eval function some of them even have 2 and using the Expression pointer threw me off a bit. What exactly does the compiler search for when looking for which eval() to run each time?
There are two topics in your question: How does the compiler know which function to use, given some classes have multiple functions with the same name? Well, they may have the same name, but they don't have the same signature. There is no ambiguity between eval() and eval(x,y) calls, because there is only one eval that doesn't accept any arguments and only one eval that accepts two arguments. Given Expression* e how does the compiler know which function to call in e->eval() expression? The answer is that the compiler does not know. This happens at runtime, not during compilation. Unless an advanced optimization technique, called devirtualization, applies (which is a big topic that I'm not going to talk about here). Typically1 when define virtual functions on a class, your compiler will store additional data within each object of that type, so called vtable, which is just an array of function pointers. Then when you do e->eval() on a virtual method, the compiler will replace this call with two steps: (1) get function pointer from the vtable stored in e object corresponding to eval virtual method, (2) call that function pointer with e object (and potentially other arguments). 1: this is an implementation detail, one of the possible strategies, not necessarily what happens exactly.
70,639,977
70,640,433
Insert/get tuple into/from vector of tuples
I'm trying to insert/get a tuple into/from a vector of tuples and came up with the following code snippet. It works fine, but I'm not entirely happy with it. Can anyone think of a more elegant solution? Is it possible to generalize the 'for_each_in_tuple_and_arg' function into a 'for_each_in_tuples' function? PS: I'm stuck with a C++14 compiler... #include <tuple> #include <vector> #include <utility> template <std::size_t I = 0, class Fn, class Tuple> constexpr typename std::enable_if <I == std::tuple_size<Tuple>::value, void>::type for_each_in_tuple(Fn&&, Tuple&) {} template <std::size_t I = 0, class Fn, class Tuple> constexpr typename std::enable_if <I != std::tuple_size<Tuple>::value, void>::type for_each_in_tuple(Fn&& fn, Tuple& tup) { fn(std::get<I>(tup)); for_each_in_tuple<I + 1>(fn, tup); } template <std::size_t I = 0, class Fn, class Tuple, class Arg> constexpr typename std::enable_if <I == std::tuple_size<Tuple>::value, void>::type for_each_in_tuple_and_arg(Fn&&, Tuple&, const Arg&) {} template <std::size_t I = 0, class Fn, class Tuple, class Arg> constexpr typename std::enable_if <I != std::tuple_size<Tuple>::value, void>::type for_each_in_tuple_and_arg(Fn&& fn, Tuple& tup, const Arg& arg) { fn(std::get<I>(tup), std::get<I>(arg)); for_each_in_tuple_and_arg<I + 1>(fn, tup, arg); } class tuple_of_vectors { public: using tov_type = std::tuple< std::vector<int>, std::vector<int>, std::vector<int>>; using value_type = std::tuple<int, int, int>; void reserve(std::size_t n) { auto fn = [n](auto& vec){ vec.reserve(n); }; for_each_in_tuple(fn, tov_); } value_type at(std::size_t n) const noexcept { value_type res{}; auto fn = [n](auto& val, const auto& vec) { val = vec.at(n); }; for_each_in_tuple_and_arg(fn, res, tov_); return res; } void insert(const value_type& tup) { std::size_t n = 0; auto fn = [n](auto& vec, const auto& val) { vec.insert(vec.cbegin() + n, val); }; for_each_in_tuple_and_arg(fn, tov_, tup); } tov_type tov_; };
As it is quite easy to write such things in current C++, which can be something like: template <typename TUPPLE_T, typename FUNC, typename ... ARGS > void for_each_in_tuple( TUPPLE_T& tu, FUNC fn, ARGS... args ) { std::apply( [&args..., fn]( auto& ... n) { (fn(args..., n),...); }, tu); } int main() { std::tuple< int, int> tu{1,2}; auto l_incr = [](int& i){i++;}; auto l_add = []( int val, int& i){i+=val; }; for_each_in_tuple( tu, l_incr ); std::cout << std::get<0>(tu) << ":" << std::get<1>(tu) << std::endl; for_each_in_tuple( tu, l_add, 5 ); std::cout << std::get<0>(tu) << ":" << std::get<1>(tu) << std::endl; } C++20 on godbolt but you are fixed at C++14. OK, so lets copy and minimize the stuff from the STL as needed to get it work with an "handcrafted" apply functionality like: namespace detail { template <class F, class Tuple, std::size_t... I> constexpr decltype(auto) apply_impl(F&& f, Tuple&& t, std::index_sequence<I...>) { return f(std::get<I>(std::forward<Tuple>(t))...); } } // namespace detail template <class F, class Tuple> constexpr decltype(auto) apply(F&& f, Tuple&& t) { return detail::apply_impl( std::forward<F>(f), std::forward<Tuple>(t), std::make_index_sequence<std::tuple_size<std::remove_reference_t<Tuple>>::value>{}); } // Workaround for missing fold expression in C++14. Simply use // list initializer to get function called. It guarantees also // execution order... struct EatEverything { template < typename ... T> EatEverything(T...){} }; template <typename TUPPLE_T, typename FUNC, typename ... ARGS > void for_each_in_tuple( TUPPLE_T& tu, FUNC fn, ARGS... args ) { apply( [&args..., fn]( auto& ... n) { EatEverything{ (fn(args..., n),0)... };}, tu); } int main() { std::tuple< int, int> tu{1,2}; auto l_incr = [](int& i){i++;}; auto l_add = []( int val, int& i){i+=val; }; for_each_in_tuple( tu, l_incr ); std::cout << std::get<0>(tu) << ":" << std::get<1>(tu) << std::endl; for_each_in_tuple( tu, l_add, 5 ); std::cout << std::get<0>(tu) << ":" << std::get<1>(tu) << std::endl; } C++14 on godbolt As we only have written a C++14 apply function, we can remove that stuff later while a non outdated compiler can be used and we stay with the single line of code implementation. Hint: I know that we can do all the stuff much better by using forwarding refs and std::forward and so on... it is an example and wants to show how we can use apply instead of handcrafted reverse algorithm.
70,640,141
70,640,319
Why am i Getting garbage value when reading a binary file?
For the sake of simplicity I wrote a simple code to reproduce my problem. As you can see on the code i created a struct with two members then I created and array of the struct type then initialized it student newStudent[3] ={{"joseph",20}, {"yonas",30},{"miryam",40}};. I stored all the info from the struct to a binary file newFile.write(reinterpret_cast<char*>(newStudent), 3 * sizeof(student));(everything is fine until here) then i created another array student loadedStudent[3]; to load into, all the data from the binary file and output the loaded data using a for loop cout<<"Name: "<<loadedStudent[i].name<<"Age: "<<loadedStudent[i].age<<endl;. The problem is that the data i stored is joseph",20, "yonas",30,"miryam",40 but the program is outputting garbage values Name: 8H???Age: 1 Name: J???Age: 1 Name: ?I???Age: 32766. Why is that? #include <iostream> #include <fstream> using namespace std; struct student{ char name[10]; int age; }; int main() { student newStudent[3] ={{"joseph",20}, {"yonas",30},{"miryam",40}}; fstream newFile; newFile.open("/Users/josephfeleke/Desktop/abeltest/file.bin", ios::out | ios::binary); //for(int i = 0; i<3; i++){ //cout<<"Name: "<<newStudent[i].name<<" Age: "<<newStudent[i].age<<endl; //} if(newFile.is_open()){ newFile.write(reinterpret_cast<char*>(newStudent), 3 * sizeof(student)); }else cout<<"faild to open file"; student loadedStudent[3]; newFile.seekg(0, ios::beg); if(newFile.is_open()){ newFile.read(reinterpret_cast<char*>(loadedStudent), 3 * sizeof(student)); newFile.close(); }else cout<<"faild to open file"; for(int i = 0; i<3; i++){ cout<<"Name: "<<loadedStudent[i].name<<"Age: "<<loadedStudent[i].age<<endl; }
When you opened the file you only opened it as output ios::out you shoul've also included ios::in so you can access the file. Now you're printing the indeterminate values of an uninitialized array. change this newFile.open("/Users/josephfeleke/Desktop/abeltest/file.bin", ios::out | ios::binary); into newFile.open("/Users/josephfeleke/Desktop/abeltest/file.bin", ios::out | ios::in | ios::binary);
70,640,210
70,658,146
Chrome not saving Cookies across different subdomains
I've written a very primitive C++ HTTP server and I want to support the JWT token using JWT-CPP. Basically, I have 2 endpoints: If the request is /auth/username, I will generate a JWT token with the username given in the URL. If the request is /verify, I will check the Cookie in the request header and look for a JWT token. If it exists, I will verify it and return the username in the JWT payload. Here is the part of the code I send the response: // Check and give JWT token if (has_auth == 0 || auth_right == 0) { // HTTPGET[1] contains the URL requested. For example, 'auth/username' size_t pos1 = HTTPGET[1].find('/'); size_t pos2 = HTTPGET[1].find('/', pos1 + 1); std::string mode = HTTPGET[1].substr(0, pos2); printf("JWT: mode is: %s\n", mode.c_str()); if (strcmp(mode.c_str(), "/auth") == 0) { printf("JWT: Auth\n"); size_t pos3 = HTTPGET[1].find('/', pos2 + 1); std::string username = HTTPGET[1].substr(pos2 + 1, pos3); printf("JWT: username is: %s\n", username.c_str()); auto token = jwt::create() .set_issuer("auth0") .set_type("JWS") .set_payload_claim("sub", jwt::claim(username)) .set_issued_at(std::chrono::system_clock::now()) .set_expires_at(std::chrono::system_clock::now() + std::chrono::seconds{86400}) .sign(jwt::algorithm::hs256{"secret"}); auto verifier = jwt::verify() .allow_algorithm(jwt::algorithm::hs256{ "secret" }) .with_issuer("auth0"); auto decode = jwt::decode(token); std::string GiveJWT = "HTTP/1.1 200 OK\r\nServer: myhttpserver\r\n" + CORS_header + "Content-type: text/plain\r\nSet-Cookie: token=" + token + "\r\n\r\n JWT token generated successful!\nYour token's username is: " + username + "\n"; write(fd, GiveJWT.c_str(), GiveJWT.size()); return; } //return; } else { std::string NeedAuth = "HTTP/1.1 401 Unauthorized\r\nServer: myhttpserver\r\n" + CORS_header + "Content-type: text/plain\r\n\r\nAuthorization failed\n"; write(fd, NeedAuth.c_str(), NeedAuth.size()); } // Verify user's token // rel_path contains the url or subdomain of the request. For example, the url here should be './verify'. if (strcmp(rel_path.c_str(), "./verify") == 0) { printf("Get in the verify\n"); if (auth_right == 1) { auto decode = jwt::decode(success_token); std::string username = decode.get_payload_claim("sub").as_string(); printf("username is: %s\n", decode.get_payload_claim("sub").as_string()); std::string JWTConfirm = "HTTP/1.1 200 OK\r\nServer: myhttpserver\r\n" + CORS_header + "Content-type: text/plain\r\n\r\nYour user name is: ?" + username + "\n"; write(fd, JWTConfirm.c_str(), JWTConfirm.size()); return; } else { std::string JWTConfirm = "HTTP/1.1 401 Unauthorized\r\nServer: myhttpserver\r\n" + CORS_header + "Content-type: text/plain\r\n\r\nWhate are you looking at?"; write(fd, JWTConfirm.c_str(), JWTConfirm.size()); return; } } This is the HTTP header & response I got from accessing /auth/oreo: I can see the server is supporting CORS in its header, so the cookie should be able to transferred across domains. However, If I switch to the endpoint /verify, that token cookie will not be carried. I know Cookies are suppose to be session-based, but is there anyway I can carry this cookie as long as the browser session exist?
Sorry for the misinterpretation ahead. What I meant was a different path, not different subdomains. In the end, I resolved this by adding the "Path=/" attribute after my Cookie, which allows the cookies to be carried forward across different paths. However, If you have stored the old cookie before, make sure you clear them first. This could be my endpoint's issue, but if I don't clear the cookies, the request will mysteriously hang even after I close the socket on the server-side. I'm not sure why though.
70,640,810
70,713,317
How vector iterator's copy-constructor use SFINAE to allow for iterator to const_iterator conversion?
While studying various std::vector's iterator implementations, I noticed this copy-constructor which uses SFINAE to allow initializing constant iterators from non-constant ones and vice versa: // Allow iterator to const_iterator conversion // ... // N.B. _Container::pointer is not actually in container requirements, // but is present in std::vector and std::basic_string. template<typename _Iter> __normal_iterator(const __normal_iterator<_Iter, typename __enable_if< (std::__are_same<_Iter, typename _Container::pointer>::__value), _Container>::__type>& __i) : _M_current(__i.base()) { } It's a common knowledge that the iterators for vectors are defined this way: typedef __gnu_cxx::__normal_iterator<pointer, vector> iterator; typedef __gnu_cxx::__normal_iterator<const_pointer, vector> const_iterator; I can't understand how the checking of container's pointer type against Iter allows the conversion. If I pass a constant iterator, Iter should be const_pointer, won't that fail the enable_if<> check and discard this constructor from the set? Which one will be used then? Could you please explain how this constructor works and maybe bring an example of such substitution? P.S. Another question is why std::list doesn't use the same technique of avoiding code duplication by declaring iterators like this. It has two separate classes for both versions of iterators. I wonder if it's possible to implement list's iterators in the very same way as vector's
If I pass a constant iterator, Iter should be const_pointer, won't that fail the enable_if<> check and discard this constructor from the set? Which one will be used then? Yes, that's exactly what happens, because that definition would be an ambiguous overload of the default (implicit) copy constructor. These extra constructors are there to allow the implicit conversion to happen only from non-const to const iterator, and explicit conversion from pointer-like types to iterators. As for std::list, I don't know! It could simply be an arbitrary implementation detail, or maybe this way was considered to be more readable/maintainable.
70,640,922
70,640,960
Passing a 2D array as Function Argument
I am trying to pass 2D arrays of arbitrary size to a function. The code that i have tried is as follows: #include <iostream> void func(int (&arr)[5][6]) { std::cout<<"func called"<<std::endl; } int main() { int arr[5][6]; func(arr); return 0; } As you can see the func is correctly called. But i want to pass a 2D array of any size. In the current example, we can only pass int [5][6]. PS: I know i can also use vector but i want to know if there is a way to do this with array. For example, i should be able to write: int arr2[10][15]; func(arr2);//this should work
You could do this using templates. In particular, using nontype template parameters as shown below: #include <iostream> //make func a function template template<std::size_t N, std::size_t M> void func(int (&arr)[N][M]) { std::cout<<"func called with: "<<N<<" rows and "<<M<<" columns"<<std::endl; } int main() { int arr2[10][15]; func(arr2); return 0; } In the above example N and M are called nontype template parameters. Using templates we can even make the type of elements in the array arbitrary, as shown below: //make func a function template template<typename T, std::size_t N, std::size_t M> void func(T (&arr)[N][M]) { std::cout<<"func called with: "<<N<<" rows and "<<M<<" columns"<<std::endl; } int main() { int arr2[10][15]; func(arr2); float arr3[3][4]; func(arr3);//this works too return 0; }
70,641,354
70,641,545
Is a declaration for a non-static data member of a class type also a definition?
I am learning C++. In particular, the difference between declaration and definition. To my current understanding All definitions are declarations but not all declarations are definitions. Here is an example of what I currently know. int x; //definition(as well as declaration according to the above quote) extern int y; //declaration that is not a definition class CustomType { int x; //is this a "declaration that is not a definition" OR a "definition" }; int main() { int p[10]; //definition //... } I want to know whether int x; inside the class' definition is a declaration that is not a definition or a definition. And where in the standard is this stated so that I can read more about it.
I want to know whether int x; inside the class' definition is a declaration that is not a definition or a definition. The declaration of a non-static data member (such as x) is a definition.
70,641,776
70,641,942
How to access class's virtual method from interrupt service routine?
I am trying to implement PWM using Timer0 for Atmega328P in C++. Indeed, I have achieved this. But, I have another related problem. I have a PWM abstract base class that provides an interface for PWM implementation. // mcal_pwm_base.h #ifndef MCAL_PWM_BASE_H_ #define MCAL_PWM_BASE_H_ namespace mcal { namespace pwm { class pwm_base { public: ~pwm_base() = default; virtual bool init() noexcept = 0; virtual void set_duty(const uint16_t duty_cycle) = 0; virtual void pwm_ISR() noexcept = 0; uint16_t get_duty() const noexcept { return pwm_duty_cycle; } protected: uint16_t pwm_duty_cycle; pwm_base() : pwm_duty_cycle(0U) { } pwm_base(const pwm_base&) = delete; const pwm_base& operator=(const pwm_base&) = delete; }; } } #endif /* MCAL_PWM_BASE_H_ */ I want to implement PWM with timer (8 bit timer). So, I created another class which derives from pwm_base class. // mcal_pwm_8.h #ifndef MCAL_PWM_8_H_ #define MCAL_PWM_8_H_ #include "mcal_pwm_base.h" #include "mcal_reg_access_dynamic.h" #include <avr/interrupt.h> namespace mcal { namespace pwm { template<const uint8_t prescalar_val = UINT8_C(0U)> class pwm_8 : public mcal::pwm::pwm_base { public: ~pwm_8() = default; virtual bool init() noexcept { // set pwm related things return true; } virtual void set_duty(const uint16_t duty_cycle) { pwm_duty_cycle = duty_cycle; } virtual void pwm_ISR() noexcept { uint8_t compare_value = (pwm_duty_cycle / 100) * 255; mcal::reg::reg_access_dynamic<uint8_t, uint8_t>::reg_set(mcal::reg::ocr0a, compare_value); } }; } } ISR(TIMER0_OVF_vect) { // pwm_ISR(); } #endif /* MCAL_PWM_8_H_ */ As you can see, I want to call pwm_ISR() member function in ISR (interrupt service routine). But, I don't know how to do it. In the book, it is written that make ISR friend function of pwm_8 class. Even if I did that, how will I reach the private member variable of pwm_duty_cycle in ISR? At this point, I need your help. And finally, this is my main function. // main.h #define F_CPU 16000000ULL #include <avr/io.h> #include <util/delay.h> #include "mcal_reg.h" #include "mcal_reg_access_static.h" #include "mcal_port.h" #include "mcal_led_port.h" #include "mcal_pwm_8.h" int main(void) { mcal::pwm::pwm_8<UINT8_C(5U)> myPwm; myPwm.init(); myPwm.set_duty(250); // This will be applied when ISR called for(;;) { } return 0; } Thank you very much beforehand.
It doesn't seem possible to supply user data (like a void*) to the ISR routine so you could make myPwm a global variable: Example: Header file: extern mcal::pwm::pwm_8<UINT8_C(5U)> myPwm; ISR(TIMER0_OVF_vect) { myPwm.pwm_ISR(); } ... and in the .cpp file: mcal::pwm::pwm_8<UINT8_C(5U)> myPwm; You could also hide the global variable in a function to get lazy initialization. Header file: mcal::pwm::pwm_8<UINT8_C(5U)>& myPwm(); // now a function ISR(TIMER0_OVF_vect) { myPwm().pwm_ISR(); // calling function to get the instance } ... and in the .cpp file: mcal::pwm::pwm_8<UINT8_C(5U)>& myPwm() { static mcal::pwm::pwm_8<UINT8_C(5U)> instance; // that returns a reference to the one instance you'll use: return instance; }
70,641,828
70,641,898
Reversing string input not giving right output
Here's how I'm going about it: int maxIndex = input.length() - 1; for (int index = 0; index <= maxIndex; index++) { char temp = input[index]; input[index] = input[maxIndex - index]; input[maxIndex - index] = input[index]; } The input is taken in a string variable called input. Now if the size of the input array is 3, the indexes are 0, 1 and 2 According to me there shouldn't have been any problems but testing this gives me: Input: pli Output: ili Why don't the first and last elements get swapped properly?
There are 2 issues here: the last assignment uses input[index] instead of temp on the right hand side You iterate until the index reaches the end, which means every corresponding pair of indices is swapped twice resulting in the original string after fixing just (1.) if (!input.empty()) { for (size_t index = 0, index2 = input.size() - 1; index < index2; ++index, --index2) { char temp = input[index]; input[index] = input[index2]; input[index2] = temp; } }
70,642,138
70,642,159
Why is my simple merge algorithm c++ not working?
I'm trying to merge two sorted vectors into a third one. However, the compiler gives me 0 in the terminal!! Can someone please tell me what I'm doing wrong? Thanks! // merging two sorted vectors std::vector<int> vec1{5}; std::vector<int> vec2{5}; std::vector<int> vec3{10}; for(int i = 0; i < 5; i++){ vec1[i] = 2 * i; } for(int i = 0; i < 5 ; i++){ vec2[i] = 2 + 2 * i; } std::sort(vec1.begin(), vec1.end()); std::sort(vec2.begin(), vec2.end()); std::merge(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), vec3.begin()); for(auto itr = vec3.begin(); itr != vec3.end(); ++itr){ std::cout << " " << *itr; }
All your vectors have .size() == 1, so you're going out of bounds, and the behavior is undefined. Use () instead of {}: std::vector<int> vec1(5); std::vector<int> vec2(5); std::vector<int> vec3(10); You should never use the {...} syntax with containers (as opposed to = {...} or {}), because it has a rather peculiar behavior. If the elements were not ints (and not constructible from ints), it would've worked as you expect: std::vector<int> x(3); // size=3, [0,0,0] std::vector<int> x{3}; // size=1, [1] std::vector<int> x = {3}; // size=1, [1] struct A {}; std::vector<A> x(3); // size=3, [A{}, A{}, A{}] std::vector<A> x{3}; // size=3, [A{}, A{}, A{}] std::vector<A> x = {3}; // compilation error std::vector<A> x = {A{}}; // size=1, [A{}] Notice that the behavior of {...} changes depending on the element type, but that doesn't happen with (...) or = {...}.
70,642,172
70,642,194
Is there a way to extract C++ code from a Windows .exe driver or a Mac OS driver?
I have a Freestyle Libre 2 blood sugar meter, and it uses a driver to upload results to the website. Unfortunately this driver is written in C++ and only compiled for Windows and Mac OS. I use Linux and have tried installing in a virtual machine and also using layers such as Wine. I think I am left with only one option, recompiling for Linux. It is a USB driver for communicating with the reader, to gather and upload the data to their website. Is there a way to extract C++ code from the .exe file and then recompile it to Linux after making any necessary changes to the code?
No. You cannot extract the original source code from a compiled binary. You can reverse engineer it, though.
70,642,263
70,642,482
Comparing unsigned integer with negative literals
I have this simple C program. #include <stdlib.h> #include <stdio.h> #include <stdbool.h> bool foo (unsigned int a) { return (a > -2L); } bool bar (unsigned long a) { return (a > -2L); } int main() { printf("foo returned = %d\n", foo(99)); printf("bar returned = %d\n", bar(99)); return 0; } Output when I run this - foo returned = 1 bar returned = 0 Recreated in godbolt here My question is why does foo(99) return true but bar(99) return false. To me it makes sense that bar would return false. For simplicity lets say longs are 8 bits, then (using twos complement for signed value): 99 == 0110 0011 -2 == unsigned 254 == 1111 1110 So clearly the CMP instruction will see that 1111 1110 is bigger and return false. But I dont understand what is going on behind the scenes in the foo function. The assembly for foo seems to hardcode to always return mov eax,0x1. I would have expected foo to do something similar to bar. What is going on here?
This is covered in C classes and is specified in the documentation. Here is how you use documents to figure this out. In the 2018 C standard, you can look up > or “relational exprssions” in the index to see they are discussed on pages 68-69. On page 68, you will find clause 6.5.8, which covers relational operators, including >. Reading it, paragraph 3 says: If both of the operands have arithmetic type, the usual arithmetic conversions are performed. “Usual arithmetic conversions” is listed in the index as defined on page 39. Page 39 has clause 6.3.1.8, “Usual arithmetic conversions.” This clause explains that operands of arithmetic types are converted to a common type, and it gives rules determining the common type. For two integer types of different signedness, such as the unsigned long and the long int in bar (a and -2L), it says that, if the unsigned type has rank greater than or equal to the rank of the other type, the signed type is converted to the unsigned type. “Rank” is not in the index, but you can search the document to find it is discussed in clause 6.3.1.1, where it tells you the rank of long int is greater than the rank of int, and the any unsigned type has the same rank as the corresponding type. Now you can consider a > -2L in bar, where a is unsigned long. Here we have an unsigned long compared with a long. They have the same rank, so -2L is converted to unsigned long. Conversion of a signed integer to unsigned is discussed in clause 6.3.1.3. It says the value is converted by wrapping it modulo ULONG_MAX+1, so the signed long −2 produces a large integer. Then comparing a, which has the value 99, to a large integer with > yields false, so zero is returned. For foo, we continue with the rules for the usual arithmetic conversions. When the unsigned type does not have rank greater than or equal to the rank of the signed type, but the signed type can represent all the values of the type of the operand with unsigned type, the operand with the unsigned type is converted to the operand of the signed type. In foo, a is unsigned int and -2L is long int. Presumably in your C implementation, long int is 64 bits, so it can represent all the values of a 32-bit unsigned int. So this rule applies, and a is converted to long int. This does not change the value. So the original value of a, 99, is compared to −2 with >, and this yields true, so one is returned.
70,642,333
70,642,461
Where did i go wrong c++ classes
Hi this is my first subject (question) at stack overflow i've tried an project about c++ classes at Code::Blocks but something went wrong #include <iostream> using namespace std; class char1 { public: string charName; float charLength; void printName() { cout<<"char name is"<<charName; } }; int main() { int charNAME; float charLENGTH; cout<<"write your char's name"<<endl; cin>>charNAME; cout<<"write your char's length"<<endl; cin>>charLENGTH; char1 name; char1 length; name.charName=charNAME; length.charLength=charLENGTH; return 0; } when i run program it asks me char's name i write something, after it asks char's length but program end there i cant do anything here is picture for help
Some fixes for your code to show you how to use your class in practice (with some c++ coding tips). #include <string> #include <iostream> // using namespace std; <== don't do this // https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice //class char1 class Character // <== give classes clear names, makes code more readable { public: std::string name; float length; // I understand you want to do this to test stuff. // but from a design point of view printing is not something // a character can do to himself /* void printName() { cout << "char name is" << charName; } */ }; // bit offtopic but : // if you want to add support for printing your character // its more common to overload operator<< for streams like this std::ostream& operator<<(std::ostream& os, const Character& character) { os << "Your character's name = " << character.name << ", and his/her length = " << character.length << "\n"; return os; } int main() { // int charNAME; in your class this is a string, be consistent. // float charLENGTH; // make an instance of the Character class Character character; std::cout << "Enter your char's name : "; // << endl; avoid using endl use "\n" if you want a newline std::cin >> character.name; std::cout << "Enter your char's length : "; // << endl; std::cin >> character.length; std::cout << "\n"; std::cout << character; // this will now call your overloaded << operator return 0; }
70,642,401
70,642,543
Can I make a Call with NASL to run a C++ programm?
We are working on a project with Nessus Attack Scripting Language ( NASL ) and we would like to run a programm written in C++. I want to ask, is it even possible to run another Script with NASL? So we would like to run the NASL script, which runs another C++ programm, which works with Zigbee to mqtt.
No. Not according to the manual. In fact it is specifically disallowed. 1.1 What is NASL ? NASL is a scripting language designed for the Nessus security scanner. Its aim is to allow anyone to write a test for a given security hole in a few minutes, to allow people to share their tests without having to worry about their operating system, and to garantee everyone that a NASL script can not do anything nasty except performing a given security test against a given target. Thus, NASL allows you to easily forge IP packets, or to send regular packets. It provides you some convenient functions that will make the test of web and ftp server more easy to write. NASL garantees you that a NASL script : will not send any packet to a host other than the target host will not execute any commands on your local system http://student.ing-steen.se/java/javacoding/toys/more_toys/nessus/txtfilez/nasl.html
70,642,530
70,642,605
Strange problems when creating a float array in c++
Code: #define N 4 float unknowns[N] = {71/129, 539/1461, 1493/8507, 17/33}; for(int i = 0; i < N; i++) { cout << unknowns[i] << " "; } cout << endl << endl; Output: 0 0 0 0 For some reason the program is outputing the numbers in the array as integers and not as floats and I don't know why. How can I fix this? This code for example works, and I tried casting them in the array itself but it still didn't work: cout << (float)71/129 << " " << (float)539/1461 << " " << (float)1493/8507 << " " << (float)17/33 << endl; Output: 0.550388 0.368925 0.175503 0.515152
The problem is, you are doing integer division (e.g., 71/129) and storing the value later in float. The result of integer is division of all your values is 0. Use float division while constructing the array (use 71.0/129.0). The code is: define N 4 float unknowns[N] = {71.0/129.0, 539.0/1461.0, 1493.0/8507.0, 17.0/33.0}; for(int i = 0; i < N; i++) { cout << unknowns[i] << " "; } cout << endl << endl
70,642,723
70,642,826
C++ opencv get cv::Point from index
I would like to extract data from a cv::Mat via the index of a pixel. This works fine for the colur e.g. cv::Vec3b, however when attempting to get the point information, it crashes stating: Error: Assertion failed (elemSize() == sizeof(_Tp)) in cv::Mat::at, Here is the code I'm using: cv::Mat src = imread(image_path, cv::IMREAD_COLOR); int max_index = src.size().area() // gives total amount of pixels (i.e. max index) std::cout << src.at<cv::Vec3b>(max_index -1) << std::endl; // gives me colour of final pixel std::cout << src.at<cv::Point>(max_index -1) << std::endl; // ERROR should give point of final pixel but crashes How can I fix this so that I can get the Point at a specific pixel index?
you can't, using Mat::at(). (it is meant to retrieve the pixel content, not the position) the bottom-right point would be either: Point(src.cols-1, src.rows-1); or in your calculation: Point((max_index-1)%src.cols, (max_index-1)/src.cols); (imo, the whole idea of using max_indexis somewhat impractical ...)
70,642,792
70,643,322
What could be a better for condition_variables
I am trying to make a multi threaded function it looks like: namespace { // Anonymous namespace instead of static functions. std::mutex log_mutex; void Background() { while(IsAlive){ std::queue<std::string> log_records; { // Exchange data for minimizing lock time. std::unique_lock lock(log_mutex); logs.swap(log_records); } if (log_records.empty()) { Sleep(200); continue; } while(!log_records.empty()){ ShowLog(log_records.front()); log_records.pop(); } } } void Log(std::string log){ std::unique_lock lock(log_mutex); logs.push(std::move(log)); } } I use Sleep to prevent high CPU usages due to continuously looping even if logs are empty. But this has a very visible draw back that it will print the logs in batches. I tried to get over this problem by using conditional variables but in there the problem is if there are too many logs in a short time then the cv is stopped and waked up many times leading to even more CPU usage. Now what can i do to solve this issue? You can assume there may be many calls to log per second.
I would probably think of using a counting semaphore for this: The semaphore would keep a count of the number of messages in the logs (initially zero). Log clients would write a message and increment by one the number of messages by releasing the semaphore. A log server would do an acquire on the semaphore, blocking until there was any message in the logs, and then decrementing by one the number of messages. Notice: Log clients get the logs queue lock, push a message, and only then do the release on the semaphore. The log server can do the acquire before getting the logs queue lock; this would be possible even if there were more readers. For instance: 1 message in the log queue, server 1 does an acquire, server 2 does an acquire and blocks because semaphore count is 0, server 1 goes on and gets the logs queue lock... #include <algorithm> // for_each #include <chrono> // chrono_literasl #include <future> // async, future #include <iostream> // cout #include <mutex> // mutex, unique_lock #include <queue> #include <semaphore> // counting_semaphore #include <string> #include <thread> // sleep_for #include <vector> std::mutex mtx{}; std::queue<std::string> logs{}; std::counting_semaphore c_semaphore{ 0 }; int main() { auto log = [](std::string message) { std::unique_lock lock{ mtx }; logs.push(std::move(message)); c_semaphore.release(); }; auto log_client = [&log]() { using namespace std::chrono_literals; static size_t s_id{ 1 }; size_t id{ s_id++ }; for (;;) { log(std::to_string(id)); std::this_thread::sleep_for(id * 100ms); } }; auto log_server = []() { for (;;) { c_semaphore.acquire(); std::unique_lock lock{ mtx }; std::cout << logs.front() << " "; logs.pop(); } }; std::vector<std::future<void>> log_clients(10); std::for_each(std::begin(log_clients), std::end(log_clients), [&log_client](auto& lc_fut) { lc_fut = std::async(std::launch::async, log_client); }); auto ls_fut{ std::async(std::launch::async, log_server) }; std::for_each(std::begin(log_clients), std::end(log_clients), [](auto& lc_fut) { lc_fut.wait(); }); ls_fut.wait(); }
70,642,910
70,647,246
What C++ type do keycodes from HID Project Use?
Recently I have found myself incredibly frustrated in programming my recently built 9 key macro keyboard I made using an arduino pro micro. The keyboard is fully functional hardware wise, but I am very new to C++ and cannot get it to do exactly what I want. Essentially, I wish to bind the 9 keys to the F13-F21 keys using an array associated with the key values, 0 through 8. To do so, I wish to use an array, but because I do not know what type the key values from HID project are, I cannot get the array to pass any meaningful data to the Keyboard.press function. static const uint8_t KEYBINDS[] = {KEY_F13, KEY_F14, KEY_F15, KEY_F16, KEY_F17, KEY_F18, KEY_F19, KEY_F20, KEY_F21}; A scenario similar to what I'm trying to do is the following, where I use a Values array to pass data to the Keyboard.press() function, just using numbers. static const uint8_t Values[] = {1, 4, 3, 6, 8}; Keyboard.press(Values[2]); However, the Keyboard.press() function requires data that looks like this, KEY_F13 KEY_TAB KEY_SPACEBAR I don't know what type of data this is. It doesn't work as string, uint8_t or uint16_t, or anything else I've tried. I can't use no type, and void doesn't work for arrays, so I have no idea what else to try. The type is not specified in the source code, at least not to what I can see, but I don't really know how to look. Some infos; using Keyboard.press(KEY_F13); does EXACTLY what I want it to. I just don't know how to pass that through an array to the function. Technically, I could get this to work using a horrible if-statement nest with a bunch of Keyboard.press() commands, but I would much rather figure this out the right way. Please let me know if any additional info is needed to help answer this question. HID-Project Documentation https://github.com/NicoHood/HID/wiki
Those are values of enum type KeyboardKeycode from ImprovedKeylayouts.h. While enum's named value can be casted implicitly to an integral type, opposite requires explicit cast. Not sure what problem you had to diagnose it, compiler diagnostics should have point at the mismatch. After all you also could used a type-agnostic declaration using C++11
70,643,026
70,643,761
C++20 modules export template instantiation
I'm creating a library and I have a class template inside a C++20 module and I want to add an instantiation in order to reduce compilation time for every project that uses my library. Are these different implementations equivalent, or is there a better way to achieve it? 1) //mod.cpp export module mod; export template<typename T> struct mystruct{ T i;}; export template class mystruct<int>; //mod.cpp export module mod; export template<typename T> struct mystruct{ T i;}; template class mystruct<int>; //mod.cpp export module mod; export template<typename T> struct mystruct{ T i;}; export extern template class mystruct<int>; //mod_impl.cpp module mod; template class mystruct<int>; Edit: This answer says only that 2. works, but my point is if also 1. and 3. are equivalent to 2.
Modules affect 2 things: the scope of names and the reach-ability of declarations. Both of these only matter if they are within the purview of a module (ie: in an imported module interface TU and not being in the global module fragment). Names declared in the purview of a module can be used outside of that module only if they are exported by that module. In the case of an explicit template instantiation, the template itself is already exported, so users outside of the module can already use the name. However, an explicit template instantiation definition is also a declaration. And modules control the reach-ability of declarations. The thing is, the rules of reach-ability for a declaration don't actually care about export: A declaration D is reachable if, for any point P in the instantiation context ([module.context]), D appears prior to P in the same translation unit, or D is not discarded ([module.global.frag]), appears in a translation unit that is reachable from P, and does not appear within a private-module-fragment. [ Note: Whether a declaration is exported has no bearing on whether it is reachable. — end note ] Emphasis added. These rules only care about which TUs have been imported (and whether the declaration is in a global/private module fragment). Therefore, if the primary template declaration was exported, an explicit template instantiation (that is not in the global/private module fragment) in one of the imported module files is reach-able by any code that imports it. So it doesn't matter if you export an explicit template instantiation. If the primary template was already exported, its name could already be used, so the only thing that matters is if the explicit template instantiation is visible. So your #1 and 2 are functionally equivalent. And its best not to export something you don't need to. As for the behavior of extern template, that's interesting. While extern normalize denotes external linkage, this does not apply to extern template. So we don't have linkage problems. And since the extern template declaration is reach-able by importers of the module (as previously stated), they'll see it and respect it. So the only question is whether the explicit definition in your "mod_impl.cpp" is also reach-able. Except that's not a question because only the declaration part of a definition is ever "reach-able". That is, reach-ability only matters for a declaration. The explicit instantiation definition is in a different TU. Therefore, it will only be instantiated in that TU; code which imports the module reaches only the declaration. And therefore, it won't instantiate the template. So yes, you can perform extern template gymnastics (though again, export doesn't matter). But it's no different than just putting the explicit instantiation in your module interface, and it's way cleaner to do that.
70,643,332
70,669,753
error: ‘HAAR_DO_CANNY_PRUNING’ is not a member of ‘cv’
I am upgrading an existing code base that use OpenCV 2 and 3 to be compatible with my Ubuntu 20.04 that uses OpenCV 4. One error I encountered when compiling is: error: ‘HAAR_DO_CANNY_PRUNING’ is not a member of ‘cv’; did you mean ‘CASCADE_DO_CANNY_PRUNING’? Should I accept the change proposed by the compiler and change cv::HAAR_DO_CANNY_PRUNING to cv::CASCADE_DO_CANNY_PRUNING for all occurrences?
Should I accept the change proposed by the compiler? Yes. The values of the 4 CASCADE_* symbols match the ones of the old HAAR_* symbols, as @DanMasek commented. You can check the enums in Enumeration Type Documentation and OpenCV-2_2 Reference, page 795.
70,643,366
70,644,143
passing optional arguments to a makefile
I have a program and i have this make file and im trying to run my program with this makefile, and it compiles well the problem is when i run the program i what to run it like this ./user -n tejo.tecnico.ulisboa.pt -p 58011 with this -n tejo.tecnico.ulisboa.pt or this -p 58011 being optional. I saw this post Passing arguments to "make run" and im not understanding what im doing wrong in the make run command So can anyone tell me whats wrong in my makefile? btw im fairly new at making makefiles and using the command line. Program: # Makefile CC = g++ LD = g++ AUXLIB = auxiliar_code/aux_functions.h SOCKETLIB = socket_operations/socket_functs.h COMMANDSLIB = commands/commands.h .PHONY: all clean run all: client client: socket_operations/socket.o auxiliar_code/aux.o commands/commands.o commands/client.o main.o $(LD) -o user socket_operations/socket.o auxiliar_code/aux.o commands/commands.o commands/client.o main.o auxiliar_code/aux.o: auxiliar_code/aux_functions.cpp $(AUXLIB) client_constants.h $(CC) -o auxiliar_code/aux.o -c auxiliar_code/aux_functions.cpp commands/client.o: commands/Client.cpp $(COMMANDSLIB) $(SOCKETLIB) $(AUXLIB) client_constants.h $(CC) -o commands/client.o -c commands/Client.cpp commands/commands.o: commands/commands.cpp $(COMMANDSLIB) $(SOCKETLIB) $(AUXLIB) client_constants.h $(CC) -o commands/commands.o -c commands/commands.cpp socket_operations/socket.o: socket_operations/socket_functs.cpp $(SOCKETLIB) $(AUXLIB) client_constants.h $(CC) -o socket_operations/socket.o -c socket_operations/socket_functs.cpp main.o: main.cpp $(COMMANDSLIB) $(AUXLIB) client_constants.h $(CC) $(CFLAGS) -o main.o -c main.cpp clean: @echo Cleaning files generated rm -f auxiliar_code/*.o commands/*.o socket_operations/*.o *.o user run: user @echo ./user $(filter-out $@,$(MAKECMDGOALS)) %: @:
What you should do is to declare a variable (possibly with default): # Fill in your default here, setting from command line will override USER_OPTIONS ?= run: user ./user $(USER_OPTIONS) Then invoke make setting the option from the command line: make run USER_OPTIONS="-n tejo.tecnico.ulisboa.pt -p 58011"
70,643,705
70,643,831
std::this_thread::sleep_for() freezing the program
I am making a loading type function so what I wanted to do was to halt my program for a few seconds and then resume the execution inside a loop to make it look like a loading process. Looking up on web I found that I can use std::this_thread::sleep_for() to achieve this (I am doing this on linux). The problem I am facing is that I am unable to make it work with \r or any other way to overwrite the last outputted percentage as the program freezes as soon as I do it, however it works perfectly with \n and it's all confusing to understand why it'd work with a newline sequence but not with \r. I am posting the sample code below, can someone tell me what am I doing wrong? #include<iostream> #include<chrono> #include<thread> int main() { for (int i = 0; i<= 100; i++) { std::cout << "\r" << i; std::this_thread::sleep_for(std::chrono::seconds(rand()%3)); } return 0; } I am kinda new to this topic and after some digging I found out that I am messing with the threads. But still not sure why this behavior is happening.
This works fine on my machine (Windows 10): #include <iostream> #include <chrono> #include <thread> #include <cstdlib> #include <ctime> int main( ) { std::srand( std::time( 0 ) ); for ( std::size_t i { }; i < 100; ++i ) { std::cout << '\r' << i; std::this_thread::sleep_for( std::chrono::seconds( std::rand( ) % 3 ) ); } } I suggest that you write '\r' instead of "\r" cause here you only want to print \r character and "\r" actually prints two characters (\r and \0). Also, it's better to seed rand using srand before calling it. However, it may not work as expected in some environments so you may need to flush the output sequence like below: std::cout << '\r' << i << std::flush; or like this: std::cout << '\r' << i; std::cout.flush( ); These are equivalent. For more info about flush see here.
70,643,880
70,647,411
Leaky Meyers Singleton: is it threadsafe?
I implemented a Meyers Singleton, then realized it could be vulnerable to the destructor fiasco problem. As a result, I changed the code to be: Instance *getInstance() { static Instance* singleton = new Instance(); return singleton; } After implementing this, and no apparent bugs occuring, a coworker was implementing a different singleton and used std::call_once instead. I've now realized that after much searching, I couldn't find if the "Leaky Meyers Singleton" is a threadsafe pattern. Should the leaky singleton be changed to std::call_once? Or is it threadsafe as-is? Is the pointer considered a "block-scope" variable? If so I think it would be thread-safe, but if not there's significant bugs introduced with the current leaky singleton approach.
Yes, this is thread-safe: no two threads will ever try to initialize the same variable with static storage duration at the same time. That includes the entirety of evaluating the initializer.
70,644,005
70,644,045
Constructor vs default constructor
I'm an aspiring software engineer and full-time CS student. During the holiday break, I have been working on exercises to be better at my craft (C++). There are topics that I just need some clarity on. I'm working on a Target Heart Rate Calculator. I have spent hours, days, trying to understand the concept of the constructor vs default constructor. I know that a constructor is required for every object created. Before going any further, I want to test my code where it prompts the user to enter their first name and then return it. For once and for all, for the slow learners out there struggling including myself, can anyone please just explain this in Layman's terms with a visual explanation, please? Below is my code. I'm receiving an error: no matching function for call to 'HeartRates::HeartRates()' main.cpp int main() { HeartRates patient; cout << "First name: "; string firstName; cin >> firstName; patient.setFirstName(firstName); patient.getFirstName(); return 0; HeartRate.h // create a class called HeartRates class HeartRates { public: // constructor receiving data HeartRates(string personFirstName, string personLastName, int month, int day, int year) { firstName = personFirstName; lastName = personLastName; birthMonth = month; birthDay = day; birthYear = year; } void setFirstName(string personFirstName) { firstName = personFirstName; } string getFirstName() { return firstName; } private: // attributes string firstName, lastName; int birthMonth, birthDay, birthYear; }; Thank you, everyone! Sheesh! My book adds all these extra words that aren't necessary and makes the reading hard. All it had to say was: If you want to create an object to receive information from a user, make sure your constructor has empty (). If you have data to input manually, pass that data through your constructor's parameters. I hope this was the guise of your explanation. I love this community - thank you so much! You all have no idea about my back story - basically transitioning from a 15 years marketing/advertising career to becoming a software engineer. You all have been so welcoming and it confirms I made a great decision to switch.✊ Here is my updated code: main.cpp int main() { HeartRates patient; cout << "First name: "; string firstName; cin >> firstName; patient.setFirstName(firstName); cout << patient.getFirstName(); return 0; } HeartRates.h // create a class called HeartRates class HeartRates { public: // constructor receiving data - THANKS STACKOVERFLOW COMMUNITY HeartRates() { firstName; lastName; birthMonth; birthDay; birthYear; } void setFirstName(string personFirstName) { firstName = personFirstName; } string getFirstName() { return firstName; } private: // attributes string firstName, lastName; int birthMonth, birthDay, birthYear; };
If you don't define any constructor, you get a constructor that takes no arguments. As soon as you defined a constructor that has arguments, your no-args constructor retired to the North Pole. So now you must write HeartRate("first", "last", 1, 1, 2001) If you don't want to write that, delete the parameter list from your constructor and just set whatever you want for initial values.
70,644,034
70,644,067
How do I fix "no match for call to" in recursion inside a function? (in a permutation recursion algorithm)
void perm(std::string fixed,std::string perm){ if (perm.length() == 1){ std::cout << fixed + perm << std::endl; }else{ for (int i=0;i<perm.length();i++){ std::string perm2 = perm; std::swap(perm2[0],perm2[i]); perm(fixed + perm[i],perm2.substr(1,perm.length()-1)); } } } This is my first question and I am (very) new to programming. I was working on a mini program which simply prints all the permutations of a string. For example, perm("","123") would be supposed to return the following values 123 132 213 231 312 321 However, on compilation, the g++ compiler returns the following error: permutations.cpp: In function ‘void perm(std::string, std::string)’: permutations.cpp:19:29: error: no match for call to ‘(std::string {aka std::__cxx11::basic_string<char>}) (std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char>)’ 19 | perm(fixed + perm[i],perm2.substr(1,perm.length()-1)); | ~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ I would like to know the cause of this error and troubleshoot it. Thank you.
void perm(std::string fixed,std::string perm){ You have a function called perm, and one of its parameters is also called perm, same name. Danger ahead. perm(fixed + perm[i],perm2.substr(1,perm.length()-1)); According to rules of C++, the first perm here is a std::string object, one of the parameters to this function. This is not getting parsed as a recursive call to the same function, but an attempt to invoke a suitable operator() on a std::string object. Your C++ compiler is grumpy because no suitable overload was found. Solution: don't use the same name for a function and one of its parameters.
70,644,062
70,644,165
Callback definition is incompatible
I use a library which has these definitions typedef void (*CallbackFunction) (ESPRotary&); void ESPRotary::setChangedHandler(CallbackFunction f) { ... } When I try to use the setChangedHandler function I get an issue that the definition of my callback is wrong. #pragma once #include "ESPRotary.h" class MyUsermod : public Usermod { private: ESPRotary r = ESPRotary(13, 12); public: void rotate(ESPRotary &r) { Serial.println(r.getPosition()); } void setup() { // argument of type "void (MyUsermod::*)(ESPRotary &r)" is incompatible // with parameter of type "ESPRotary::CallbackFunction"C/C++(167) r.setChangedHandler(rotate); } }; What am I doing wrong?
The callback function needs to be defined statically when defined inside the class: class MyUsermod : public Usermod { private: ESPRotary r = ESPRotary(13, 12); public: /* Callback function "static" defined */ static void rotate(ESPRotary &r) { Serial.println(r.getPosition()); } void setup() { r.setChangedHandler(rotate); } }; References Why callback functions needs to be static when declared in class?
70,644,176
70,644,205
Cannot erase a shared_ptr from set
I am trying to have an object with a set of pointers to another object. when I try to erase on of the set's values I get an error and crash, I really dont know what could be causing it. here is the library and after that the main function: when I try to run it it does everything its supposed to do, and when it gets to the removeemployee it crashes and sends out the following: Process finished with exit code -1073740940 (0xC0000374) I run it on clion if that matters, and in c++11. #include <ostream> #include <iostream> #include "Manager.h" Manager::Manager(int id, string firstName, string lastName, int birthYear) : Citizen(id, firstName, lastName,birthYear), salary(0), employees(), work_flag(false) {} int Manager::getSalary() const { return salary; } void Manager::setSalary(int _salary) { if((salary + _salary) < 0){ salary = 0; }else { salary += _salary; } } void Manager::addEmployee(Employee* employee_add) { shared_ptr<Employee> employee(employee_add); if(employees.find(employee) != employees.end()){ throw mtm::EmployeeAlreadyExists(); } employees.emplace(employee); } //this is the function void Manager::removeEmployee(int id) { for(auto it = employees.begin(); it != employees.end(); it++){ if(it->get()->getId() == id){ employees.erase(it); return; } } throw mtm::EmployeeDoesNotExists(); } Manager *Manager::clone() { return new Manager(*this); } ostream &Manager::printShort(ostream &os) const { os<<this->getFirstName()<<" "<<this->getLastName()<<endl; os<<"Salary :"<<this->getSalary()<<endl; return os; } ostream &Manager::printLong(ostream &os) const { os<<this->getFirstName()<<" "<<this->getLastName()<<endl; os<<"id - "<<this->getId()<<" birth_year - "<<this->getBirthYear()<<endl; os<<"Salary :"<<this->getSalary()<<endl; os<<"Employees:"<<endl; for(const auto & employee : employees){ employee->printShort(os); } return os; } bool Manager::findEmployee(int id) { int i = 0; for(const auto & employee : employees){ cout<<++i<<endl; if(employee->getId() == id){ cout<<"return true"<<endl; return true; } } cout<<"return false"<<endl; return false; } bool Manager::isWorkFlag() const { return work_flag; } void Manager::setWorkFlag(bool workFlag) { work_flag = workFlag; } and this is the main function: int main() { Employee e1(1, "John", "Williams", 2002); Employee e2(2, "Alex", "Martinez", 2000); Manager m1(1,"Robert", "stark", 1980); m1.addEmployee(&e1); m1.addEmployee(&e2); Employee e3(7, "Reuven", "Guetta", 2001); m1.addEmployee(&e3); m1.printLong(cout); cout<<"Delete"<<endl; //here is the problem m1.removeEmployee(e2.getId()); m1.printLong(cout); return 0; }
shared_ptr<Employee> employee(employee_add); There is only one reason to have a shared_ptr, in the first place; there's only one reason for its existence; it has only one mission in its life, as explained in every C++ textbook: to be able to new an object, and have the shared_ptr automatically take care of deleteing it when all references to the object are gone, avoiding a memory leak. In your program this object was not instantiated in dynamic scope with new: Employee e2(2, "Alex", "Martinez", 2000); Manager m1(1,"Robert", "stark", 1980); m1.addEmployee(&e1); // etc, etc, etc... and that's the reason for the crash. If you are not using new, simply get rid of all shared_ptrs in the shown code.
70,644,252
70,644,286
Is there a way to optimise the Collatz conjecture into a branchless algorithm?
I'm trying to create an algorithm that will compute the collatz conjecture, this is the code so far: while (n > 1) { n % 2 == 0 ? n /= 2 : n = n * 3 + 1; } I was wondering if there was a way to optimize this any further since efficiency and speed is crucial for this, and I've heard about branchless programming but I'm not sure how to implement it, or if it's worth it to begin with.
Sure. You need the loop, of course, but the work inside can be done like this: n /= (n&-n); // remove all trailing 0s while(n > 1) { n = 3*n+1; n /= (n&-n); // remove all trailing 0s } It also helps that this technique does all the divisions by 2 at once, instead of requiring a separate iteration for each of them.
70,644,411
70,644,626
Aliasing - what is the clang optimizer afraid of?
Take this toy code (godbolt link): int somefunc(const int&); void nothing(); int f(int i) { i = somefunc(i); i++; nothing(); i++; nothing(); i++; return i; } As can be seen in the disassembly at the link, the compiler reloads i from the stack 3 times, increments and stores back. If somefunc is modified to accept int by value, this doesn't happen. (1) Is the optimizer 'afraid' that since somefunc has access to is address, it can indirectly modify it? Can you give an example of well defined code that does that? (remember that const_cast'ing away and modifying is undefined behavior). (2) Even if that was true, I'd expect that decorating somefunc with __attribute__((pure)) would stop that pessimization. It doesn't. Why? Are these llvm missed optimizations? Edit: If somefunc returns void, __attribute__((pure)) does kick in as expected: void somefunc(const int&) __attribute__((pure)); void nothing(); int f(int i) { somefunc(i); i++; nothing(); i++; nothing(); i++; return i; } Maybe this attribute is sort of half baked (it is rare in practice).
As mentioned in a comment, using const_cast to remove the constness of a reference to an object that was defined as non-const is well-defined. In fact, that's its only real use. As for __attribute__((pure)): Who knows. The nothing() calls are necessary to reproduce the situation; if those are marked pure then proper optimization is done; the invocation of somefunc doesn't have much of an impact on that situation. Basically, the compiler tends to be quite conservative unless everything in a code block is pure. While it should arguably be able to deduce that nothing() doesn't affect i, that's very much a "best effort" area of optimization and not something that properly optimized code should rely on.
70,644,482
70,645,311
system("cls") command closes the input terminal
The problem is located under the Draw function, where I use the system() command. #include <iostream> #include <conio.h> #include <stdlib.h> using namespace std; bool gameover; const int width = 60; const int height = 30; int x, y, FruitX, FruitY; enum edirection { Stop = 0, Left, Right, Up, Down, }; edirection dir; void Setup() { gameover = true; dir = Stop; x = width / 2; y = height / 2; FruitX = rand() % width; FruitY = rand() % height; } void Draw() { system("cls"); //Clears Screen, but is not working!!! //Top Line for (int i = 0; i <= width; i++) cout << "#"; cout << endl; //Side Lines for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (j == 0 || j == width - 1) cout << "#"; if (i == y && j == x) cout << "<"; else if (i == FruitY && j == FruitX) cout << "@"; else if (j > 0 || j != width - 1) cout << " "; } cout << endl; } //Bottom Line for (int i = 0; i <= width; i++) cout << "#"; cout << endl; } void Input() { if (_kbhit()) { switch (_getch()) { case 'a': dir = Left; break; case 'd': dir = Right; break; case 'w': dir = Up; break; case 's': dir = Down; break; case 'x': gameover = true; break; } } } void Logic() { switch (dir) { case Left: x--; break; case Right: x++; break; case Up: y--; break; case Down: y++; break; default: break; } } int main() { Setup(); while (!gameover); { Draw(); Input(); Logic(); } }
I improved your code and now it works to some degree. However, I can't write the whole game for you since I have no info on how it should be written. Take a look: #include <iostream> #include <cstdlib> #include <ctime> #include <conio.h> struct GameStatus { static constexpr std::size_t width { 60 }; static constexpr std::size_t height { 30 }; std::size_t x { }; std::size_t y { }; std::size_t FruitX { }; std::size_t FruitY { }; enum edirection { Stop = 0, Left, Right, Up, Down, }; edirection dir; bool gameover { }; }; void Setup( GameStatus& game_status ) { game_status.gameover = false; game_status.dir = game_status.Stop; game_status.x = game_status.width / 2; game_status.y = game_status.height / 2; std::srand( std::time( 0 ) ); game_status.FruitX = std::rand( ) % game_status.width; game_status.FruitY = std::rand( ) % game_status.height; } void Draw( GameStatus& game_status ) { system( "cls" ); //Top Line for ( std::size_t i { }; i <= game_status.width; ++i ) { std::cout << '#'; } std::cout << '\n'; //Side Lines for ( std::size_t i { }; i < game_status.height; ++i ) { for ( std::size_t j { }; j < game_status.width; ++j ) { if ( j == 0 || j == game_status.width - 1 ) std::cout << '#'; if ( i == game_status.y && j == game_status.x ) std::cout << '<'; else if ( i == game_status.FruitY && j == game_status.FruitX ) std::cout << '@'; else if ( j > 0 || j != game_status.width - 1 ) std::cout << ' '; } std::cout << '\n'; } //Bottom Line for ( std::size_t i { }; i <= game_status.width; ++i ) std::cout << '#'; std::cout << '\n'; } void Input( GameStatus& game_status ) { if ( _kbhit( ) ) { switch ( _getch( ) ) { case 'a': game_status.dir = game_status.Left; break; case 'd': game_status.dir = game_status.Right; break; case 'w': game_status.dir = game_status.Up; break; case 's': game_status.dir = game_status.Down; break; case 'x': game_status.gameover = true; break; } } } void Logic( GameStatus& game_status ) { switch ( game_status.dir ) { case game_status.Left: --game_status.x; break; case game_status.Right: ++game_status.x; break; case game_status.Up: --game_status.y; break; case game_status.Down: ++game_status.y; break; default: break; } } int main( ) { GameStatus game_status; Setup( game_status ); while ( !game_status.gameover ) { Draw( game_status ); Input( game_status ); Logic( game_status ); } } You can see the struct GameStatus. All those dangerous globals are now encapsulated in an instance of this struct called game_status. All the functions can receive a reference to that object and then use it (read/modify).
70,644,798
70,644,827
Is it possible to intialize array filled with zeros in member initializer list?
I need to define an empty constructor of class Array, which has one argument that contains value of parameter m. It needs to allocate memory for m elements in an array and initialize it with zeros. class Array{ protected: int* data; int m; public: Array(int m); }; Is it possible to initialize it with zeros in member initializer list, or it can't be done except with a for loop in the body of this constructor. I defined this constructor like this: Array::Array(int m):m(m),data(new int[m]){} but of course its filled with random trash values leftover in the memory.
You may write either Array::Array(int m): m( m ), data( new int[m]() ) { } or Array::Array(int m): m( m ), data( new int[m]{} ) { } It is better to declare the data member m as having the type size_t instead of the type int.
70,645,211
70,645,283
Why is it allowed for the C++ compiler to opmimize out memory allocations with side effects?
Another question discusses the legitimacy for the optimizer to remove calls to new: Is the compiler allowed to optimize out heap memory allocations?. I have read the question, the answers, and N3664. From my understanding, the compiler is allowed to remove or merge dynamic allocations under the "as-if" rule, i.e. if the resulting program behaves as if no change was made, with respect to the abstract machine defined in the standard. I tested compiling the following two-files program with both clang++ and g++, and -O1 optimizations, and I don't understand how it is allowed to to remove the allocations. // main.cpp #include <cstdio> extern int g_alloc; static int* foo(int n) { // operator new is globally overridden in the other file. return new int(n); } int main(int argc, char** argv) { foo(argc); foo(argc*2); printf("allocated: %d\n", g_alloc); return g_alloc; } // new.cpp #include <cstdio> #include <cstdlib> #include <new> int g_alloc = 0; void* operator new(size_t n) { g_alloc += n; printf("new %lu\n", n); return malloc(n); } The idea is to override the default operator new(size_t) with a function with side effects: printing a message and modifying a global variable, the latter being used as the exit code. The side effects do not impact the allocation itself but it still change the output of the program. Indeed, when compiled without optimizations, the output is: new 4 new 4 allocated: 8 But as soon as optimizations are enabled, the output is: allocated: 0 The result is the same with when using standards 98 to 17. How is the compiler allowed to omit the allocations here? How does it fit the as-if rule?
Allocation elision is an optimization that is outside of and in addition to the as-if rule. Another optimization with the same properties is copy elision (not to be confused with mandatory elision, since C++17): Is it legal to elide a non-trivial copy/move constructor in initialization?.
70,645,649
70,645,697
C++ overload of swap function not working
I'm writing a custom class for which I want to use the std::swap function. As I read in this post How to overload std::swap() , I have to overload it in the same namespace of the object I'm trying to swap and there's an example. I (thing) I'm replicating the example, but the function that gets called when using std::swap() isn't the one defined by me. Here is what my code looks alike: //grid.hpp namespace myname { template <typename T> class Grid { ... friend void swap(Grid &a, Grid &b) { using std::swap; std::cout << "Custom Swap Used" << std::endl; swap(a.nrwow, b.nrows); swap(a.ncols, b.ncols); a.grid.swap(b.grid); } } } but when I call the swap function no string gets printed, so this function doesn't get called. //file.cpp #include"../src/grid.hpp" int main() { myname::Grid<int> grid1(10, 10); myname::Grid<int> grid2(10, 10); std::swap(grid1, grid2); // this should print a string }
You have to uses std::ranges::swap, or find it via ADL if you aren't using C++20: myname::Grid<int> grid1(10, 10); myname::Grid<int> grid2(10, 10); std::ranges::swap(grid1, grid2); // Or with ADL using std::swap; swap(grid1, grid2); "Swapping" does not exactly mean std::swap, but this form of "using std::swap; swap(x, y);", which is encapsulated by std::ranges::swap. Writing std::swap(grid1, grid2) directly calls the default template<typename T> void std::move(T&, T&);. This will use the move construct and move assignment operators instead of your custom swap function, which is why you don't see "Custom Swap Used".
70,645,885
70,646,403
How to properly generically forward a parameter pack into a lambda?
I'm trying to forward a generic parameter pack from a base function, but trouble doing so, particularly if there are non-literal non-reference types in the type list Considering the following example: #include <utility> #include <iostream> #include <future> #include <vector> template < typename... Args > class BaseTemplate { public: BaseTemplate() = default; virtual ~BaseTemplate() = default; virtual std::future< void > call(Args... args) { return std::async(std::launch::async, [this, &args... ] { // .. first(std::forward<Args>(args)...); second(std::forward<Args>(args)...); third(std::forward<Args>(args)...); // ... }); } protected: virtual void first(Args...) { /* ... */ } virtual void second(Args...) = 0; virtual void third(Args...) { /* ... */ } }; class SomeType { public: explicit SomeType(std::vector< float >* data) : ptr(data) { /* ... */ } ~SomeType() = default; // ... // protected: float member = 5.6; std::vector< float >* ptr; }; class Derived1 : public BaseTemplate< int, float, SomeType > { public: using Base = BaseTemplate< int, float, SomeType >; Derived1() : Base() { /* ... */ } ~Derived1() = default; protected: void second(int, float, SomeType obj) override { std::cout << "Derived1::" << __func__ << " (" << obj.member << ")" << std::endl; printf("%p\n", obj.ptr); for (const auto& val : *(obj.ptr)) { std::cout << val << std::endl; } } }; class Derived2 : public BaseTemplate< int, float, const SomeType& > { public: using Base = BaseTemplate< int, float, const SomeType& >; Derived2() : Base() { /* ... */ } ~Derived2() = default; protected: void second(int, float, const SomeType& obj) override { std::cout << "Derived2::" << __func__ << " (" << obj.member << ")" << std::endl; printf("%p\n", obj.ptr); for (const auto& val : *(obj.ptr)) { std::cout << val << std::endl; } } }; int main(int argc, char const *argv[]) { std::vector< float > data {0, 1, 2, 3}; SomeType obj(&data); Derived1 foo1; Derived2 foo2; // auto bar1 = foo1.call(1, 5.6, obj); // Segmentation fault auto bar2 = foo2.call(1, 5.6, obj); // OK // ... // bar1.wait(); bar2.wait(); return 0; } Everything works as intended if SomeType is passed by reference, but segfaults if passed by value. What is the proper way to use std::forward<>() in order to account for both cases?
The problem is not with std::forward calls; the program exhibits undefined behavior before it gets to them. call takes some parameters by value, but the lambda inside always captures them by reference. Thus, it ends up holding references to local variables, which are destroyed as soon as call returns - but the lambda is called later, possibly on a different thread. At that point, all those references are dangling - not just the reference to SomeType, but also to int and to float. One possible solution could go like this: virtual std::future< void > call(Args... args) { std::tuple<BaseTemplate*, Args...> t{this, args...}; return std::async(std::launch::async, [t] { // .. std::apply(&BaseTemplate::first, t); std::apply(&BaseTemplate::second, t); std::apply(&BaseTemplate::third, t); // ... }); } We store arguments in a tuple - copies of those passed by value, references to those passed by reference. Then the lambda captures this tuple by value, and uses std::apply to pass its components along to the actual function being called. Demo
70,645,895
70,646,813
Weird characters appear at the end of file when encrypting it
I never thought I would have to turn to SO to solve this. Alright so for more insight I am making my own encryption program. I'm not trying to make it good or anything it's just a personal project. What this program is doing is that it's flipping certain bits in every single byte of the character making it unreadable. However every time I run the program and decrypt I get weird characters on the output. These characters seem to match the amount of lines as following: ^^ text that I want to encrypt ^^ after encrypting. (a lot of the text got cut off) ^^ after decrypting. there's 10 null character corresponding to the amount of newlines. there also seems to be another weird '�' character. Where are these bytes coming from?? I've tried a lot of stuff. Here is my code if anyone needs it (it's compiled with default flags): #include <iostream> #include <fstream> #include <cstring> #include <string> #define ENCRYPTFILE "Encrypted.oskar" typedef unsigned char BYTE; char saltFunc(BYTE salt, char chr) { for(int i = 0; i < 8; i++) { if((salt >> i) & 1U) { chr ^= 1UL << i; } } return chr; } int main () { std::ofstream encryptFile(ENCRYPTFILE, std::ifstream::in); std::ifstream inputFile(ENCRYPTFILE, std::ifstream::in); unsigned int length; unsigned int lineLength; BYTE salt = 0b00000001; std::string line; std::cin.unsetf(std::ios::dec); std::cin.unsetf(std::ios::hex); std::cin.unsetf(std::ios::oct); //std::cout << "input salt in hex with a prefix 0x so for example. 0xA2" << std::endl; //std::cin >> std::hex >> salt; inputFile.seekg(0, inputFile.end); length = inputFile.tellg(); inputFile.seekg(0, inputFile.beg); std::cout << lineLength << std::endl; char* fileBuffer = new char[length]; char* encryptFileBuffer = new char[length]; memset(fileBuffer, 0, length); memset(encryptFileBuffer, 0, length); while (inputFile.good()) { // just get file length in bytes. static int i = 0; fileBuffer[i] = inputFile.get(); i++; } while (std::getline(inputFile, line)) ++lineLength; inputFile.clear(); encryptFile.clear(); std::cout << "file size: " << length << std::endl; for(int i = 0; i < length; i++) { encryptFileBuffer[i] = saltFunc(salt, fileBuffer[i]); encryptFile << encryptFileBuffer[i]; } inputFile.close(); encryptFile.close(); delete[] encryptFileBuffer; delete[] fileBuffer; return 0; }
The problem is that you are measuring the length of the file in bytes, which, for text files, is not the same as the length in characters. But you are then reading it as characters, so you end up reading too many characters and then writing extra garbage after then end in the output file. Since you are getting one extra character per line, it is likely you are running on Windows, where line ending characters are two bytes in the file. That's where the extra incorrect length you are seeing is coming from. For encryption/decryption what you probably want to do is read and write the file in binary mode, so you are reading and writing bytes not characters. You do this by adding std::ios::binary into the flags when opening the file(s): std::ofstream encryptFile(ENCRYPTFILE, std::ifstream::in | std::ios::binary); std::ifstream inputFile(ENCRYPTFILE, std::ifstream::in | std::ios::binary);
70,645,945
70,646,004
What are the use cases of class member functions marked &&?
I don't know which C++ standard presented this feature, but I cannot think of any use cases of this. A member functions with && modifier will only be considered by overload resolution if the object is rvalue struct Foo { auto func() && {...} }; auto a = Foo{}; a.func(); // Does not compile, 'a' is not an rvalue std::move(a).func(); // Compiles Foo{}.func(); // Compiles Can someone please explain the use case for this? Why we ever want some routine to be performed only for rvalues?
Ref-qualification was added in c++11. In general, propagation of the value-category is incredibly useful for generic programming! Semantically, ref-qualifications on functions help to convey the intent; acting on lvalue references or rvalues -- which is analogous to const or volatile qualifications of functions. These also parallel the behavior of struct members, which propagate the qualifiers and categories. A great example of this in practice is std::optional, which provides the std::optional::value() function, which propagates the value-category to the reference on extraction: auto x = std::move(opt).value(); // retrieves a T&& This is analogous to member-access with structs, where the value-category is propagated on access: struct Data { std::string value; }; auto data = Data{}; auto string = std::move(data).value; // expression yields a std::string&& In terms of generic composition, this massively simplifies cases where the input may be an lvalue or an rvalue. For example, consider the case of using forwarding references: // Gets the internal value from 'optional' template <typename Optional> auto call(Optional&& opt) { // will be lvalue or rvalue depending on what 'opt' resolves as return std::forward<Optional>(opt).value(); } Without ref-qualification, the only way to accomplish the above code would be to create two static branches -- either with if constexpr or tag-dispatch, or some other means. Something like: template <typename Optional> auto call(Optional&& opt) { if constexpr (std::is_lvalue_reference_v<Optional>) { return opt.value(); } else { return std::move(opt.value()); } } On a technical level, rvalue-qualifications on functions provides the opportunity to optimize code with move-constructions and avoid copies in a semantically clear way. Much like when you see a std::move(x) on a value, you are to expect that x is expiring; it's not unreasonable to expect that std::move(x).get_something() will cause x to do the same. If you combine && overloads with const & overloads, then you can represent both immutable copying, and mutating movements in an API. Take, for example, the humble "Builder" pattern. Often, Builder pattern objects hold onto pieces of data that will be fed into the object on construction. This necessitates copies, whether shallow or deep, during construction. For large objects, this can be quite costly: class Builder { private: // Will be copied during construction expensive_data m_expensive_state; ... public: auto add_expensive_data(...) -> Builder&; auto add_other_data(...) -> Builder&; ... auto build() && -> ExpensiveObject { // Move the expensive-state, which is cheaper. return ExpensiveObject{std::move(m_expensive_state), ...} } auto build() const & -> ExpensiveObject // Copies the expensive-state, whcih is costly return ExpensiveObject{m_expensive_state, ...} } ... }; Without rvalue-qualifications, you are forced to make a choice on the implementation: Do destructive actions like moves in a non-const function, and just document the safety (and hope the API isn't called wrong), or Just copy everything, to be safe With rvalue-qualifications, it becomes an optional feature of the caller, and it is clear from the authored code what the intent is -- without requiring documentation: // Uses the data from 'builder'. May be costly and involves copies auto inefficient = builder.build(); // Consumes the data from 'builder', but makes 'efficient's construction // more efficient. auto efficient = std::move(builder).build(); As an added benefit, static-analysis can often detect use-after-move cases, and so an accidental use of builder after the std::move can be better caught than simple documentation could.
70,646,081
70,656,303
(0xc0210000) Error while trying to Connect PostgreSQL via C++
Background I'm trying to establish a basic connection to a Postgresql Database via C++. For that i'm using Visual Studio 2019. I'm following the instructions that can be found in http://www.tutorialspoint.com/postgresql/postgresql_c_cpp.htm The paths to the additional libpqxx and PostgreSQL includes, libraries and dependencies have all been added: Includes, Libraries, Dependencies. I'm trying to connect to a Database "test" at port 5433. #include <string> #include <iostream> #include <pqxx/pqxx> using namespace std; using namespace pqxx; int main(int argc, char* argv[]) { try { connection C("dbname = test user = postgres password = 1234 hostaddr = localhost port = 5433"); if (C.is_open()) { cout << "Opened database successfully: " << C.dbname() << endl; } else { cout << "Can't open database" << endl; return 1; } //C.disconnect(); } catch (const std::exception & e) { cerr << e.what() << std::endl; return 1; } } Problem Building in Debug mode (x64) works without problem: Rebuild started... 1>------ Rebuild All started: Project: TEST_IT002, Configuration: Debug x64 ------ 1>TEST_IT002.cpp 1>C:\Users\yassi\source\repos\TEST_IT002\TEST_IT002\TEST_IT002.cpp(8,26): warning C4100: 'argv': unreferenced formal parameter 1>C:\Users\yassi\source\repos\TEST_IT002\TEST_IT002\TEST_IT002.cpp(8,14): warning C4100: 'argc': unreferenced formal parameter 1>TEST_IT002.vcxproj -> C:\Users\yassi\source\repos\TEST_IT002\x64\Debug\TEST_IT002.exe 1>Done building project "TEST_IT002.vcxproj". ========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ========== But as soon as i try to run the Programm (also in Debug Mode x64), i get the following Error: 'TEST_IT002.exe' (Win32): Loaded 'C:\Users\yr\source\repos\TEST_IT002\x64\Debug 'TEST_IT002.exe'. Symbols loaded. 'TEST_IT002.exe' (Win32): Loaded 'C:\Windows\System32\ntdll.dll'. 'TEST_IT002.exe' (Win32): Loaded 'C:\Windows\System32\kernel32.dll'. 'TEST_IT002.exe' (Win32): Loaded 'C:\Windows\System32\KernelBase.dll'. 'TEST_IT002.exe' (Win32): Loaded 'C:\Windows\System32\ws2_32.dll'. 'TEST_IT002.exe' (Win32): Loaded 'C:\Windows\System32\rpcrt4.dll'. 'TEST_IT002.exe' (Win32): Loaded 'C:\Windows\System32\msvcp140d.dll'. 'TEST_IT002.exe' (Win32): Loaded 'C:\Windows\System32\vcruntime140d.dll'. 'TEST_IT002.exe' (Win32): Loaded 'C:\Windows\System32\vcruntime140_1d.dll'. 'TEST_IT002.exe' (Win32): Loaded 'C:\Windows\System32\ucrtbased.dll'. The thread 0x4e24 has exited with code -1071579136 (0xc0210000). The thread 0x2624 has exited with code -1071579136 (0xc0210000). The program '[8808] TEST_IT002.exe' has exited with code -1071579136 (0xc0210000). I have tried to connect to the default database and I have tried different Versions of Libpqxx, Unfortunately i still get the same error message: Any suggestion to help solve this issue is highly appreciated. Thank you!
For those running into similar issue, following the latest instructions in the libpqxx Gitub page would solve the issue.
70,646,126
70,646,346
OpenGL mix fix pipeline and shader program (Qt)
I'm working on a old code that used fixed function pipeline, the scene is a bit complex but works fine. For the sake of simplicity, I replaced it with one blue triangle : void RenduOpenGL::paintGL() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glViewport(0, 0, this->width(), this->height()); glBegin(GL_TRIANGLES); glColor3d(0,0,1); glVertex3d(0.7, 0.7, 0.0); glVertex3d(-0.5, 0.7, 0.0); glVertex3d(0.1, -0.7, 0.0); glEnd(); } Now I want to add shaders for new elements in the scene but keep the old elements of the scene like this blue triangle. I've read here that I can mix the two to produce a scene containing the first then the second. Therefore I want to add this code after the blue triangle : float vertices[] = { 0.6, 0.6, 0.0, -0.6, 0.6, 0.0, 0.0, -0.6, 0.0, }; vbo.create(); // glGenBuffers(...); vbo.bind(); // glBindBuffer(GL_ARRAY_BUFFER, vbo); vbo.allocate(vertices, sizeof(vertices)); // glBufferData(GL_ARRAY_BUFFER, 9 * sizeof(float), vertices, GL_STATIC_DRAW); vbo.release(); // glBindBuffer(GL_ARRAY_BUFFER, 0); prog.addShaderFromSourceFile(QOpenGLShader::Vertex, "shaders/base.vert"); prog.addShaderFromSourceFile(QOpenGLShader::Fragment, "shaders/base.frag"); vao.create(); // glGenVertexArrays(...) vao.bind(); // glBindVertexArray(vao); prog.enableAttributeArray("position"); // glEnableVertexAttribArray(VAO_position); prog.setAttributeBuffer("position", GL_FLOAT, 0, 3); // (offset, size, stride=0); // glVertexAttribPointer(VAO_position, 4, GL_FLOAT, False, 0, reinterpret_cast<const void *>(offset)(0)); (False, vao.release(); // glBindVertexArray(0); // draw the triangle prog.bind(); // glUseProgram(shader_program); vao.bind(); // glBindVertexArray(vertex_array_object); glDrawArrays(GL_TRIANGLES, 0, 3); vao.release(); // glBindVertexArray(0); prog.release(); // glUseProgram(0); I use Qt to call the openGL functions, the corresponding opengl functions are in comments. My shaders are very basic : // base.vert #version 330 // vertex shader in vec3 position; void main() { gl_Position = vec4(position.xyz, 1); } // base.frag #version 330 // fragment shader out vec4 pixel; void main() { pixel = vec4(1, 0.5, 0, 1); } That is supposed to draw an orange triangle, but when I put the code after the blue triangle code, I don't see the orange triangle created from shaders.
Short (with code) answer: The VBO and the prog.enableAttributeArray and prog.setAttributeBuffer should be in the VAO. Something along the lines: float vertices[] = { 0.6, 0.6, 0.0, -0.6, 0.6, 0.0, 0.0, -0.6, 0.0, }; prog.bind(); // glUseProgram(shader_program); vao.create(); // glGenVertexArrays(...) vao.bind(); // glBindVertexArray(vao); vbo.create(); // glGenBuffers(...); vbo.bind(); // glBindBuffer(GL_ARRAY_BUFFER, vbo); vbo.allocate(vertices, sizeof(vertices)); // glBufferData(GL_ARRAY_BUFFER, 9 * sizeof(float), vertices, GL_STATIC_DRAW); //vbo.release(); // glBindBuffer(GL_ARRAY_BUFFER, 0); prog.addShaderFromSourceFile(QOpenGLShader::Vertex, "shaders/base.vert"); prog.addShaderFromSourceFile(QOpenGLShader::Fragment, "shaders/base.frag"); prog.enableAttributeArray("position"); // glEnableVertexAttribArray(VAO_position); prog.setAttributeBuffer("position", GL_FLOAT, 0, 3); // (offset, size, stride=0); // glVertexAttribPointer(VAO_position, 4, GL_FLOAT, False, 0, reinterpret_cast<const void *>(offset)(0)); (False, vao.release(); // glBindVertexArray(0); // draw the triangle prog.bind(); // glUseProgram(shader_program); vao.bind(); // glBindVertexArray(vertex_array_object); glDrawArrays(GL_TRIANGLES, 0, 3); vao.release(); // glBindVertexArray(0); prog.release(); // glUseProgram(0); Not so long but textual answer: OpenGL is a state machine, you need to link together: the VBO and how to read its data, inside the VAO. However, IMHO, Qt people have sadly chosen their abstractions poorly: enableAttributeArray and setAttributeBuffer would be clearer as members of the VAO class instead of the prog class.
70,646,188
70,646,228
Why does it display the sum if numbers aren't between the 2 values?
I want it to not display the result of the sum if the numbers are lower or equal to 1 or 1000. I don't know if using if is the best way, but that's what I tried using, and I don't really understand why it doesn't work. I also tried writing conditions with || and &&, but those don't work either. #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int sum; int a, b, c; int main() { cin >> a; cin >> b; cin >> c; sum = a + b + c; if ( 1 <= a, b, c <= 1000) { //also tried ( 1 <= a || b || c <= 100) and ( a, b, c >= 1 && a, b, c <= 1000) cout<< sum; } else { cout<< "can't calculate"; } return 0; }
The expression in this if statement if ( 1 <= a, b, c <= 1000) is an expression with the comma operator. It is equivalent to if ( ( 1 <= a ), ( b ), ( c <= 1000 ) ) and the value of the expression is the value of its last operand. That is this if statement is equivalent to if ( ( c <= 1000 ) ) It seems you mean if ( 1 <= a && a <= 1000 && 1 <= b && b <= 1000 && 1 <= c && c <= 1000 ) { std::cout << a + b + c << '\n'; } Pay attention to that there is no sense to calculate the sum sum = a + b + c; before the checking the values of the variables a, b and c in the if statement.
70,646,201
70,646,252
What does array index operator do on an object if not overloaded?
I'm writting Matrix class and got to the point where I need to create an array of Array objects, but Array can't have constructor with no arguments ( it need m argument to allocate memory for it ). I searched and haven't found the solution, people only sugest doing it with Vector object, but I am not allowed to do it with anything other than arrays. Then a friend sent me the constructor for matrix that works for them, but even they don't know why it works. Matrix::Matrix(int n, int m):n(n),m(m) { srand(time(0)); this->data=new Array(n); for(int i=0; i<n; i++){ this->data[i].m=this->m; this->data[i].data=new int[m]; for(int j=0; j<this->m; j++){ this->data[i].data[j]= rand()%10; } } } I don't get how this this->data[i] is defined? [] operator isn't overloaded anywhere and data is only a single Array object not an array of Array-s. So why and how is this working and not an compile error? Source files: Header: #define ROK04_ROK04_H class Array{ protected: int* data; int m; public: Array(int m); Array& operator = (const Array& a); virtual ~Array(); Array& operator+=(const Array& a); virtual void setElem(int pos, int value); virtual void print() const; friend class Matrix; }; class Matrix{ protected: Array* data; int n; int m; public: Matrix(int n, int m); }; #endif //ROK04_ROK04_H ``` #ifndef ROK04_ROK04_H #define ROK04_ROK04_H class Array{ protected: int* data; int m; public: Array(int m); Array& operator = (const Array& a); virtual ~Array(); Array& operator+=(const Array& a); virtual void setElem(int pos, int value); virtual void stampa() const; friend class Matrix; }; class Matrix{ protected: Array* data; int n; int m; public: Matrix(int n, int m); void stampaj(); }; #endif //ROK04_ROK04_H Cpp: #include <iostream> #include <ctime> #include "rok04.h" using namespace std; Array::Array(int m):m(m),data( new int[m]() ){} Array& Array::operator=(const Array& a) { cout << "Usao" << this << endl; for(int i = 0; i < m; i++){ data[i] = a.data[i]; } return *this; } Array::~Array() { delete[] data; } void Array::setElem(int pos, int value) { try { if(pos >= m){ cout << "Usao\n"; throw out_of_range("Index out of bounds!"); } data[pos] = value; } catch (out_of_range& oor){ cerr << oor.what() << endl; } } void Array::print() const { // cout << m; for (int i = 0; i < m; ++i) { cout << data[i] << " "; } cout << endl; } Array &Array::operator+=(const Array& a) { int* temp = new int(m+a.m); for(int i = 0; i < m; i++){ temp[i] = data[i]; } for (int i = m; i < m+a.m; ++i) { temp[i] = a.data[i-m]; } delete[] data; data = temp; m = m+a.m; return *this; } Matrix::Matrix(int n, int m):n(n),m(m) { srand(time(0)); this->data=new Array(n); for(int i=0; i<n; i++){ this->data[i].m=this->m; this->data[i].data=new int[m]; for(int j=0; j<this->m; j++){ this->data[i].data[j]= rand()%10; } } }
You have this definition: int* data. So by default, given a pointer operand, data[x] is translated into *(data + x) by the C++ compiler.
70,646,265
70,655,931
OpenACC: How to force copy data from host to device even if already present?
I am trying to build some time metrics for an OpenACC code. One of the most time consuming tasks is copying a big array from the host to the device. I am running the same code multiple times in order to take an average and get a more accurate value. However, I ran into the problem that this big array is only copied once, therefore in all the subsequent runs of the code, the copying time is not taken into consideration. I must be missing something here, but I thought that when we are working with 'structured data directives' the memory only exists within the data region. However, judging from my time measurements, this doesn't seem to be case. More insight on what is actually happening here would be greatly appreciated. This is how the code looks like: (data is the big array that I want to explicitly copy into the device each time this is run) #pragma acc data copyin(data[0:N*4]) create(grid[0:n*n], cell_ij) copyout(grid[0:n*n]) { // ... } I am compiling with: pgc++ -lstdc++ -O2 -Wall -std=c++11 -acc -ta=nvidia -Minfo=accel The compiler tells me: Generating copyin(data[:262144]) [if not already present] How do I get rid of the [if not already present]? Like copy it anyways?
Assuming that these variables are not in another data region, they wouldn't be present so would be copied. But if you want to be sure, you can use "create" in the data region and then use the "update" directive to explicitly copy the arrays. #pragma acc data create(data[0:N*4], grid[0:n*n], cell_ij) { #pragma acc update device(data[0:N*4]) // ... #pragma acc update self(grid[0:n*n]) }
70,646,384
70,646,572
Call a function that takes in a pointer to the current class from inside the class
I am trying to call a method outside of the Entity class that takes in an entity pointer as a parameter, and I am getting this compiler error: C3861: 'PrintEntity': Identifier not found My code looks like this: #include <iostream> class Entity { public: int x, y; Entity() { this->x = 0; this->y = 0; } Entity(int x, int y) { this->x = x; this->y = y; PrintEntity(this); } int GetX() const { const Entity* e = this; } }; void PrintEntity(Entity* e) { std::cout << e->x << ", " << e->y << std::endl; } int main() { Entity e(5, 5); } (This isn't practical code, but more of a proof-of-concept exercise) I understand that this error is occurring because I have not defined a prototype for PrintEntity, and so the Entity class does not recognize the PrintEntity() function when it is called in the Entity constructor, but when I define a prototype just before the Entity class declaration like this: void PrintEntity(Entity* e); class Entity { ... } I get these 5 errors: C2182: 'PrintEntity': illegal use of type 'void' C2065: 'Entity': undeclared identifier C2065: 'e': undeclared identifier C2064: term does not evaluate to a function taking 1 arguments C2365: 'PrintEntity': redefinition; previous definition was 'data variable' My understanding of why these errors are occurring is that the PrintEntity() prototype does not recognize the Entity class, as it has not been defined yet. So if I cannot write the prototype before the class definition because Entity has not been defined, and I cannot call the PrintEntity() method without prototyping it, how can I make this code work while still being able to call PrintEntity() inside of the Entity class?
One solution is to forward declare Entity and PrintEntity before the class definition and implement PrintEntity after the class definition: class Entity; void PrintEntity(Entity*); class Entity { // ... }; void PrintEntity(Entity* e) { std::cout << e->x << ", " << e->y << std::endl; } Demo (Note that GetX doesn't return an int as it promised to do. That must be fixed) It does look like you would be better off creating a header file with a class definition without member function implementations though. You should move those to a .cpp file instead.
70,646,389
70,646,481
is it safe to call delete inside a remove_if predicate?
I have a vector std::vector<Object*> objects; And a method that removes an object if it's found: void Remove(Object *o) { objects.erase( std::remove_if( objects.begin(), objects.end(), [&o](Object *_object) { if (o == _object) { delete _object; return true; } return false; } ), objects.end() ); } Is this safe? Should I not call delete? But then would erase call delete for me? I'm a bit confused. Would this invalidate the iterator or leak memory?
Would this invalidate the iterator or leak memory? Memory doesn't get leaked by individual bits of code; it gets leaked by complete programs. Someone has to be responsible for deallocation, but just because it doesn't happen here, doesn't mean it won't happen at all. Not calling delete here would also not "leak memory"; what leaks memory is the entire program. Code like this cannot stand on its own. It's difficult to figure out where the responsibility lies, except by following established patterns. That's why tools like std::unique_ptr<T>, std::shared_ptr<T> and std::weak_ptr<T> exist. Please use them. The iterator will not be invalidated. The iterator is iterating over elements of the container, which are the pointers themselves. delete does not affect the pointers it's used with. delete affects the pointed-at memory. Would erase call delete for me? No. Is this safe? Code like this risks a double deallocation (undefined behaviour) if any other code could possibly attempt to delete any of the same pointed-at elements from the container. Again, this is not a local risk, it is a whole-program risk. Again, figuring out memory management across a whole-program context is difficult in general. Please use standard library tools like std::unique_ptr<T>, std::shared_ptr<T> and std::weak_ptr<T>, as appropriate to the situation, in appropriate ways. A proper tutorial on memory management in C++ is beyond the scope of a Stack Overflow question.
70,646,523
70,648,797
How to check whether two array or list are identical?
In python, one can easily determine whether arr1 is identical to arr2, for example: [1,2,3] == [1,2,3] {1,2,3} == {3,1,2} (1,2,3) == (1,2,3) How do you do this in C++? //#include <bits/stdc++.h> using namespace std; int main() { // if ({1, 2}== {1, 2}) // cout<<" {1, 2}== {1, 2}"; if ((1, 2)== (2, 2)) cout<<" (1, 2)== (1, 2) equal"; } if ({1, 2}== {1, 2}) cout<<" {1, 2}== {1, 2}"; throws an error error: expected primary-expression before ‘{’ token, however, if ((1, 2)== (2, 2)) cout<<" (1, 2)== (1, 2) equal"; gives unexpected result, it thinks (1, 2) and (2, 2) are the same. Do I have to convert list to vector do the comparison in C++, like below? #include <iostream> #include <vector> using namespace std; int main() { if (vector<int>({1, 2})== vector<int>({1, 2})) cout<<" vector<int>({1, 2})== vector<int>({1, 2}"; } So what are the data type of (1,2) and {1,2} in C++?
In python, one can easily determine whether arr1 is identical to arr2, for example: [1,2,3] == [1,2,3] In Python the square brackets are enough to denote a list. In C++, which a statically typed language, you can't do this. You have to declare the arrays or vectors using their types: std::vector<int> vec1 = {1, 2, 3}; std::vector<int> vec2 = {1, 2, 3}; As explained in the other answers, on it's own {1, 2, 3} is a braced initialization list, not an array or vector. In C++, arrays and vectors do not have value semantics. You can't compare them like you would two integers using ==. Instead you would have to use a function, such as std::equal, from the standard library to compare the two: std::equal(std::begin(vec1), std::end(vec1), std::begin(vec2), std::end(vec2)) which internally compares each element in the two vectors one by one. Of course, this is more long winded than in Python but under the hood Python is doing the same thing. Alternatively, you can use std::array, which is a container that encapsulates fixed size arrays and that does have an operator ==: std::array<int, 3>{1,2,3} == std::array<int, 3>{1,2,3} For sets: {1,2,3} == {3,1,2} and tuples: (1,2,3) == (1,2,3) you can use the == operator like so: std::set<int>{ 1, 2, 3 } == std::set<int>{3, 1, 2} std::make_tuple( 1, 2, 3 ) == std::make_tuple(3, 1, 2) but you have to explicitly create the sets and tuples first unlike Python, which infers from the brackets what you want to create. Demo
70,647,024
70,649,680
Qt GUI hanging with worker in a QThread
I have a worker which needs to complete an arbitrary blocking task class Worker : public QObject { Q_OBJECT; public: using QObject::QObject; public slots: void start() { for (int i = 0; i < 10; i++) { qDebug("I'm doing work..."); Sleep(1000); } } }; In my MainWindow constructor, I start the task like so: class MainWindow : public QWidget { Q_OBJECT; public: explicit MainWindow(QWidget* parent = nullptr) : QWidget(parent) { QThread* t = new QThread(this); Worker* w = new Worker(this); w->moveToThread(t); this->connect( t, &QThread::started, w, &Worker::start ); this->connect( t, &QThread::finished, t, &QThread::deleteLater ); t->start(); } }; And my entry point: int main(int argc, char** argv) { QApplication app(argc, argv); MainWindow mainWindow{}; mainWindow.show(); return app.exec(); } When I run the program, I just get a spinning mouse circle, and the window contents don't load until 10 seconds later (when the worker is complete). Why is this so? What do I need to do so that Worker::start is run in the background without affecting the GUI? P.S. I am using Qt 6.2.2 and Windows 11, but I highly doubt that has anything to do with this issue.
The problem is that the worker is actually not moved to thread (Isn't a warning written to console? I bet it is.), because its parent, i.e. MainWindow instance is still in the GUI thread. When moving to thread, you can only move the whole hierarchy of objects by moving the very top parent. You cannot have parent in different thread than its children. You should create the worker without parent. Worker* w = new Worker(); Of course you should also add some finished() signal to your Worker class. class Worker : public QObject { Q_OBJECT; public: using QObject::QObject; void start() { for (int i = 0; i < 10; i++) { qDebug("I'm doing work..."); Sleep(1000); } emit finished(); } signals: void finished(); }; and add these connections: this->connect( w, &Worker::finished, t, &QThread::quit ); this->connect( t, &QThread::finished, w, &Worker::deleteLater ); otherwise your thread's even loop will not end and the worker will not be deleted.
70,647,429
70,648,147
Makefile Selecting type of compilation
How can I make it so that I can use the commands like make debug or make release, such that they both invoke the set of rules below but with different compilation flags (e.g. -g for debug and -DNDEBUG for release)? # Object Files OBJECTS := $(addprefix $(BUILDDIR)/,$(SOURCEFILES:.cpp=.o)) compile: $(OUTPUT) $(MAIN) $(OUTPUT): @mkdir $(BUILDDIR) $(MAIN): $(OBJECTS) @$(CXX) $(CXXFLAGS) $(INCLUDES) $(LIBS) -o $(OUTPUTMAIN) $(OBJECTS) $(BUILDDIR)/%.o: %.cpp @$(CXX) $(CXXFLAGS) $(INCLUDES) -c $< -o $@ .PHONY: debug release debug: ... Compile with debug flags ... release: ... Compile with release flags ...
It's not difficult, just use target-specific variable values: debug: CXXFLAGS += -g -whatever release: CXXFLAGS += -DNDEBUG -otherstuff debug release: $(OBJECTS) link things... But there's a problem with your design. You build an object foo.o with either the debug flags or the release flags, but either way you name it foo.o and put it in the same build directory. So later on, when you build, say release, and there's a foo.o already there, Make will happily use it. See the problem? I suggest you have two build directories, one for debug and one for release; there are other ways, but you must decide before you tinker with the makefile.
70,647,441
70,647,627
How to determine the offset of an element of a tuple at compile time?
I need to determine the offset of a certain indexed element of a tuple at compile time. I tried this function, copied from https://stackoverflow.com/a/55071840/225186 (near the end), template <std::size_t I, typename Tuple> constexpr std::ptrdiff_t element_offset() { Tuple p; return (char*)(&std::get<I>(*static_cast<Tuple *>(&p))) - (char*)(static_cast<Tuple*>(&p)) ; } including variants in which I eliminate p and replace &p by nullptr. This function seems to work well at runtime but I cannot evaluate it at compile time. https://godbolt.org/z/MzGxfT1cc int main() { using Tuple = std::tuple<int, double, int, char, short, long double>; constexpr std::size_t index = 3; constexpr std::ptrdiff_t offset = element_offset<index, Tuple>(); // ERROR HERE, cannot evaluate constexpr context Tuple t; assert(( reinterpret_cast<char*>(&t) + offset == reinterpret_cast<char*>(&std::get<index>(t)) )); // OK, when compiles (without "constexpr" offset) } I understand this is probably because the reinterpret_casts cannot be done at compile time. But so far it is basically the only function that proved to work (at runtime). Is there a way to rewrite this function in a way that can be evaluated at compile type? I also tried these approached list at the beginning of https://stackoverflow.com/a/55071840/225186, but they all give garbage results (at least in GCC) because they assume a certain ordering of the tuple elements and the offset are calculated by "walking" index by index and aligning bytes.
You can use this: template <std::size_t I, typename Tuple> constexpr std::size_t element_offset() { using element_t = std::tuple_element_t<I, Tuple>; static_assert(!std::is_reference_v<element_t>); union { char a[sizeof(Tuple)]; Tuple t{}; }; auto* p = std::addressof(std::get<I>(t)); t.~Tuple(); std::size_t off = 0; for (std::size_t i = 0;; ++i) { if (static_cast<void*>(a + i) == p) return i; } } Which avoids having to reinterpret_cast to a char pointer, and shouldn't have any undefined behaviour. You can also make this work with tuples that can't be default constructed in a constant expression by not initializing the tuple: template <std::size_t I, typename Tuple> constexpr std::size_t element_offset() { using element_t = std::tuple_element_t<I, Tuple>; static_assert(!std::is_reference_v<element_t>); union u { constexpr u() : a{} {} // GCC bug needs a constructor definition char a[sizeof(Tuple)]{}; Tuple t; } x; auto* p = std::addressof(std::get<I>(x.t)); std::size_t off = 0; for (std::size_t i = 0;; ++i) { if (static_cast<void*>(x.a + i) == p) return i; } } While this works in gcc, clang, and msvc today, it might not in the future.
70,647,584
70,647,882
C++ class function pointer
I have a request for function pointer by C++. below is the sample what I need: in API file: class MyClass { public: void function1(); void function2(); void function3(); void function4(); }; in main file: MyClass globalglass; void global_function_call(???)// <---- how to do declaration of argument??? { //Do *function } int main() { global_function_call(&globalglass.function1()); // <---- pseudocode, I need to use global class global_function_call(&globalglass.function2()); global_function_call(&globalglass.function3()); global_function_call(&globalglass.function4()); return 1; } I have no idea to do declaration...
To do what you are asking for, you can use a pointer-to-member-method, eg: MyClass globalglass; void global_function_call(void (MyClass::*method)()) { (globalglass.*method)(); } int main() { global_function_call(&MyClass::function1); global_function_call(&MyClass::function2); global_function_call(&MyClass::function3); global_function_call(&MyClass::function4); return 1; } Online Demo
70,647,706
70,647,822
Exporting an inline struct in c++
I was programming in c++ and I came across an issue. I had a struct for the player in a header file and wanted to use the struct in two different files. struct { float x; float y; } player; I tried many things and I did much research but it always resulted in errors or the variables not updating throughout all the files. However I made a discovery, you can use inline struct EXPORT { float x; float y; } player; (c++17) Ive looked online and I cant find anyone talking about this, ive even searched "inline struct EXPORT" on github and no code results came up. I wonder if ive made a discovery. I am wondering if this is a known syntax and if it is a good idea to use such a function.
am wondering if this is a known syntax Yes. The syntax of variable and class definition is known. In this case, you define an inline variable named player which is of a class type named EXPORT. There is no "exporting" involved here.
70,647,738
70,654,396
How does QIODevice::readLine(qint64 maxSize = 0) works?
The documentation of this method states: QByteArray QIODevice::readLine(qint64 maxSize = 0) This is an overloaded function. Reads a line from the device, but no more than maxSize characters, and returns the result as a byte array. However, I notice that even if we pass maxSize = 0, viz. don't pass anything, the readLine() sends several bytes in the line. Is this a well defined behaviour? Besides, here is one decade old issue on the same topic: QIODevice::readLine(qint64 maxSize = 0) default argument performs poorly (should be documented). Is this still relevant?
It's not mentioned in the Qt API documentation, but passing in a value of 0 as the maxSize argument is treated as having a special meaning of "as many bytes as possible". Evidence of that intent can be seen at line 1466 of the qiodevice.cpp source file in Qt: if (maxSize == 0) maxSize = MaxByteArraySize - 1;
70,649,326
70,649,393
generateKey cpp function
Hello i have a problem with one of my functions generateKey() that returns char*. Its generate the key normal but when i print it i can see something weird. char* aesStartup::generateKey() { const char alphanum[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; char newKey[32]; srand(time(0)); for (int i = 0; i < 32; i++) newKey[i] = alphanum[rand() % 62]; cout << newKey; return newKey; } output: u6gWj8dBHxJhEztsHXfE5V3HSvZ2zVNb╠╠╠╠╠╠╠╠0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ can someone help me?
You have two serious problems: First of all you seem to have forgotten that strings in C++ are really called null-terminated strings. For an array of characters to be a "string" it needs to be terminated with the '\0' character. Which also means a 32-character string needs to have 33 elements. The second problem is that you return a pointer to local data. Once the function generateKey returns, the life-time of all local variables ends, and pointer to them will become invalid. You can solve both problems very easily: Stop using character arrays for strings, and start using the C++ standard std::string class for all your strings. On another note, you should only call srand once in your program. And C++ have much better functions and classes for generating random numbers than the C compatibility functions srand and rand.
70,649,378
70,649,575
How do I suppress deprecation warnings for function parameters?
I previously used such pragmas, which I seem to recall worked both with GCC (ubuntu) and clang (macos). They seem to be effective to suppress warning from header #includes. // test.cpp struct [[deprecated]] Foo {}; #pragma clang push #pragma clang ignored "-Wdeprecated-declarations" int main() { auto foo_fun = [](const Foo &f) {}; foo_fun(Foo()); } #pragma clang pop However, it does not seem to work when the deprecated type occurs as a lambda or plain function parameter, when compiled with clang -std=c++14 -o wat test.cpp. The compiler version is Apple clang version 12.0.0 (clang-1200.0.32.29) What do I do to suppress deprecation warning in these contexts?
You are missing a diagnostic keyword in your pragma declarations: #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" ... #pragma clang diagnostic pop
70,649,490
70,649,622
I have a variable b in parent class and when i try to access variable b from sum3 class it shows ambiguous b error
I have a variable b in the parent class and when I try to access variable b from sum3 class it shows an ambiguous b error. And if I remove the sum from inheritance it will give "clas.cpp|25|error: 'int sum::b' is inaccessible within this context| " error what to do? #include<iostream> using namespace std; class sum { public: int b=8; }; class sum2:sum { public: int c=4; }; class sum3:sum2,sum { public: int h=9; void add() { int l; l=h+c+b; cout<<l; } }; int main() { sum3 c; c.add(); }
this is because you are inheriting from both sum2 and sum classes but sum2 is inheriting from sum so it inherits the variable b also so when you intend to use the variable b inside of the class sum3 the compiler doesn't know which variable you want because there is one in class sum2 and one in class sum with the same name b. one of the solutions to this is to use the scope resolution operator inside of the class sum3 like this: class sum3:sum2,sum { public: int h=9; void add() { int l; l=h+c+sum2::b; cout<<l; } }; this removes the ambiguity by telling the compiler which variable I intend to use and in this case it's sum2 variable. Note that: this is called the diamond problem and it occurs in multiple inheritance situations if you want to read further and to know how to avoid them you can use this link: How can I avoid the Diamond of Death when using multiple inheritance?
70,649,825
70,661,182
Topological Sorting using Kahn's Algorithm
I wanted to know ,what does the following part of code mean , I understood the whole function but the for loop at the end is making me confused and not able to understand. So please tell me what it is doing there? void topologicalSort(vector<int> adj[], int V) { vector<int> in_degree(V, 0); for (int u = 0; u < V; u++) { for (int x:adj[u]) in_degree[x]++; } queue<int> q; for (int i = 0; i < V; i++) if (in_degree[i] == 0) q.push(i); while (!q.empty()) { int u = q.front(); q.pop(); cout<<u<<" "; for (int x: adj[u]) if (--in_degree[x] == 0) q.push(x); } } This the link to whole code https://ide.geeksforgeeks.org/PSNw3VplJL
Kahn's algoritm (which has nothing to do with BFS): Find all the vertexes with in-degree 0 and put them in a queue (q in your code). Pick a vertex from the queue, output it, and delete it from the graph. Deleting the vertex will reduce the in-degree of all its neighbors. Some of these could reach in-degree 0 -- put those ones in the queue. Go back to 2 until you're out of vertexes. That last for loop does step (3).
70,650,470
70,651,141
How to avoid shared pointers in C++ caused by try/catch?
I use shared pointers because of variable can only live in block where it was created. int main(void) { std::shared_ptr<project::log::Log> log; try { log = make_shared<annmu::log::Log>("error.log"); // can throw eception } catch(std::exception &e) { std::cout << "Error\n\n"; return 0; } } I would like to avoid shared pointers and created code more simple. Something like following code (not working code). int main(void) { project::log::Log log; // can throw eception try { log = project::log::Log("error.log"); // can throw eception } catch(std::exception &e) { std::cout << "Error\n\n"; return 0; } } Is it good way to avoid shared pointers? Is it more efficient solution? In second solution the object is created two times. Thank you for you answer.
It is always good practice to avoid using shared pointers, unless you are actually sharing the pointer. You could use a unique_ptr as a drop in replacement. It is not a bad idea to have a non-throwing constructor, which constructs the object into a valid-empty state. Handling exceptions in construction is always more complex than handling an exception during an operation. Complex solutions require more brain-power, and brain-power is a scarce resource in large programs So in general, I think everything you say is right. I like to think of objects as having 6 distinct stages. Allocation Construction Initialisation Active // Do useful functions, etc Destruction Deallocation For simple objects reducing this to just construction/destruction is just convenient, and reduces how much you have to think about. For heavy-weight objects it makes sense to separate out each stage and make them separately testable. You get better error handling and error reporting this way (IMHO)