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
71,548,000
71,548,039
ostream << operator not getting invoked
I have created a class Animal with some basic properties and added a no data constructor. I have overloaded the ostream operator as well to print the properties. Animal.cpp #include<bits/stdc++.h> using namespace std; class Animal { string name; int action; public: Animal() { name = "dog"; ...
The 2nd parameter of operator<< is declared as Animal &; Animal() is a temporary and can't be bound to lvalue-reference to non-const. You can change the type to const Animal &; temporary could be bound to lvalue-reference to const. (Then write needs to marked as const too.) class Animal { string name; int actio...
71,548,291
71,548,379
Forward CMake BOOL to C++
I want to be able to set a bunch of boolean flags when calling CMake, that are later used in C++ code. Something like: set(DEBUG_ENABLE false CACHE BOOL "enable debugging") target_compile_definitions(target PRIVATE DEBUG_ENABLE=${DEBUG_ENABLE}) This actually works fine and produces something equivalent to: #define DEB...
I'd use configure_file. It won't get you a C++ bool directly, but it's something that will actually scale over time. You'll need to make a config file template for cmake to modify, in this example config.hpp.in. #cmakedefine01 DEBUG_ENABLE Next, add a configure_file line to your CMakeLists.txt. configure_file(config....
71,548,320
71,548,608
How to add a value at some list[x][y] in C++?
I am trying to add some value at cost[x][y] and the list must be a pointer type. I declared the list like this: list<int>* cost = new list<int>[V]; // V being user input And here I'm trying to add the value "c" at the place of cost[x][y]. How am I supposed to add that .When I try to use iterator as below it says "Deb...
The problem is that the lists will be initially empty. So, having 0 elements. So, you can write cost[x] and can get an iterator. That is OK. But, as said, the list is empty. So, if you try to advance the iterator, it will fail. Because, it will be equal to end() in the beginning. And this cannot be advanced. Else, it w...
71,548,740
71,549,138
Using Boost Beast to build Platform specific client-side authentication in SSL connection
I’m working on boost::beast based application on macOS platform, and I wonder how I can provide a client-side certificate to authenticate against the server ? basically , in macOS the certificates are stored in keychain, and cannot be exported (backed by dedicated hardware called secured-enclave for better security)… S...
See set_verify_callback There are examples here: asio/example/cpp11/ssl/client.cpp asio/example/cpp03/ssl/client.cpp You can see it integrated in Beast's ssl_stream: https://www.boost.org/doc/libs/1_78_0/libs/beast/doc/html/beast/ref/boost__beast__ssl_stream/set_verify_callback/overload2.html
71,548,837
71,548,999
function to print min and max value of an array using c++ pointers
I'm trying to understand pointers in c++ so I made a function that takes an array and the length of that array and print out the min and max values of that array, however, it always just print the last element in that array for both min and max, I went through my code line by line but I still don't understand the reaso...
Since, you are using the de-referencing operator in the if condition. You are basically changing the value at the memory location where the pointer is pointing (in this case the 0th index of the array). What you should do in the if condition is store the index where the minimum and maximum values are present. Like so i...
71,549,394
71,550,087
C++ access callback data
I am attempting to create a wrapper around class functions. The purpose of my wrapper is to test input, output, and enforce order of operations with various calls throughout my program. I am trying to not make any changes to the callee class. Attached is an example of what I am trying to achieve, but unable to figure o...
@JohnFilleau had mentioned to pass the class object instead of the function from within the class. The following is the solution based on example code that he provided, and I modified to work with the example. I realize the question is confusing but would like to thank both JohnFilleau and Taekahn for the discussion. I...
71,549,789
71,549,848
Inbuilt / pre-defined comparator in cpp
Recently I learnt about comparators in cpp from STL. I came to know we can use greater<>() as third argument for sorting instead of writing own logic. Just curious to know how many inbuilt comparators are there in cpp.
The standard library defines pretty much what you would expect as analogues to the built-in operators: std::equal_to // == std::not_equal_to // != std::less // < std::less_equal // <= std::greater // > std::greater_equal // >= Since C++20 also constrained versions of all these comparison functi...
71,549,797
71,550,159
How to use IDirect3D9 functions
I am trying to use the function GetAdapterIdentifier but for some reason I keep on getting an error g++ main.cpp -ld3d9 -ld3dcompiler -lgdi32 -static -static-libstdc++ -o output main.cpp: In function 'int main()': main.cpp:22:59: error: cannot call member function 'virtual HRESULT IDirect3D9::GetAdapterIdentifier(UINT,...
Found this blog that helped me get to this answer #include <iostream> #include <d3d9.h> #include <D3D9Types.h> #include <tchar.h> #include <string.h> LPDIRECT3D9 g_pDirect3D = NULL; LPDIRECT3DDEVICE9 g_pDirect3D_Device = NULL; int main(void) { UINT x = 0; // Ordinal number that denotes the display adapter....
71,550,127
71,550,215
What is the purpose of d-char-sequence in C++ raw strings?
On this reference: https://en.cppreference.com/w/cpp/language/string_literal, raw string is defined as: prefix(optional) R"d-char-sequence(optional)(r-char-sequence(optional))d-char-sequence(optional)" Example: const char* s1 = R"foo( Hello World )foo"; What is the purpose of the d-char-sequence ("foo" in the exam...
The optional d-char-sequence is used to define the end marker of the raw string. For example, if the raw string contains the substring )", then the line: const char* s = R"(string with )" inside)"; will raise a syntax error. This can be fixed by using the optional d-char-sequence that is not met inside the raw string: ...
71,550,243
71,550,297
My helper function is returning an empty string
I'm writing some code for a game, and I'm attempting to write a helper function to return a string inside an object: const char* getGhostName(GhostAI* ghostAI) { if (ghostAI) { GhostInfo* ghostInfo = getGhostInfo(ghostAI); const auto ghostName = ghostInfo->fields.u0A6Du0A67u0A74u0A71u0A71u0A66u0A65u...
il2cppi_to_string() returns a temporary std::string, which will be destroyed at the end of the expression that calls il2cppi_to_string(). You are obtaining a const char* pointer to the data of that temporary std::string, which is what ReSharper is warning you about. Since the temporary std::string is destroyed before t...
71,550,602
71,550,671
No matching function call error when the functions are actually being called
I am currently doing a project for school and for some reason, g++ won't compile my code properly, saying: Rectangle.cpp: In constructor ‘Rectangle::Rectangle()’: Rectangle.cpp:8:22: error: no matching function for call to ‘Line::Line()’ Rectangle::Rectangle(){ ^ In file included from Rectangle.h...
You are trying to default construct two Lines (width and length) in the Rectangle constructor. Since Line doesn't have a default constructor you need to use the member initializer list: Rectangle::Rectangle() : // colon starts the member initializer list width(Point(0,4), Point(0,0)), length(Point(0,0), Point(...
71,550,695
71,552,097
Undefined identifier and unresolved external errors C++ Visual Studio 2022
This is basically two errors in one, that seem to come from the same thing. If I define my functions in my main.cpp file, and forward declare them at the top of the file, it doesn't give me any errors and everything runs smoothly. When trying to declutter and move things into seperate .cpp files, it starts to give me l...
The issue mentioned by WhozCraig is very useful, I hope you will read it carefully. Regarding your question, after I modified some code, the program can run correctly. The error is caused by the template. Since you are a beginner and the program is not very complicated, the following code is more convenient for you to ...
71,550,798
71,551,013
How to add the Github "BigFloat" library to my c++ project
(Sorry if this question is glaringly obvious or poorly written as I am fairly inexperienced to any form of coding and this website) I've been trying to include a library called "Big float" from github to my project as it needs to calculate very large numbers with high precision but my compiler doesn't recognise the lib...
The library you are referring to appears to consist of source code only. This means you need to compile it yourself. Just add the "BigFloat.cc" and "BigFloat.h" files to your project. Then, in your own code, write #include "BigFloat.h" to get access to the BigFloat class.
71,551,071
71,551,430
Deduce complete type of parent from one of its template parameters
I want to get the typename of the parent that has a specific template parameter(key). For example, if I have a parent MyParent<int, 1>, I want to be able to get that type(MyParent<int, 1>) from my child with just '1'. If I have MyParent<float,2> I want to be able to get that type(MyParent<float, 2>) with just '2'. Basi...
To avoid having to write a using declaration for the members of each of the parent classes, you can write a variadic class template wrapper that exposes this member for all of the types (as in the Overloader pattern shown here) template<typename... Ts> struct Bases : Ts... { using Ts::GetType...; }; And now your ...
71,551,116
71,551,979
OpenSSL 3 Diffie-Hellman Key Exchange C++
Before OpenSSL3 this was simple. DH* dh = DH_new(); /* Parameters */ dh->p = BN_bin2bn(bin_p, bin_p_size, NULL); dh->g = BN_bin2bn(bin_g, bin_g_size, NULL); /* Private key generation */ BN_hex2bn(&dh->priv_key, hex_priv_key); /* Public key generation */ DH_generate_key(dh); /* Derive */ int shared_key_size = DH_com...
You have to create an EVP_PKEY with domain parameters first if you use custom prime and generator. // Create the OSSL_PARAM_BLD. OSSL_PARAM_BLD* paramBuild = OSSL_PARAM_BLD_new(); if (!paramBuild) { // report the error } // Set the prime and generator. if (!OSSL_PARAM_BLD_push_BN(paramBuild, OSSL_PKEY_PARAM_FFC_P, pr...
71,551,522
71,551,804
Is every "complete" object a "most-derived" object?
Per [intro.object]/2: [..] An object that is not a subobject of any other object is called a complete object [..]. So consider this snippet of code: struct Base {}; struct Derived : Base {}; struct MostDerived : Derived {}; I can't understand the wording in this quote from the standard: [object.intro]/6: If a compl...
Per the question "What does the "most derived object" mean?" I think that (correct me if I am wrong), objects of type "most-derived" class only, like MostDerived, are called "most-derived" objects. Does this true?. "Most derived class" is supposed to be dependent on the object under consideration. It is not a propert...
71,551,631
71,551,668
Im having a code error, while doing a code for a circular link list
Im having a problem finding the solution on my code, it was running okay, but while I as editing the main to Run the code, something might have change. so now I'm having this error on my code that says: this' argument to member function 'isEmpty' has type 'const CircularLinkedList', but function is not marked const Thi...
The error is self-explanatory: in your CircularLinkedList<T>::CircularLinkedList copy constructor, the parameter is marked const. You can only use its method that are defined as const. So change your isEmpty definition to something like bool isEmpty() const {...} After all, checking if the list is empty should not mod...
71,552,052
71,552,118
What is good approach to declare object being used globally? c++
I know that global/extern variables are bad, still not sure why exactly though. But some cases, I can't figure out how to deal with this problem without using extern. For example, in the server application I'm developing, I need every class, every source file to access list of all client objects. So that I can sending ...
Singleton can help. There is a simple example: static MemPool *MemPool::getMemPool() { static MemPool g_mempool = MemPool(/***...***/); return &g_mempool; } Memory *MemPool::allocMemFromPool(const size_t &size) { //... } auto data = getMemPool()->allocMemFromPool(1024);
71,552,170
71,552,203
C++ call functions internally
I'm working with following code which gives access to low level monitor configuration using Windows APIs https://github.com/scottaxcell/winddcutil/blob/main/winddcutil/winddcutil.cpp And I would like to create a new function that increases or decreases the brightness, I was able to do this using Powershell but since th...
you need to add a needed option here line 164 std::unordered_map<std::string,std::function<int(std::vector<std::string>)>> commands { { "help", printUsage }, { "detect", detect}, { "capabilities", capabilities }, { "getvcp", getVcp }, { "setvcp", setVcp}, {"increasebr...
71,552,258
71,552,295
request for member ‘nickname’ in ‘a’, which is of non-class type ‘Author [1000]’
#include <iostream> using namespace std; struct Author { int id ; string fullname; string nickname; int age ; }; struct Book { int id ; string title; int year; float price ; }; void menu (){ cout << "Add New Author (1) \n" ; cout << "Display Author List (2)\n " ; cout << "Add New Book (3) \n" ; cout << "Disp...
The problem you're facing is just the order of operations you're performing. a is an array of Authors, nickname is the member variable you're trying to access. you first need to decide which array entry you want to select by using a[j], then afterwards access the member variable 'nickname' by appending .nickname. this ...
71,552,539
71,552,577
How to create a Discord bot in C++ 98 with platform toolset version v120?
I'm working on a C++ 98 project with platform toolset version v120 on VS 2013. I'm trying to implement Discord bot API in my project. I've tried several unofficial Discord libraries for C++, like Sleepy-Discord, DPP, and Discord.CPP. But it seems like none of them are compatible with my project's C++/platform toolset v...
As stated on the Discord Developer Portal, their API can be accessed entirely through web requests. You don't need any additional libraries, except if you want to use a prebuilt REST or WebSocket library for easier use, which - if available to you - i would highly recommend.
71,553,105
71,553,142
Seg fault with default allocation std::set<void*>
I am trying to learn STL allocators for void*. Here is my code #include <set> #include <memory> class Test { public: std::set<void*> GetAllInformation() { return info_set_; } private: std::set<void*> info_set_; }; int main() { std::unique_ptr<Test> test_obj_; const auto info = test_obj_->GetAllInf...
The problem is that currently test_obj_ is not pointing to any Test object. Thus the expression test_obj_->GetAllInformation() leads to undefined behavior. Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on th...
71,553,445
71,553,636
Concatenation of multiple absolute std::filesystem::path instances
Why is the result of concatenating the following paths /c/d? std::filesystem::path{"/a"} / std::filesystem::path{"b"} / std::filesystem::path{"/c/d"} My mental model so far had the resulting path set to /a/b/c/d. To my surprise, it was simply /c/d. Curious to know where I went wrong here. (And what the right mental mo...
/a is an absolute path, and b is a relative path, so concatenating them will produce /a/b. But /c/d is also an absolute path, so concatenating it with anything in front of it is basically a no-op, the absolute path will take priority, so the final result is just /c/d. This is discussed in more detail on cppreference.co...
71,553,666
71,554,186
How to insert pointer in QGraphicsItem so when they get selected pointer will be accessed?
I want to select rectangle/polyline through scene with mouse click and should be able to print it's name and other property. It's name and other properties are in the graph node. But I dont want to interact graph again. So when I was drawing rectangle/polyline through graph co-ordinates, I should be able to store so...
Use Qt's dynamic properties, check QObject::setProperty. It should do the trick. But AFAIC, I would have used a double QMap to associate directly <graph_node, QGraphicsItem> AND <QGraphicsItem, graph_node> - so you can search quickly for both associations, and both in O(log2(n)) complexity. You can store this either as...
71,555,055
71,555,120
Explanation of the C++ template function argument deduction when matching `T const &&t` against `int const *`
I don't understand how the argument deduction rule works in this case. I have the following simple code snippet: template<typename T> void fn(T const &&t) { std::cout << __PRETTY_FUNCTION__ << std::endl; std::cout << typeid(decltype(t)).name() << std::endl; } int main() { int const *ar = nullptr; std::cout...
In the parameter declaration T const &&t, const is qualified on T, i.e. t is declared as an rvalue-reference to const T. When ar with type const int * is passed, T is deduced as const int *, then the type of t would be const int * const &&, i.e. an rvalue-reference to const pointer to const int. Note that the consts ar...
71,555,500
71,555,616
Separate declaration and definition in .h and .cpp but NON-class functions?
I have the practice of writing functions that do not have to be in a class in namespaces, so I would like to know if can separate them in source and headers files: utilities.hpp: namespace nms { static void process(); }; utilities.cpp void nms::process(){/*...*/} But like this I only get an error: main.cpp:(.text...
In the header file utilities.hpp: namespace nms { static void process(); }; static means the function has internal linkage, meaning it declares a unique function for each translation unit in which the header is included. The only translation unit (TU) for which the corresponding unique (internal linkage) process()...
71,556,162
71,556,586
Provide different functionality with subclasses
I don't know if this title is descriptive enough... but I have no idea what else to call it. What I'm trying to do is the following: There is a class (lets call it the AgentClass) that consumes the functionality of some other class (in this example the Initializer). I have different versions of Initializer (like ZeroIn...
Roughly speaking you have two options: Choose at runtime which derived class to use, then you can pass the instance as parameter to the constructor: AgentClass(BaseInit& init) { init.init(data); } Or select at compile time which derived class to use. When it is ok that eg AgentClass<RandomInit> is a different type t...
71,556,814
71,557,402
C++ Is data race big problem in producer/consumer pattern?
I still learning multithread programming with network involved. My question is that when I designed threads as consumer/producer pattern, and producer modify variable randomly, consumer checks variable and do something based on it, would it be still bad(big problem)? Like the code below. int flag = 0; void producer() ...
A data race results in undefined behavior. C++ draft N4860 6.9.2.1 Data races (21.2) The execution of a program contains a data race if it contains two potentially concurrent conflicting actions, at least one of which is not atomic, and neither happens before the other, except for the special case for signal handlers ...
71,556,861
71,557,659
Cast a variable to void pointer in Julia
In C/C++ we are able to do this: double my_var = 4.32; void* my_var_ptr = &my_var; which results in the my_var_ptr being a void pointer pointing to the memory which stores the value 4.32. I am trying to do the same in Julia, but I face several errors. Naively, I tried this: my_var=Cdouble(4.32) my_var_ptr=Ptr{Cvoid}(p...
TL; DR julia> my_var = Cdouble(4.32) julia> my_var_ptr = Ptr{Cvoid}(pointer_from_objref(Ref(my_var))) Ptr{Nothing} @0x00007f2a9148c6c0 pointer only works for array-like elements julia> methods(pointer) # 18 methods for generic function "pointer": [1] pointer(a::Random.UnsafeView) in Random at /usr/share/julia/stdlib/...
71,557,313
71,557,625
for loop not executing on zero parameters
I am a self-taught python & C programmer and Iam now trying to learn C++ As a small exercise, I tried to port a function I had created in a Python minigame of mine, that generates a random matrix, then averages it, to create a map with terrain elevation. I tried implementing it in C++ using a trick with size_t and the ...
You make a call to AverageSurroundings with row==0 and/or col==0 (see your loop variables in Average). But std::size_t is an UNSIGNED type... So when it's zero, minus 1, it underflows in AverageSurroundings's loops and returns 0xFFFF FFFF FFFF FFFF... Which is obviously greater than row+1 (or col+1). So the loop isn't ...
71,557,908
71,558,201
sprintf into char* var[1] fails with Segmentation fault
consider code: using std::cout; using std::cerr; using std::endl; using std::string; using std::vector; // . . . char* envp[10]; vector<string> lines; char* c_line = nullptr; size_t len = 0; while ((getline(&c_line, &len, input_file)) != -1) { string line; lines.push_back(line.as...
I do not recommend mixing std::string and old C-strings in such a wild manner. Instead I'd rely on C++ classes as long as possible: std::ifstream inputFile("path to file"); if(!inputFile) { // error handling } std::vector<std::string> lines; std::string tmp; while(std::getline(inputFile, tmp)) { lines.emplace_...
71,558,090
71,558,091
What language rules governs that `T&&` in a templated array-by-&& function argument is *not* a forwarding reference?
A static analysis tool I'm using prompts me that I need to std::forward the argument of the following function down the call chain: template<typename T, std::size_t size> constexpr void f(T (&& arr)[size]) { /* linter: use std::forward on 'arr' here */ } as it identifies the function parameter type as a forwarding ref...
The relevant section is [temp.deduct.call]/1 [emphasis mine]: Template argument deduction is done by comparing each function template parameter type (call it P) that contains template-parameters that participate in template argument deduction with the type of the corresponding argument of the call (call it A) as descr...
71,558,263
71,559,966
Proper way to perform unsigned<->signed conversion
Context I have a char variable on which I need to apply a transformation (for example, add an offset). The result of the transformation may or may not overflow. I don't really care of the actual value of the variable after the transformation is performed. The only guarantee I want to have is that I must be able to retr...
I know that signed types overflow is undefined behaviour, True, but does not apply here. a += 140; is not signed integer overflow, not UB. That is like a = a + 140; a + 140 does not overflow when a is 8-bit signed char or unsigned char. The issue is what happens when the sum a + 140 is out of char range and assigned...
71,558,576
71,559,078
Why hasn't cppreference got any knowledge points about _Base_bitset when introducing bitsets?
I noticed that in cppreference/bitset, bitset is not mentioned to be inherited from _ Base_bitset , including the following header file. Does the cppreference estimate omit this inheritance relationship? namespace std { template<size_t N> class bitset { public: // bit reference class reference { frien...
The description of std::bitset can be found in the C++ Standard at 22.9 Utilities.bitset. It doesn't mention _Base_bitset or other details, because those are left to the library implementors.
71,558,717
71,558,790
Proper use of template classes
I have an exercise wherein I must use a template class "Garage" that takes as parameters either a "car" or a "bike". Easy enough but I keep getting errors since I obviously don't understand the templates well enough. Is this : template<class Car> class Garage{ Car array[10]; public: void addCar(int counter1); ...
If you had to write out specifically every implementation for each instantiation then there would be no need for templates in the first place. You could name your classes CarGarage and MotorbikeGarage and call it a day. You probably want something along the line of this: template<class VehicleType> class Garage{ Ve...
71,558,802
71,559,812
Vector out of boundaries access: why such behavior?
I am aware that out of boundary access of an std::vector in C++ with the operator[] results in undefined behavior. So, I should not expect anything meaningful doing that. However, I'm curious about what is actually happening there under the hood. Consider the following piece of code: #include <iostream> #include <vecto...
A hypothetical answer that could have happened: The UB caused arbitrary piece of memory to be overwritten. This is called memory corruption. That overwritten arbitrary piece of memory happened to be right before the dynamic memory that the vector allocated. The arbitrary piece of memory right before the allocation happ...
71,560,000
71,562,119
Is there an issue with "cache coherence" on C++ multi-threading on a *Single CPU* (Multi-Core) on Windows?
(EDIT: Just to make it clear: The question of "cache coherence" is in the case that there is no use of atomic variables.) Is it possible (A single CPU case: Windows can run on top of Intel / AMD / Arm CPU), that thread-1 runs on core-1 stores a bool variable (for example) and it stays in L1 cache, and thread-2 runs on ...
CPU cache is always coherent across cores that we run C++ threads across1, whether they're in the same package (a multi-core CPU) and/or spread across sockets with an interconnect. That makes it impossible to load a stale value once the writing thread's store has executed and committed to cache. As part of doing that...
71,560,016
71,560,236
Template specialization not taking place
#include<bits/stdc++.h> using namespace std; template <typename T1, typename T2> inline T1 max (T1 const& a, T2 const& b) { return a < b ? b : a; } template <> inline int max<int,int> (const int& a, const int& b) { return 10; } int main() { cout << max(4,4.2) << endl; cout << max(5,5) << endl; ...
using namespace std; will make all names from the standard library namespace std visible to unqualified name lookup as if they were defined in the global namespace. This includes the function std::max which has an overload of the form template<typename T> const T& max(const T&, const T&); This overload is chosen for y...
71,560,565
71,560,796
Moving unique_ptr inside a lambda function gives me a compiler error on C++17
Given the following hierarchy: class IJobInterface { }; class JobAbstract : public IJobInterface { public: JobAbstract(std::string n) : name(n) {}; protected: std::string name; }; class JobConcrete: public JobAbstract { public: JobConcrete(std::string n, int i) : JobAbstract(n), index(i) {}; void do...
The issue is that lambda's operator () is declared const and with the move you try to modify the unique pointer j. Declare it mutable via auto t = std::thread([j = std::move(job)]() mutable ...) or pass the unique_ptr as an argument to the lambda.
71,560,793
71,561,534
How to use enum from another class and file withouot repetitive scoping? c++
I feel like this is an easy question but I don't seem to find the answer myself. I was wondering if there is a way of using the enum in another file, without having to use scoping? e.g. Head.h namespace h{ class Eye{ enum class State{ closed = 0, blinking, open, staring, rolling // etc. }; void print(const State &...
Don't put a type alias at the top of the namespace unless that's really the logical scope you want. If you just want to save typing in the Body methods you haven't shown, simply namespace h{ class Body{ using State = Eye::State; State eye; State eyesOpen(); }; } will work. It seems odd that the eyes are the only...
71,560,852
71,561,469
How to transform int parameter pack
Given a template template <int... Ints> struct FixedArray; How to implement a meta function that multiplies each integer value by a given number? template <int A, typename F> struct Mul; Mul<2, FixedArray<5, 7, 8>>::type is the same as FixedArray<10, 14, 16>
To do this, you can first define an empty Mul class: template<int A, typename T> struct Mul; Then create a specialization for FixedArray: template<int A, int ... Ints> struct Mul<A, FixedArray<Ints...>> { using type = FixedArray<(Ints * A)...>; }; However, I'd rather have a typedef inside FixedArray, so the resu...
71,561,883
71,562,135
Virtual functions that act like dynamic casts
In JOINT STRIKE FIGHTER AIR VEHICLE C++ CODING STANDARDS Bjarne states, that: Down casting (casting from base to derived class) shall only be allowed through one of the following mechanism: Virtual functions that act like dynamic casts (most likely useful in relatively simple cases) Use of the visitor (or similar) p...
It's referring to a technique that was kind of common in the early days of C++, before dynamic_cast, RTTI, etc., were added to the language. The basic idea looks something like this: class Derived1; class Derived2; class Base { public: virtual Derived1 *toDerived1() const { return nullptr; } virtual Derived2 *...
71,562,522
71,564,515
Constructing a constexpr lambda with member function pointer
I am attempting to build a constexpr lambda that uses a member function pointer as part some type of registration process. The problem is the outermost function that is part of that process is not constexpr which makes the argument (the function pointer) not valid in a constexpr context. Can that createLambda call and ...
If you want to make next statement constexpr auto invokable = createLambda(method); Pass method as non-type template argument template<auto method> auto passthrough() // Function cannot be constexpr { constexpr auto invokable = createLambda(method); // This is not valid, what are my alternatives to make this poss...
71,563,520
71,563,621
literal type in constexpr expression and template parameter
Why do I can use non constexpr literal types in constexpr functions(such as reflection) and it can be returned as constexpr, but I can't use such types in template non-type parameters? class Point { public: constexpr Point(double xVal = 0, double yVal = 0) noexcept : x(xVal), y(yVal) {} ...
constexpr is not a property of a type. It is a specifier on a variable/function declaration. Objects whose lifetime begins within the evaluation of the constant expression are usable in that constant expression and don't need to be declared constexpr. The expression that needs to be a constant expression here is in the...
71,563,779
71,564,088
What are dependent names in C++?
When is a C++ name "dependent"? Apparently it is not dependent when it uses a type-definition in the same scope. It is however dependent, when it uses a type definition in a nested scope of this scope. Consider the following examples: Example A: template <typename T> struct some_struct { struct B { int ...
If I'm reading https://en.cppreference.com/w/cpp/language/dependent_name correctly, both B and B::C are dependent. But B also "refers to the current instantiation", which allows it to be used without typename. It seems to be a fancy way of saying that "whether it's a type can't be affected by specializations". You can ...
71,563,781
71,564,009
How to input commands c++
Hi I'm trying implement commands in a c++ console app The app has a command prompt , basically does nothing until you type a specific command , now the problem is I can't find an efficient way to do this, the only solution I can think of is implementing thousands of if else statements which are not exactly efficient, a...
Have a std::map of string => std::function Like this #include <iostream> #include <map> #include <functional> #include <string> typedef std::function<void(const std::string &)> CmdFunc; void cmda(const std::string &line) { std::cout << "cmda " << line << "\n"; } void cmdb(const std::string& line) { std::cout <<...
71,563,790
71,563,886
Need to store result of cURL http request as a map in C++
I've been using cURL library in C++ to make HTTP requests. When storing the result in a string it works perfectly fine however the result is like this: and this is all one continuous string. I want to access each exchange rate and save them into different variables so I can make calculations with them. I have tried sa...
You are grabbing a JSON (JavaScript Object Notation) file. To make your life much easier you should look into using a library for processing JSON in C++ like jsoncpp. This site here provides a quick tutorial.
71,563,845
71,563,909
Why do I get "forbids converting a string constant to ‘char*’" in C++?
I'm trying to invert the case manually, and I tried this: char* invertirCase(char* str){ int size = 0; char* iterador = str; char* retorno = str; while (*iterador != '\0') { if (retorno[size] < 96) { retorno[size] = *iterador + 32; } else { retorno[size]...
Why do I get "forbids converting a string constant to ‘char*’" in C++? The error message means that you are trying to pass a string literal to the function. String literals in C++ have types of constant character arrays that passed by value to functions are implicitly converted to the type const char *. And any attem...
71,564,234
71,564,806
How can I make this work and is there a way to optimize this?
I wanted to do a calculator with c++, and I did not wish my calculator to do only 2 number calculations, so I "made" 2 operator calculator. Also, I want to learn if there is a way to make this without two switch statements to make it easier for machines and programmers to read. #include <iostream> int top1 ; int main...
You could make use of a function: int Evaluate(const char operator, const int num1, const int num2) { bool is_valid_operator = true; int result = 0; switch (operator) { case '+': result = num1 + num2; break; case '-': result...
71,564,476
71,564,911
How to iterate over a range-v3 action?
I'm new to range-v3. I started by write a program that generates a range of integers, modifies it, and prints out the resulting range. I used a modifier from the actions library, which rendered my code non-iterable. Could someone help me understand how to convert a ranges::action::action_closure into an iterable? Here'...
Actions do not return a light-weight ephemeral object that can be lazily iterated over like view operations do. Actions are applied eagerly to actual containers and return actual containers, but still can be composed together. In the following std::vector<int>() is an r-value that gets filled via push_back which return...
71,564,678
71,564,794
OpenGL how to create a sphere from half-sphere in c++
So, from a material I have, I managed to somehow complete it to half-sphere, the original destination. But now I have to make a sphere from the said half-sphere and I'm lost. I haven't met an answer online that has a fourth parameter (raze). Can someone tell me what I'm missing? The code: void drawSphere(double r, int ...
For a full sphere raze must be equal r. However, the condition if (lat0>alpha && lat1>alpha) is wrong. It has to be: if (lat0 >= -alpha && lat1 <= alpha) Note that for a full sphere you need to draw slices from -M_PI/2 to M_PI/2. That means if (lat0 >= -M_PI/2 && lat1 < -M_PI/2).
71,565,613
71,565,773
Passing message in std::exception from managed code to unmanaged
I am trying to throw a std::exception from managed code so that it is caught in unmanaged code. Where I'm struggling is passing a string (describing the exception) so that the (re-)caught exception can be examined using the what() method ... #pragma managed static std::string InvokeMethod() { try { //... ...
Following suggestion made by @Joe, I inherit from std::exception ... class InvokeException : public std::exception { public: InvokeException(std::string const& message) : msg_(message) { } virtual char const* what() const noexcept { return msg_.c_str(); } private: std::string msg_; }; ... and then ...
71,565,682
71,565,805
Returning a rapidjson::GenericValue from a function
I want to make a function that returns a constructed rapidjson::Value from it. Like this: using JsonValue = rapidjson::GenericValue< rapidjson::UTF16LE<> >; JsonValue MakeInt(int val) { return JsonValue().SetInt(val); //copy-by-reference is forbidden //return JsonValue().SetInt(val).Move(); //same, Move() returns a...
What compiler and C++ version are you using? This compiles OK in MS Visual Studio 2019: using JsonValue = rapidjson::GenericValue< rapidjson::UTF16LE<> >; JsonValue MakeInt(int val) { JsonValue json_val; json_val.SetInt(val); return json_val; } I compile with C++11. Please see this (from document.h) #if R...
71,566,083
71,566,111
C++) why const int*& parameter can't take int* argument?
before writing, I'm not good at english. So maybe there are many awkward sentence. void Func1(const int* _i) { }; void Func2(const int& _j) { }; void Func3(const int* (&_k)) { }; int main() { int iNum = 1; int* pInt = new int(1); Func1(pInt); // works; Func2(iNum); //works Func3(pInt); // er...
Func1(pInt); // works; int* could convert to const int* implicitly Func2(iNum); //works; int could be bound to const int& Func3(pInt); // error; pInt is a int*, when being passed to Func3 which expects a reference to const int*, then it would be converted to const int*, which is a temporary and can't be bound to lvalu...
71,566,232
71,566,322
How to split a string and record each split as a distinct variable C++
I was looking at a popular StackOverflow post about how to split strings. I have found this very useful, but I'd like to take each split and store it in array or a distinct string variable. Such that I can access: scott, tiger, mushroom, or fail. Below is my attempt to do this, but I cannot complile this due to an e...
str[] is an array of individual chars, but you are trying to store std::string objects in it, hence the error. Change the array to hold std::string instead of char. And then consider using std::vector instead of a fixed array. #include <iostream> #include <string> #include <vector> std::vector<std::string> str; ...
71,568,141
71,568,180
Fastest way to insert a character at the beginning of the string in C++?
So while solving problems on Leetcode I came across this problem. To generate a string normally, I could just use str.push_back('a'). But if I want to generate the string backwards I would use this same method and reverse the string at the end. Using str.insert() resulted in Time Limit Exceeded and str='a'+str; would a...
You already answered your own question by saying reversing. Just use += operator to append and then reverse. As another way, first push elements into a stack then pop them to fill string. If it is still slow, then divide the output into small segments and pipeline the reversing + appending parts to hide latency using m...
71,568,155
71,568,178
What is the syntax to require a template variable to be void?
Is there a way to write a requires requires expression to apprehend that a template parameter is void? I believe it is legal to make the value of std::is_void_v<ParmThree> a parameter of the template. However, I cannot formulate a syntax to check this in a requirement - for being either true or false. Is it possible? H...
requires requires works because the nested (second) requires returns a bool. Since you already have a bool, you can just do requires std::is_void_v<T>: template <typename T> requires std::is_void_v<T> struct A {};
71,568,361
71,570,945
Boost Asio Serial port How to find out the size of the buffer in the queue for reading C++
In Arduino data can be read as follows: void setup() { Serial.begin(9600); } String Comand = ""; void loop() { if (Serial.available() > 0) //If there is data read { char c = Serial.read(); //get byte if(c!='\n') { Comand+=c; } else { ...
The idea of asynchronous IO is that you donot check whether data is available. Instead, you defer the completion of the read until that is the case. Now, you're using Asio to still do synchronous IO. And your requirement is: If I read in a cycle, and there is no data, the program will stop and wait for the data, it do...
71,568,830
71,569,572
How to print following pattern in C++ :1st row->10101010...;2nd row->11001100..;3rd row ->11100011 etc
How to print following pattern in C++ :1st row->10101010...;2nd row->11001100..;3rd row ->11100011 and so on. Number of alternate 0 and 1s depends on the row number. Pattern should look like: 1010101010 1100110011 1110001110 Code: #include<iostream> using namespace std; int main() { int row,col...
You are overcomplicating this - you don't need any arrays or tricky indexing. Print one row at a time, starting with 1. Switch back and forth between 0 and 1 at the appropriate columns. for (int r = 1; r <= row; r++) { int symbol = 1; for (int c = 1; c <= col; c++) { std::cout << symbol; if ...
71,569,611
71,569,895
Does popen load whole output into memory or save in a tmp file(in disk)?
I want to read part of a very very large compressed file(119.2 GiB if decompressed) with this piece of code. FILE* trace_file; char gunzip_command[1000]; sprintf(gunzip_command, "gunzip -c %s", argv[i]); // argv[i]: file path trace_file = popen(gunzip_command, "r"); fread(&current_cloudsuite_instr, instr_size, 1, trace...
I only know that popen creates a pipe. There are two implementations of pipes that I know: On MS-DOS, the whole output was written to disk; reading was then done by reading the file. It might be that there are still (less-known) modern operating systems that work this way. However, in most cases, a certain amount of ...
71,570,764
71,571,344
Slow compilation speed for "const unordered_map" as global variable
I am experiencing really slow compilation time, probably due to the existence of a global variable of the kind std::unordered_map. Below you can find the lines of code, which are located in a file called correspondance.h using Entry_t = std::tuple<Cfptr_t, short int, short int>; ... #include "map_content.h"...
Change #include "map_content.h" inline const std::unordered_map<std::string, Entry_t> squaredampl{MAP_CONTENT}; #undef MAP_CONTENT to extern const std::unordered_map<std::string, Entry_t> squaredampl; and in a new .cpp file: #include "correspondance.h" #include "map_content.h" const std::unordered_map<std::string, En...
71,571,034
71,572,183
How to get an instance of class in const expressions (decltype, templates ...)
How to get an instance of a class? Everyone would answer: call its constructor like class_name() Then what if the class has no default constructor? I have a function accepting a byte buffer as argument: template<typename BUFFER> void fun(BUFFER& buf) { I need to have some restrains on BUFFER, and I choose the newest ...
There is already range_value_t which is used to obtain the value type of the iterator type of range type R, so in your case it should be #include <ranges> template<std::ranges::range BUFFER> requires std::same_as<std::byte, std::ranges::range_value_t<BUFFER>> void fun(BUFFER& buf);
71,571,315
71,571,342
Using "typedef" or "using" to define a structure - which is best?
Sample structure: typedef struct tagExportSettings { COLORREF crHeading{}; COLORREF crEvenBack{}; COLORREF crOddBack{}; COLORREF crHighlight{}; COLORREF crDate{}; COLORREF crEvent{}; COLORREF crEmpty{}; COLORREF crNotes{}; } EXPORT_SETTINGS_S; Visual Assist says...
Even better is to use neither. One type name should be enough. Pick either tagExportSettings or EXPORT_SETTINGS_S and stick with it. Example: struct tagExportSettings { // ... }; But, 1. All my code in the software uses EXPORT_SETTINGS_S As I said, pick either name. If you use EXPORT_SETTINGS_S, then name the cl...
71,571,363
71,571,418
What happens when we return with a Sum in C++?
int sum(int k) { if (k > 0) { return k + sum(k - 1); } else { return 0; } } int main() { int result = sum(10); cout << result; return 0; } It's a C++ code I don't understand, when you return in the 3rd like (return k + sum(k-1); aren't we returning 10 + 9 together? Not like 10+9+8+7+6+5+4+3+2+1=55...
This summation function is using recursion (basically when a function contains a callback of itself inside). When you call sum(10), the value you will get is 10 + sum(9), not just 10 + 9. Then sum(9) == 9 + sum(8) and so on until sum(10) == 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0) which will break the recursion ...
71,572,011
71,595,536
How to update a progress Bar in QML by calculating the countdown on the C++ side in the QTWidget?
I basically want to send the progress from the c++ side to update the value of the ProgressBar on the QML size. I am trying to integrate QML into a widget application. The thing is I have my mainwindwo.cpp file like this: MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow)...
You have to create a class that inherits from QObject and is a bridge between C++ and QML: #ifndef PROGRESSBRIDGE_H #define PROGRESSBRIDGE_H #include <QObject> class ProgressBridge : public QObject { Q_OBJECT Q_PROPERTY(int progress READ progress WRITE setProgress NOTIFY progressChanged) public: explicit ...
71,572,186
71,575,543
Question on converting boost shared pointer to standard shared pointer
This is more of a follow up question on the second answer posted here. The code from this answer is shown below: template<typename T> void do_release(typename boost::shared_ptr<T> const&, T*) { } template<typename T> typename std::shared_ptr<T> to_std(typename boost::shared_ptr<T> const& p) { return std::s...
The shared pointer created has a destroy function object (deleter) that has state. In particular it has a copy of the boost shared ptr. The destruction action does nothing, it is the destruction of deleter that cleans up the boost shared ptr. There is a problem though: Does the C++ standard fully specify cleanup of the...
71,572,605
71,572,769
Why same values inside string even after swapping the underlying integer?
I have a 64 bit unsigned integer and for some reason I have to store it inside a string. What I am wondering is that the value inside the string is same even after using the swapped integer? For example: #include <iostream> #include <byteswap.h> using namespace std; int main() { uint64_t foo = 98; uint64_t f...
You can see the same thing with arrays of char: int main() { char foo[8] = { 98, 0, 0, 0, 0, 0, 0, 0 }; char foo_reversed[8] = { 0, 0, 0, 0, 0, 0, 0, 98 }; std::string out(foo, 8); std::string out_reversed(foo_reversed, 8); std::cout << "out: " << out << std::endl; std::cout << "out_revers...
71,572,995
71,573,866
What is the correct way to initialise pointers to structs in C++?
I am trying to learn the best practices while improving my C++ skills and I've got a question. If I have, for example this, struct: struct Vector { int x; int y; }; typedef struct { Vector position; Vector velocity; } Ball; Which one would be the correct way to initialise it? Ball* _ball1 = new Ball()...
First, you can do this: Ball ball; You now have a local Ball object. It will last until the enclosing code is closed. That is: cout << "Foo\n"; if (true) { Ball ball; } cout << "Bar\n"; The ball exists only inside those {}. If you try to use it outside (where the cout of Bar is found), it won't be there. So in ma...
71,573,073
71,583,397
Cygwin 3.3.4 random end of program
I'm looking for tips to find a direction where I have to investigate. I have a little c++ project that works well both on my old cygwin (3.0.4(0.338/5/3)) and on a debian distrib (thanks to Posix) In this project I use some libraries like log4cplus (cxxTest, rapidJson, ...) Now I had to upgrade my cygwin. So I install ...
For every people who read this thread in future : I don't really find a solution in Cygwin, but like @Alan Birtles mention : Use WSL (or another updated solution). It work like a charm. thanks to microsoft ;)
71,573,199
71,573,351
The deduction guide for std::array
In the C++ 17 and C++ 20 Working Drafts of the C++ Standard the deduction guide for the class template std::array is defined the following way template<class T, class... U> array(T, U...) -> array<T, 1 + sizeof...(U)>; As a result for example this declaration std::array a = { 1ll, 2llu }; should be compiled and the d...
C++17 has that requirement in the deduction guide. template<class T, class... U> array(T, U...) -> array<T, 1 + sizeof...(U)>; Requires: (is_­same_­v<T, U> && ...) is true. Otherwise the program is ill-formed. [array.cons#2]
71,573,741
71,573,807
How to install a Chrome extension with C/C++?
I have to install a Chrome extension using C/C++. I tried to copy the whole folder of a extension in C:\Users[login_name]\AppData\Local\Google\Chrome\User Data\Default\Extensions. After copying it I deleted the extension from Chrome and then pasted the extension folder back to its own place but it doesn't get installed...
Google Chrome supports the following alternative extension installation methods: Using a preferences JSON file (for macOS X and Linux only) Using the Windows registry (for Windows only) source: https://developer.chrome.com/docs/extensions/mv3/external_extensions/
71,574,407
71,575,059
Problem parsing date/time with timezone name using Howard Hinnant's library
I'm writing a method to parse date/time strings in a variety of formats. std::chrono::system_clock::time_point toTimePoint(const std::string str) { ... a bunch of code that determines the format of the input string std::string formatStr = string{"%Y-%m-%d"} + " " // Delimeter between date and ...
When reading an offset with %z (e.g. -0600), combined with a sys_time type such as system_clock::time_point, the parse time point is interpreted as a local time, and the offset is applied to get the sys_time, as desired in your first two examples. However this is not the case when reading a time zone name or abbreviati...
71,574,663
71,574,954
CPython extension using omp freezes Qt UI
I am working on a scientific algorithm (image processing), which is written in C++, and uses lots of parallelization, handled by OpenMP. I need it to be callable from Python, so I created a CPython package, which handles the wrapping of the algorithm. Now I need some UI, as user interaction is essential for initializin...
Because of Python's "Global Interpreter Lock", only one thread can run Python code at a time. However, other threads can do I/O at the same time. If you want to allow other threads to run (just like I/O does) you can surround your code with these macros: Py_BEGIN_ALLOW_THREADS // computation goes here Py_END_ALLOW_TH...
71,574,914
71,575,147
Do I have to overload functions for every different parameter?
I want to create a function to simplify a list/vector. I can do it in python: i = [1, 2, 3, 4, 5] f = [1.1, 2.2, 3.3, 4.4, 5.5] s = ["one", "two", "three", "four", "five"] def simplify(lst): if len(lst) == 0: return 0 tmp = lst[0] for x in range(1, len(lst)): tmp += lst[x] print(tmp) ...
My question is, can I do in c++ like I did in python? (creating a single function for multiple types) Almost. A C++ function template is not a function, but using one can look indistinguishable from it. You will also struggle with your choice of -1 as the result if the sequence is empty, as -1 is not a string. templa...
71,575,173
71,660,184
Building GStreamer with CMake causes SDP & WebRTC unresolved external symbol errors
I'm building a C++ GStreamer project with CMake which depends on GStreamer, GLIB, Libsoup and json-glib. I'm new to CMake and having trouble setting up my project. I've managed to include many of the dependencies but some seem to remain unresolved even though they are part of GStreamer. All GStreamer methods and types ...
I've managed to solve it by using a premade find script I found online. https://chromium.googlesource.com/external/Webkit/+/master/Source/cmake/FindGStreamer.cmake It creates all necessary defines which I then include and link. These are the defaults as specified in the FindGStreamer.cmake file FIND_GSTREAMER_COMPONENT...
71,575,246
71,576,145
Is it possible to create "parent" class' method that accepts "child" class object as a parameter?
What I'm trying to do is something like this: class Parent{ ..... .... public: Child* func(); }; Child* Parent::func() { Child C[] = {.....,....,...}; return C; } class Child : Parent{....}; Excuse my total disregard for <array here.
You can forward-declare Child before using it in the declaration of func(). This only works for pointers and references. You would then need to fully define what Child looks like before you can make Child instances in the definition of func(), and then you can return Child* pointers as needed. Note that returning a p...
71,575,691
71,575,756
std::vector does not release memory in a thread
If I create a thread with _beginthreadex, and in the thread I used std::vector<WCHAR> that consumes 200MB of memory - when the thread ends, the memory is not released. Even after CloseHandle, the memory is not released. Here is a working example: #include <windows.h> #include <process.h> #include <vector> using namespa...
C++ doesn't know that calling _endthreadex makes the thread go away. So it doesn't call the destructors of local variables like asdf before it calls _endthreadex. Solution: Don't do that. return 0; ends the thread and calls the destructor.
71,576,273
71,576,466
Fast byte copy C++11
I need to convert C# app which uses extensively bytes manipulation. An example: public abstract class BinRecord { public static int version => 1; public virtual int LENGTH => 1 + 7 + 8 + 2 + 1; // 19 public char type; public ulong timestamp; // 7 byte public double p; ...
Best option, in my opinion, is to actually go to C - use memcpy to copy over the bytes of any object. Your above code would then be re-written as follows: void FillBytes(uint8_t* bytes) { bytes[0] = (uint8_t)type; memcpy((bytes + 1), &t, sizeof(uint64_t) - 1); memcpy((bytes + 8), &p, sizeof(double)); ...
71,576,623
71,579,381
Constexpr expand constructor parameter pack into member array (C++11)
I want to expand a pack of variadic parameters into a struct member in C++11. My approach is the following: template <typename... Ts> struct cxpr_struct { constexpr cxpr_struct(Ts... Args) : t_(Args...) {} std::array<int, sizeof...(Ts)> t_; }; int main() { cxpr_struct(10, 20, 30); } However, this yields t...
due to c++11, you have to use something like that: template <typename... Ts> struct cxpr_struct { constexpr cxpr_struct(Ts... args) : t_{args...} {} std::array<int, sizeof...(Ts)> t_; }; template<typename... Ts> cxpr_struct<Ts...> build(Ts...args){ return cxpr_struct<Ts...>(args...); } int main() { au...
71,576,948
71,577,334
How cppwinrt.exe tool know which C++ version to use to generate the headers from .winmd files?
I don't see any switch to specify the "C++ version" in the cppwinrt.exe tool ! (my fundamental assumption is cppwinrt.exe tool binds the C++ 17 syntax to the ABI, I can't figure out how it can bind C++ 20 or future newer versions syntax ) Similarly, the cswinrt.exe tool from C#/WinRT projection generates .cs files fro...
The cppwinrt.exe tool doesn't allow you to specify a C++ language standard. It simply defaults to C++17, with the ability to opt-in to newer language features by way of feature test macros. The result is that the generated header files can be compiled with any C++17 compiler, or a compiler that supports a later languag...
71,577,055
71,578,034
How can I add a path to a Makefile?
In C++, I have a library path I know how include when building with a CMakeLists.txt file but I don't know how to include it when building with a Makefile. I tried applying the solution asked and answered here but it didn't work. The contents of the Makefile is below. The library's name is "NumCpp". The full path to th...
This line assigns a value to a makefile variable named COMMON: COMMON=/O2 /MT /EHsc /arch:AVX /I../include /Fe../bin/ this line assigns a value to a makefile variable name cl_var: cl_var = 'cl' These lines in the recipe use (or "expand") the variables cl_var and COMMON: $(cl_var) $(COMMON) testxml.cc ../bin/mujoco210...
71,577,371
74,487,602
Will ObjC setter automatically copy a C++ object passed as a parameter when get called?
I recently read about a std::unique_ptr as a @property in objective c and the suggestion to store a unique_ptr in ObjC as a property is as following: -(void) setPtr:(std::unique_ptr<MyClass>)ptr { _ptr = std::move(ptr); } My question is in ObjC, does the parameter get copied in this case? Because if that happens, ...
My question is in ObjC, does the parameter get copied in this case? That depends. Let me introduce a custom class where all copy operations are removed to better demonstrate possible outcomes under different circumstances: struct MyClass { MyClass() { std::cout << "Default constructor" << std::endl; ...
71,577,835
71,577,897
Should I qualify pointer parameters with volatile if they may be changed during the execution of a function?
Say I have the function int foo(int * const bar){ while(!*bar){ printf("qwertyuiop\n"); } } where I intend to change the value at bar to something other than 0 to stop this loop. Would it be appropriate to instead write it as below? int foo(int volatile * const bar){ while(!*bar){ printf("q...
volatile was intended for things like memory-mapped device registers, where the pointed-to value could "magically" change "behind the compiler's back" due to the nature of the hardware involved. Assuming you're not writing code that deals with special hardware that might "spontaneously" change the value that bar point...
71,578,589
71,579,169
C++ vector push_back async object in for loop
I was coding a for loop in C++11, where I needed to push back an async object onto a vector. I wanted to split the object initialization into two steps: std::vector<std::future<bool>> asyncThreads; for (int i = 0; i < processorCount; i++) { auto boundFunc = std::bind(&Foo::foo, this); auto asyn...
A std::future object is not copyable, but moveable. So therefore, you must call move on the object to push it onto the vector.
71,578,607
71,580,760
zlib error -3 while decompressing archive: Incorrect data check
I am writing a C++ library that also decompresses zlib files. For all of the files, the last call to gzread() (or at least one of the last calls) gives error -3 (Z_DATA_ERROR) with message "incorrect data check". As I have not created the files myself I am not entirely sure what is wrong. I found this answer and if I d...
First off, the whole point of the CRC is to detect corrupted data. If the CRC is bad, then you should be going back to where this file came from and getting the data not corrupted. If the CRC is bad, discard the input and report an error. You are not clear on the "behavior" you are trying to reproduce, but if you're tr...
71,578,686
71,578,723
Why does "for(std::size_t i=2; i >= 0; --i)" fail
I was surprised when this for loop failed to run properly: for (std::size_t i=2; i >= 0; --i) I figured, okay, probably the final check is if -1 >= 0, and since i is not allowed to be negative, we have a problem. Presumably i is looping around to (264 - 1). However, this for loop does execute: for (std::size_t i=2; i+...
What is going on here? std::size_t is an unsigned integer type. i >= 0 All unsigned integers are greater than or equal to 0. There exists no value for which this relation would be false and hence the loop cannot end. i+1 > 0 An unsigned integer can be 0. Hence this relation can be false and the loop can end. Ex...
71,578,699
74,013,278
setGeometry obstructed by setText
I created a Qt Widget in Qt Creator which consists of a QSlider and a QProgressBar whose length I want to adjust to the position of the slider like this: To do so, I use setGeometry(). In order to maintain the length relative to the window width, I call my resizeProgressBar() in my overridden resizeEvent(). The slider...
Since the originally intended way did not work, I've now solved the problem by using a horizontal layout containing the QProgressBar as well as a horizontal Spacer on the right of the bar. The stretch factors are set to 1 and 0, respectively. Now, when I move the slider, I change the stretch factors accordingly, so the...
71,578,740
71,586,797
constexpr result from non-constexpr call
Recently I was surprised that the following code compiles in clang, gcc and msvc too (at least with their current versions). struct A { static const int value = 42; }; constexpr int f(A a) { return a.value; } void g() { A a; // Intentionally non-constexpr. constexpr int kInt = f(a); } My understanding w...
As mentioned in the comments, the rules for constant expressions do not generally require that every variable mentioned in the expression and whose lifetime began outside the expression evaluation is constexpr. There is a (long) list of requirements that when not satisfied prevent an expression from being a constant ex...
71,578,748
71,579,204
Printing an std::array gives random values
I am trying to print out an std::array as seen below, the output is supposed to consist of only booleans, but there seem to be numbers in the output aswell (also below). I've tried printing out the elements which give numbers on their own, but then I get their actual value, which is weird. My main function: float f(flo...
Floating point maths will often not produce accurate results, see Is floating point math broken?. If we print out the values of indx and indy: 20, 20 20, 19 20, 18 20, 17 20, 15 20, 14 20, 13 20, 13 20, 11 20, 10 20, 9 20, 9 20, 8 20, 6 20, 5 20, 5 20, 3 20, 3 20, 1 20, 1 19, 20 19, 19 19, 18 19, 17 ... You can see th...
71,578,994
71,579,044
Member initialization while using delegate constructor
The C++ standard does not allow delegate constructors and member initializers in a single mem-initializer-list, yet the following code compiles fine with clang++ and g++. #include <iostream> class Shape { public: Shape(); }; class Circle : public Shape { public: std::string name; Circle(std:...
You are not using a delegating constructor. A delegating constructor calls another constructor in the same class. For example, in: struct Foo { Foo(int) : Foo("delegate") {} // #1 Foo(std::string) {} // #2 }; #1 and #2 are both constructors for Foo, and constructor #1 delegates to constructor #2. In your case,...
71,579,286
71,579,532
QT push button to create object
I am trying to create a little game using a pile structure, and im using QT Widget Application, my problem is: i have a class Pile that needs to be initialized with Pile p1(size), and "size" is obtained when the button "Create" is pushed. The problem is: when i do this, my object p1 will be exclusive to the PushButton ...
One of many possible solutions. Assuming that class Pile is not a QObject and you need to create plural instances of this class, we would nee so container to store those Piles. There are standard containers and there is Qt's own container template QList, which is a mixture of list, vector and queue. Ensure that you use...
71,579,360
71,579,919
Why is user defined copy constructor calling base constructor while default copy constructor doesn't?
Consider the following example: class A { public: A() { cout<<"constructor A called: "<<this<<endl; }; A(A const& other) = default; }; class B : public A { public: B() { cout<<"constructor B called: "<<this<<endl; }; ...
Why is the constructor of A is called when copying B? Shouldn't the copy constructor of A be called instead? No, it shouldn't. A derived class must always initialize a base class. If the derived class has a constructor that is implemented explicitly by the user, but it does not explicitly call a base class construct...
71,579,930
71,580,090
Would not deleting the head in a linked list cause a memory leak?
I'm currently trying to make my own destructor for my Linked List class, and I know that I can't delete the head in the destructor because curr is using it in the code above, but would not deleting the head cause memory leaks in my code? Do I even need to set head equal to null? ~LinkedList(){//Destructor Nod...
I know that I can't delete the head in the destructor because curr is using it in the code above Then what you know is wrong, because you can and must free the head node, otherwise it will be leaked if the list is not empty. Just because curr points to the head node does not mean you can't free that node. Just don'...
71,580,681
71,650,283
SSL gRPC client works fine in C#, but fails with UNAVAILABLE "Empty update" in C++
On Windows 10 Pro 21H2 with VS2022 17.1.2 and .NET 6, I am porting a simple C# gRPC client to C++, but the C++ client always fails to connect to the server despite my code seemingly doing the same, and I ran out of ideas why. My gRPC server is using SSL with a LetsEncrypt generated certificate (through LettuceEncrypt),...
This is a known issue in the Windows C++ implementation of the gRPC client (and apparently macOS too). There is a small note on the gRPC authentication guide stating: Non-POSIX-compliant systems (such as Windows) need to specify the root certificates in SslCredentialsOptions, since the defaults are only configured for...
71,581,135
71,581,174
Why it is needed to use const A& instead of just A&?
I was wondering why it is needed to use const A& in this situation, Why can't I use just A&? according to what I read is because it specified that it won't change the object. Is there any other reason? I would like a better explanation. Code: #include<iostream> #include<set> class A{ public: int x; A(int x=0)...
A& is an lvalue reference, which means it can change the thing it's looking at. With A(A& rhs) you can call it like int x = 10; A a(x); And then any changes to rhs in the constructor will change the actual variable x. And that's fine. But when you do A a(10); That's a problem. Because if someone changes rhs in the c...
71,581,252
71,581,417
Calling private method from a Public method in the same class
I am trying to call the method gcd() in my multiplication method but I'm not sure what the correct way is. When I run the code below the console displays blank lines, when it should print a fraction. I've tried calling this->gcd(), fraction2.gcd() and gcd(). EDIT: Added cout override and main() to be able to run #inclu...
ok here goes why this->gcd doesnt work. YOu have class Fraction { int gcd(int num1, int num2) { int absNum1 = abs(num1); int absNum2 = abs(num2); while (num2 != 0) { int remainder = absNum1 % absNum2; absNum1 = absNum2; absNum2 = remainder; } ...
71,581,531
72,770,957
HALO support on recent compilers for C++ coroutines
I have read the article Using Coroutine TS with zero dynamic allocations, and the author insists that HALO would work for coroutines and he provides an godbolt link which shows generator example HALO applied with clang 5.0. However, with more recent version of clang(clang 13.0.1 on godbolt) I can see calls to operator ...
The original example does HALO with -O3, just not with -O2. Seems like HALO does happen, but depends on additional optimization passes. All I did was update it to C++20 and stdx -> std. https://godbolt.org/z/qrvWo68Yz
71,582,622
71,583,398
How does stoi() function work with stringstream in C++?
So I'm new to C++, so bear with me here. I'm trying to read a csv file and parsing the data into smaller strings to hold in my class. As I attempt t do this, I come across a problem with stoi(). Every time I try to convert my string to an int, I get an error "terminate called after throwing an instance of 'std::invalid...
The operator>> will read a stream directly into an integer (you don't need to manually convert it). string data; int rank; while (getline(file, data)) { stringstream s(data); // Always check stream operations worked. if (getline(s, date, ',')) { aSong.setDate(date); // Why is Da...
71,582,876
71,586,011
gcov coverage limited to test files in minimal g++ project
After failing to get coverage with-cmake I set up a minimalistic project to see if I can get coverage working that way. It's derived from using-gtest-without-cmake It has a src folder with a header and source file in it. QuickMaths.hpp : #include <cstdint> using size_t = std::size_t; size_t multiply(size_t a, size_t ...
This error occurs because you are linking multiple files with the same name. There are two clues to the problem: When running the test, you will see a warning such as the following: libgcov profiling error:REDACTED/a-QuickMaths.gcda:overwriting an existing profile data with a different timestamp The coverage report ...
71,583,142
71,583,425
Template interface singleton
I was hoping to use an interface to make a generic template class I can add to any other class to easily create singletons. (By easily create singletons I mean avoid having to re-write the 6 lines for GetInstance) template <class T> class Singleton { public: static T* GetInstance(); }; template<class T> inline T* S...
First of all, your singleton should look differently as yours isn't thread safe. Then there are at least 2 solutions. First, is to make a particular instantiation a friend, so it would look something like this: template <class T> class Singleton { public: static T* GetInstance(); }; template<class T> T* Singleton<...