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
62,991,363
62,991,626
Access non-persisted memory-mapped files
I cannot find a library for non-persisted memory-mapped files in Linux for C++. I searched for a while to find any library but there is nothing is there any reason why this does not exist in Linux and what would work instead of non-persisted memory-mapped files to share memory between two programs. Thanks in advance.
There is no need for a library. This is directly supported by the POSIX standard. Use MAP_ANONYMOUS on mmap: The mapping is not backed by any file; its contents are initialized to zero.
62,991,480
62,991,555
Can I forbid temporary objects as parameters?
Let's say I have the function: void foo(Object& o) { /* only query o, dont alter it*/ } Is it possible to call this function only with already constructed objects and have Visual Studio throw a compile error if I call the function with a temporary object? struct Object { /*Members*/ } void foo(Object& o) { ...
If your parameter is not const, the function won't accept temporaries. If your parameter is const, the function accepts both temporary and regular objects. But if you want to prevent that, you can use the following struct Object{}; void foo(const Object& o) { /*only query o, don't alter it*/ } void foo(Object&& ) =...
62,991,495
62,991,541
Can I enable strict floating point behavior for single function in GCC and Clang?
I have the following function: template <typename Float, std::enable_if_t<std::is_floating_point_v<Float>, int> = 0> constexpr Float inf2nan(Float x) { static_assert(std::numeric_limits<Float>::is_iec559); return x * 0 + x; } This function will return NaN if the input is infinity, otherwise just the input. Unf...
One way how to do that is to place all function definitions for which you want to have a certain set of compiler flags into on compilation unit (.cpp file) and compile this compilation unit with its own settings. That way you do not need to rely on compiler related in source settings. How to exactly do that depends on ...
62,991,680
62,991,852
What does output indicate when larger address is subtracted from smaller address in C/C++ programming?
Given a snippet of code as: int a[5]; printf("%u\n",&a[3]-&a[0]); printf("%u",&a[0]-&a[3]); now the output of first line in subtraction of addresses is as per formula ( (addg - adds)/size of data type ) where, addg is greater than adds. The output for above snippet in gcc is: 3 4294967293 The first line output (i.e. ...
The problem in your code is that you have undefined behaviour. Not because of the pointer arithmetic but because you are printing signed integers using the %u format specifier. Change to the %td format (the t to specify a 'pointer difference' type) and you will see more meaningful results: #include <stdio.h> #include ...
62,991,712
63,010,383
how to disable /Qspectre using Visual Studio 2019 Developer Command Prompt
I tried to google it but couldn't find it. I want to Disable /Qspectre from command line. Note: I am trying this inside docker container i have already installed component for it.But still i am getting error MSB8040: Spectre-mitigated libraries are required for this project.So i want to disable it and give try. if it ...
I am afraid there is no direct command line method to disable /Qspectre. I suggest that you could disable it by some other methods. Put/copy file with name 'Directory.Build.props' to build folder with content: <Project> <PropertyGroup Label="Configuration"> <SpectreMitigation>false</SpectreMitigation> </Propert...
62,992,245
62,992,405
C++ std::find for strings ignoreres lower/upper case?
I need for a class a function which checks if a string is contained in another. Did I understand right that the STL function std::find for strings ignore lower and upper case (that is what I need)?
find searches for an element equal to value std::string::find iterates over the range and returns the position to the first element satisfying the condition or last is no match was found. if you pass a substring contained in a larger string to the std::find function, the algorithm should return the position where the...
62,992,854
62,992,947
How to avoid same sequences of random numbers
I would like to generate different sequences of uniformly distributed samples. To this end, I initialize the default random engine with different seeds, but the same sequences are produced: #include <iostream> #include <random> void fun(double seed) { std::cout << "given seed: " << seed << std::endl; std::defa...
The seed of the generator is an integer. The problem is that all numbers generated by your dis_1 are less than 1, and greater than or equal to 0. Therefore they implicitly convert to the same value 0 when converted to an integer. The solution is to use a different seed, rather than 0 always.
62,992,867
62,993,169
Max no. of elements that can be stored in the std::vector<int>
As we can store 10^7 elements in array,if we are required to store the elements >= 10^9 then how can we do that?
Max no. of elements that can be stored in the std::vector Depends on the limitations of the system that runs the program. On a 64 bit system, the maximum is most likely limited by the amount of physical memory your system has available. if we are required to store the elements >= 10^9 then how can we do that? Then ...
62,993,001
62,993,875
Do std::async and std::future use mutexes and a condition variable under the hood?
I've been lead to believe that using std::async with the returned future is basically just a simplified way of using mutexes, where the actual handling of the new std::thread and the locking/unlocking of the mutex is abstracted away by the async function and the future. I'm fairly new to multi-threading concepts - is t...
Maybe. It's up to the implementer. They can do it with std::mutex and std::condition_variable, or with the underlying components with which they implemented those, or with some other scheme. The standard prescribes the observable behaviour, not the implementation.
62,993,060
62,996,545
Segmentation fault for calling base class variable
I have been using this code for a long time now in a project. However, I have recently added llvm-config --cxxflags --libs to the compiler in order to link with llvm libraries and it started generating seg faults. I have located the error and it happens when I call base class's variables. Here is a small example of wha...
When i changed compile options the pointers were set to 0xfffffff by default instead of 0. Therefore the check if (pointer) generated true even when the pointer were not initialized that led to calling function graphViz().
62,993,136
62,993,245
How to check if a std::unique_ptr is null, if it is in a std::vector?
I have a vector<unique_ptr<BaseClass>>, and I am adding new items to it by calling vec.push_back(std::make_unique<DerivedClass>()). How can I check for nullptr using operator bool()? I tried to use vec.back() directly, like so: if((!vec.empty() && vec.back()) { // yay! } else { //nay! } but it always returns with ...
As you can read from here, if the vector is empty, it's UB. If it's not your case, as you can read from here instead, unique_ptr has a operator bool() which checks whether an object is currently managed by the unique_ptr So, with: vector.empty(); You can check if the vector has elements, and with: vector<unique_ptr<so...
62,993,544
63,028,358
Definition of dllimport static field not allowed with Qt Creator and Cocos2d
I have been given a task to make a qt project originally created on Mac run on Windows. It needs to use MinGW (g++ and gcc) for compilation. I had problems with _WIN32 and _WINDOWS not being defined when trying to build the project (although it says in settings that they were), so I just hardcoded that bit for the time...
I had to define _WIN32 and _WINDOWS in the project menu of the QtCreator as additional arguments for make to avoid the hardcoding. I also had to define CC_STATIC to prevent Cocos2d to insert the dllimport or dllexport before each of the functions. The arguments I added were: DEFINES+="_WIN32 _WINDOWS CC_STATIC"
62,993,977
62,995,593
Determining the cause of kubernetes pod restart
I'm running into issues with our Kubernetes deployment. Recently we are running into a problem with one of the pods being restarted frequently. The service inside is using C++, with Google Logging and should dump a stacktrace on a crash (it does do that when run locally). Unfortunately, the only log message I was able ...
The pod could have been terminated for reasons like out of memory. Use kubectl describe pod <podname> which contains the information. There should be output like this (could also be a different reason than OOM): Last State: Terminated Reason: OOMKilled
62,994,044
62,994,212
unable to open file in visual studio
im learning c++ using visual studio as ide. I'm currently doing io streams, but when i try to open a file, the program doesn't open the file. here is the code - #include <iostream> #include <string> #include <iomanip> #include <fstream> #include <vector> int main() { std::ifstream file; file.open("Text.txt");...
you need to keep the file in the directory where the executable is generated by default when using Visual Studio. this is typically located in your solution directory under a folder called Debug/Release depending on your configuration. check the project settings to see where the executable will be generated and copy t...
62,995,172
62,996,584
C++ detect program ending in destructor
I have not found answer for this question but I'm almost 100% sure there is laying out somewhere. I have a normal C++ class, and I'm using a 3rd party logging system. Unfortunately I have 2 requirements and 3 facts which I can't match: Requirements: Log something in destructor Handle the program termination clean (wit...
Can I somehow detect in the destructor of a class (myClass) if program is terminating Yes, if the instance has static storage. You can register a function that will be executed during destruction of static objects using std::atexit. This function can be used to set a namespace scope variable that signifies whether th...
62,995,665
63,032,702
C++ fluent interface
I'm implementing a fluent interface for my C++ GUI library. The basic concept is for every function to return a pointer to template. Here are two classes. template <class T> class wnd { public: T* set_id(int id) { id_ = id; return (T*)this; } T* set_text(std::string text) { text_ = text; return (T*)this; } prot...
I feel a bit younger now, because I found an answer on Stack Exchange. What is needed is a modified CRTP using default template arguments. Here's the class code. template <typename Q, typename T> struct fluent_type { typedef Q type; }; template <typename T> struct fluent_type<void, T> { typedef T type; }; tem...
62,995,720
63,015,092
How to fix Missing CSRF token in sentry
After fighting with sentry when installing it on openshift i got it up and running only to discover that when sending an event to my server it will throw this error: 12:30:59 [WARNING] django.request: Forbidden (CSRF cookie not set.): /api/1/envelope/ (status_code=403 request=<WSGIRequest: POST u'/api/1/envelope/'>) 1...
Proxy /api/ to sentry relay worker. Relevant part from https://github.com/getsentry/onpremise/blob/master/nginx/nginx.conf upstream relay { server relay:3000; } upstream sentry { server web:9000; } server { location /api/store/ { proxy_pass http://relay; } location ~ ^/api/[1-9]\d*/ { proxy_pass http://relay; }...
62,996,308
62,996,388
What Type of Initialization Occurs When Calling Copy Constructor?
Consider the simple struct below (defaulted just to be explicit). struct foo { foo() = default; foo(const foo&) = default; }; foo bar() { return foo{}; // return does copy init } What kind of initializations take place below? foo a; // default init foo b{}; // value initialization foo c{bar()}...
Given foo c{bar()};, c is direct-list-initialized from the return value of bar(). And it's same for foo d{c};, d is direct-list-initialized from c. initialization of a named variable with a braced-init-list (that is, a possibly empty brace-enclosed list of expressions or nested braced-init-lists) As the effect, for...
62,996,553
62,998,161
Function parameter with unknown value cannot be used in a constant expression
Why I get compilation error "function parameter 'field' with unknown value cannot be used in a constant expression"? All marked as constexpr, I don't see any problems with knowing value at compile time. Is there any way to fix this error? #include <tuple> #include <string_view> namespace { template<typename Tuple, t...
function parameter are not constexpr, so you have to play with type instead: template <typename T, typename Tuple> struct has_type : std::false_type {}; template <typename T, typename... Ts> struct has_type<T, std::tuple<Ts...>> : std::disjunction<std::is_same<T, Ts>...> {}; with usage similar to for_each(fields, [](c...
62,996,729
62,999,378
Compiler warning/error when using #if on something that is undefined
Consider the following example: #define FOO false #if FOO void foo(){} #endif Obviously, foo() does not exist. But when I forget to define FOO, the result is the same: #if FOO void foo(){} #endif Is there any way to have foo() {} conditionally, depending on FOO, but automatically yielding a warning or error when FOO ...
Also, although using an undefined macro is not an error (it evaluates to 0), you can make it one by adding the following to your GCC or Clang command line: -Wundef -Werror But note that all warnings will now be treated as errors, and you will become reliant on build settings. So I prefer the explicit approach of #else...
62,996,973
62,997,084
why exception specification of a constructor for empty class type is non-throwing exception specification
struct Test{ Test() = default; // why the implicitly declared as non-throwing exception specification ? }; The implicitly-declared copy constructor for a class X will have the form X::X(const X&) if each potentially constructed subobject of a class type M (or array thereof) has a copy constructor whose first para...
What we have here is less a matter of formal logic and more a matter of what English words mean. The text for the copy constructor form specifies "do the thing if each X has property Y". The text for the exception specifier says "do the thing if any X has property Y". Now, if we look at the copy constructor case, what ...
62,997,345
63,004,428
Triggering googletest error on EXPECT_FLOAT_EQ even when numbers are within 4 decimal places
I'm creating unit tests for a program that performs floating point computations in C++. Throughout the unit test file, I've been using EXPECT_FLOAT_EQ successfully, even when the floating point numbers are not exactly the same: some successful tests have had results that are ~.00000001 off without triggering an error. ...
The IBM docs got it wrong. The EXPECT_FLOAT_EQ macro requires the values to be "almost equal" or, strictly defined, within 4 units in the last place. Google Test docs on floating point comparison give a short explanation of ULPs, with references to more reading. If you want values to be equal within 4 decimal places, u...
62,997,507
62,997,852
How to free memory allocated by new[]?
I'm currently trying to create vector-like container. It uses memory allocated by new[] as it's base. the problem arises when I need to expand the array. I allocate a bigger chunk of memory with new[], then memcpy old memory into there and delete[] the old memory. Thing is, trying to store any pointer or any pointer-co...
How to free memory allocated by new[]? Using delete[]. This must be done before the pointer value is lost, and it must be done after the last use of the pointer value. And it must be done exactly once. And it must not be done for any other pointer than one that was returned by array new. Thing is, trying to store an...
62,997,757
62,999,689
Program goes into infinite loop, But if removed some functions or lines, it works
A basic student database using classes, I accept name, roll number, and sgpa(cgpa equivalent but out of 10). I used while loop, and switch case,but if the code for sgpa validation, and code for displaying all students with same sgpa is removed, the program works neatly, but if not, the program goes into continuous loop...
I found the bug, it was a type conversion bug, i was accepting a float value but passing it as a int,just worked, don't know why.But thanks for each comment and suggestion.
62,997,769
63,042,117
Link PCL libraries while compiling C++ programs in Linux
I am new to the Point Cloud Library. There is a thing that has been bugging me for some time. So, on my system, whenever I have to compile a C++ program, which requires OpenCV libraries to be linked, I use the following terminal command: g++ -std=c++11 fileName.cpp -o executableFile `pkg-config --cflags --libs opencv` ...
I experimented for a while, and here is how I figured this out. man pkg-config tells you the folders where pkg-config looks for .pc files. So, I checked those folders for the exact .pc file names that I want pkg-config to link with my .cpp file. I found the required file (pcl_io-1.11.pc) at \usr\local\lib\pkgconfig Nex...
62,998,445
63,003,754
How to set C++ language standard in C++ Builder
Today we worked on a piece of code that requires either C++14 or C++17. My colleague used C++Builder for the code editing, and also wanted to try to compile the code piece with it. We could not find the setting where one sets the C++ language standard. What we found by googling was that C++builder has a "classic compi...
Hans Passant has posted a comment to my question which links to New in RAD Studio 10.3: C++17, asynchronous C++ code completion, and more, thank you. From this link I learn: C++ Builder 10.2 does not include any support for C++14 nor C++17. C++ Builder 10.3 supports C++17 only when compiling 32 bit windows binaries. S...
62,998,448
62,999,281
Implementation of Djikstra doesn't seem to match theoretical complexity
I am implementing yet another Djikstra's shortest path algorithm. I have run it on smallish datasets and from what I can tell it is doing things just fine. The goal is to use this to approximate a geodesic on a mesh. So for example the green line in the following image is an approximation of the geodesic connecting the...
put the queue.push() statement inside if. if (total_distance < node_distance_map[neighbour_id]) { node_parent_map[neighbour_id] = current_node_index; node_distance_map[neighbour_id] = total_distance; queue.push({ total_distance, neighbour_id }); } You'd still get the right answer without doing this, but th...
62,998,454
62,998,655
Confused about insertion into linked list
This is the code for the node class itself: struct Node { int data; struct Node * next; Node(int x) { data = x; next = NULL; } }; The code below inserts a new node at the beginning of a linked list. My question is why the fourth line doesn't mess up the order of the list. If head was previously in the ...
head is not a node. It's a variable which holds the address of a node. head = new_node; does not move any nodes! It looks at the value in the new_node variable (which is the address of a node) and stores that same value into the head variable. It doesn't change the list. It only changes the head variable. This line cha...
62,998,823
62,999,067
Recursion ( return statement )
I face a problem while solving a problem in codeforces using recursion in java . package codeforces; import java.util.Scanner; public class NewClass11 { static int solve(int x, int y, int count) { if (x > y) { return count; } else { count++; x = x * 3...
But why this is not work like as c++ code? Because C++ is different from Java. The difference that applies in this case is that C++ doesn't require that all branches of a non-void function return. The shown C++ program is well-formed, so it compiles. Instead, if the function execution reaches the last curly brace wit...
62,999,354
62,999,489
Vector resizing shortcut?
Can std::vector foo.resize(foo.size()+1); be turned into foo.size++;? I know vectors auto-resize, but it would be a handy shortcut.
No, it can't. You have no access to the size of a vector other than by: its functions that perform data-based operations such as adding a new element its function size() that returns, in a read-only manner, its current size. The way to spell foo.size++ is foo.emplace_back(). You do this because you want a new element...
62,999,409
63,002,224
Is putting const before and after a function header equivalent?
While reading some code, I didn't understand the meaning of the const modifier. For example, are the following two lines equivalent? void output() const; const void output();
For any case const T function(ARGS ...) means that the function returns const T object. For T function(ARGS ...) const things are different. First, you can't have this kind of function wherever you want. This function must be only as a non-static member function of user-defined type (AKA struct or class). class A { T...
62,999,546
62,999,680
Use NULL pointer in C shared library
I am creating a C shared library. I provide a function to the user that has the declaration below: int getResults(Elements** el) where Elements is an array of structs provided by the user, which the function then fills with the values. The final number of calculated elements is different each time, depending on parame...
could this approach fail? It could be misunderstood. Other than that, I don't see a problem with the API. I have read that NULL does not necessarily mean a specific number, 0 that is. So, if for example a user links with the library using another compiler, standard or integrates it with C++, is it guaranteed that th...
62,999,794
63,002,987
How to compile with boost/python numpy library? Make can't find the library files
I have a C++ extension that uses the numpy library from Boost/Python. Here's the .h file: #pragma once #include <string> #include <exception> #include <utility> #include <deque> #include <map> #include <vector> #include <random> #include <time.h> #include <python3.6m/Python.h> #include <boost169/boost/python/object/p...
Added this behind -L /lib64 and it worked: -L /lib64/boost169
63,000,052
63,000,331
Comma Operator in subscript operator?
I am quite confused with the comma operator. I have never seen such code with such syntax? but I am curious if it useful at any place? why is it deprecated in c++20? #include <iostream> int main() { int a[5]{1,2,3,45,5}; std::cout << a[(2,3)] <<'\n'; // this is work , in c++17 works std::cout << a[2,3] <...
It's important to recognize the difference between comma as an expression operator and comma as a separator between grammatical terms of some kind. They use the same punctuation, but they don't have the same meaning. Within the {} of a braced-init-list, individual terms are separated by commas. So {1,2,3,45,5} is a seq...
63,000,236
63,000,736
Creating array size of passed value gives garbage value
int higher_element = arr[0]; for(int i = 0; i < length; i++) if(arr[i] > higher_element) higher_element = arr[i]; cout << "Higher element in an unsorted array :" << higher_element << endl; int Hash[higher_element] = {0}; Here I want to create a new array of size higher_element and initialize it to 0 but...
Since you are using C++, I suggest you to use vector. Here's the std::vector solution for your problem. std::vector<int> Hash(higher_element); Vectors initialize to 0 automatically. But for your clarification, std::vector<int> Hash(higher_element,0);
63,000,336
63,367,356
C++ function instrumentation via clang++'s -finstrument-functions : how to ignore internal std library calls?
Let's say I have a function like: template<typename It, typename Cmp> void mysort( It begin, It end, Cmp cmp ) { std::sort( begin, end, cmp ); } When I compile this using -finstrument-functions-after-inlining with clang++ --version: clang version 11.0.0 (...) Target: x86_64-unknown-linux-gnu Thread model: posix In...
I've run into the same problem. It looks like support for these flags was once proposed, but never merged into the main branch. https://reviews.llvm.org/D37622 This is not a direct answer, since the tool doesn't support what you want to do, but I think I have a decent work-around. What I wound up doing was creating a...
63,001,065
63,001,256
Function-pointer with variable count and type parameter?
In C++ I need to pass some variables to a function, and I want that function to call back my function pointer with my parameters: // Example program #include <iostream> #include <string> using namespace std; typedef void(*callback)(int,int); void otherFunction(string query, callback c, ??) { cout << "otherFuncti...
I would suggest to use variadic template for the parameters, and template argument deduction to avoid declaring the type of the function: template<class Callback, class ...T> void otherFunction(Callback c, T ...params) { cout << "otherFunction is processing data" << endl; c(params...); // if you want to have th...
63,001,251
63,001,389
How can I generate the following pattern using C++?
If n = 5 1 2 1 5 2 4 3 4 3 6 5 3 4 8 7 2 5 10 9 1 I have tried the following code but doesn't give the correct output. #include <iostream> using namespace std; void main() { int i, j; for (i = 1; i <= 5; i++) { for (j = 1; j >= i; j++) { cout << j; ...
Each column of the output follows a pattern, so you can print out the correct values as you iterate through the rows: for (int i = 1; i <= n; ++i) std::cout << i << " " // natural numbers << 2 * i << " " // even natural numbers << 2 * i - 1 << " " // odd natural numbers ...
63,001,619
63,002,562
Derived class serialization - 'unregistered class' exception
Trying to get boost serialization to work. The main idea is to have a base class that contains a few members and some derived classes, each derived class has it's own private members alongside with the base class members. This is a minimal version of what I'm trying to do: class base { public: virtual void ...
This is one rare occasion where auto might hurt: auto d20 = new derived20(); ar << d20; Contrast with: base *b; iar >> b; Note how d20 is derived20*, not base*. So you're invoking Undefined Behaviour by attempting to deserialize a type from an archive that contains another type. Simply changing that: base* d20 = new ...
63,001,878
63,088,628
Access Violation when using SDL2_mixer effects?
I've been working on my own lib for 3D audio using SDL2_Mixer and DSPFilters by Vinne Falco. Currently i'm at the stage where i need to create custom DSP to filter audio, while SDL_mixer takes care of the registering of the effects, the actual DSP is proving difficult. SDL provides: void Effect(int chan, void* stream, ...
I'm pretty sure len is in bytes, not in float elements. You could use len/sizeof(float). – keltar This was the answer provided by keltar, which fixes the access violation. (It was provided on a seperate streamlined question)
63,001,903
63,002,813
Using smart pointers within multi-threaded application
I have some calculation I need to perform that is dependent on two or more steps as follows: class A { public: double step1() { return 2.5; } }; class B { public: double step2() { return 1.2; } }; class Result { public: Result(std::shared_ptr<A> _a, std::shared_ptr<B> _b) : a(_a), b(_b) {}; double ge...
Part of the problem you are having is that you are passing unique_ptr's around. But you have missed one move for the one that resides within your ResultFunctor class when trying to pass it into std::thread here: threads.push_back(std::thread(task, i)); If you have to use unique_ptr then you will most likely need a mov...
63,002,069
63,002,172
Down sides of abusing O(1) lookup of a hash table?
Hash tables are very common data structures used for coding problems presented in competitive programming/interviews. Hash tables take key value pairs so that you can lookup a key and get the value. However, I often find myself needing the O(1) lookup of a key and not really caring about the value. For example: If I ne...
You should use a data structure the way it's intended to be used. And then you can profile your code to see if the performance is adequate. If it isn't, then optimize bottlenecks. Having said that, a better data structure to check if a string has already been used would be std::unordered_set or std::set. Your use case ...
63,002,082
63,002,083
Why is my semaphore on a forked process not being released?
I have a problem with a POSIX semaphore being used to release a forked process. The forked process is started by calling another instance of the running process after a fork and exec. Sometimes the child is being released and other times it is not. It is a POSIX shared memory named semaphore and the weird thing is it w...
This problem was occurring ultimately because I was calling sem_unlink on the POSIX semaphore before doing a wait on it in the forked process. Calling sem_unlink causes the semaphore to be removed when all file descriptors have called sem_close on the semaphore. This, in essence, prevented my child process from being a...
63,002,163
63,012,388
How to rename container name in cryptoki
I have write some code that writes keypair of public and private key in a token. From the keypair, I create pkcs10 and later generate certificate file from it. The certificate file will be inserted to the token. It all run successfully, but somehow the certificate cannot being read by CAPI or Internet Explorer. If i in...
If your cryptoki library allow it, you can rename all the objects by setting new properties of them by calling C_SetAttributeValue function. In your case it can looks like this: CK_ATTRIBUTE atAttr[2]; atAttr[0].type = CKA_LABEL; atAttr[0].pValue = pLabelValue; // <-- pass here new Label val...
63,002,254
63,002,862
local installation of gcc in home directory
my question is: how do I make sure gcc automatically finds the right include files by default? what I did is compile gcc modules branch with --prefix=$HOME/.local and it worked. next thing to try it out with the next requirement: install "build2" with that new compiler. so I do PATH="$HOME/.local/bin:$HOME/.local/libex...
If you use GNU Make, you have to set some of the implicit variables: $ export CXX=/path/to/your/installation/bin/g++ $ export CC=/path/to/your/installation/bin/gcc $ export LDFLAGS="${LDFLAGS} -L /path/to/your/installation/lib64 \ -Wl,-rpath -Wl,/path/to/your/installation/lib64" where /path/to/your/i...
63,002,406
63,002,674
Why is nothing happening when I implement travel in my infectious disease simulation?
I have an issue with my infectious disease simulation. Here is the relevant code: void City::updateTravel(City &cityDestination) { vector<bool> travelArray; for (int i = 0; i < population; i++) { if (people[i].travel(cityDestination.getCity())) { travelArray.push_back(true); } ...
It seems to be a problem with how to define the counters of these loops: for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { if (i != j) { cities[i].updateTravel(cities[j]); } } } Try this: for (int i = 0; i < 2; i++) { for (int j = i+1; j < 2; j++) { if (i != j)...
63,002,438
63,002,644
Are there smaller Visual Studio 2015 C++ Redistributable (vcredist_x86.exe) than 14 MB?
I have a Windows x86 32 bit desktop application built using Visual Studio 2015 written in C and C++ using the MFC framework for the User Interface. For the installer I am using NSIS compiler with an NSIS script to generate the installation .exe used to install the application which is composed of some 10 different comp...
If I remember correctly, you may provide the required DLLs with your application rather than the installer. Another option is to go for static linking. These approaches will result in a much smaller overall size, but the dependencies will never be updated for fixes unless you do so. This may be a deal breaker or not de...
63,002,447
63,002,780
QLibrary: How to create two instances from one .so file?
QLibrary works fine to obtain one set of function pointers from one instance of an .so library. However, it does not work when trying to obtain two different instances of function pointers from the same .so file. Both sets of pointers point to the same locations in memory, making them redundant and not useful. Accordin...
The text you quote is the response: Multiple instances of QLibrary can be used to access the same physical library. Two instances: QLibrary loader1("lib.so"); QLibrary loader2("lib.so"); but the same physical library. So the functions are at the same memory location. Once the library is loaded, you use one library. ...
63,002,548
63,002,891
How to initialize class object that takes string as input inside another class
A class from a library that takes string needs to be initialized in my own class. Trying to do something like this, but gives me the error: expected identifier before string constant Class MyClass{ public: ClassA obj("some string"); } How can I properly do this?
Simplest thing is to do the initialization in the MyClass constructor, e.g. class MyClass { public: MyClass() : obj("some string") {} ClassA obj; };
63,002,903
63,004,073
Setting up an array of char using smart pointer and std::vector
I want to have an array of char[maxname]. My initial approach was the following class char_list { char_list(int noc){names_.reserve(noc)} std::vector<std::unique_ptr<char>> names_; void setname( const char* name){ names_.push_back(name)}; } When I try to invoke the routine by e.g. char aux[100]; aux = 'asad...
In C++ you shall banish char[] and arrays in general. Normally you are expected to use std::vector and in the case of string, use std::string. Vector grows & shrink automatically and do memory management for you. std::string does the same but is specialized for string management. So you code would look like: std::vecto...
63,003,062
63,003,301
What is the overhead cost for running a Python script via a shell command executed by C++?
I am using a Python script to handle part of a C++ program, but the process is going extremely slowly. I have a basic function for running shell commands and retrieving the output: std::string ShellCommand::RunShellCommand(std::string cmd) { char buffer[128]; std::string Response = ""; FILE* pipe = popen(cm...
The overhead is the following: popen() - It creates a pipe (low overhead) and starts a sh process (relatively expensive) sh - Parses the command line (low overhead) and starts a python process (relatively expensive) python - Parses and compiles the Python script (somewhat expensive) and executes the script. The 2nd a...
63,003,296
63,021,437
Unable to use stringstream to read in int and double
#include <iostream> #include <sstream>//for istringstream int main(){ std::istringstream iss; std::string tempSTR; int A; double B; std::cout<<"Please enter an int.\n"; std::cin>>tempSTR; iss.str(tempSTR); iss>>A; std::cout<<"A = "<<A<<"\n"; std::cout<<"Please enter a doubl...
`` #include <iostream> #include <sstream>//for istringstream //Using stringstream to read in multiple arguments int main(){ std::istringstream iss; std::string tempSTR; int A; double B; std::cout<<"Please enter an int.\n"; std::cin>>tempSTR; iss.str(tempSTR); iss>>A; iss.clear()...
63,003,338
63,003,488
Type determination when indexing on non-array pointers & reading beyond the last element
int main() { auto foo = new int; } I understand that foo will be of type int*. Since foo is a pointer you can index it with []. Therefore foo[0] will be the same as *foo and be of type int. What I'm having trouble with understanding is why foo[1] would be an int. I know c++ doesn't care that you go 'out of bounds'...
In this expression foo[1] there is used the pointer arithmetic. This expression is evaluated like *( foo + 1 ) The sub-expression foo + 1 has the type int * . So formally the full expression has the type int. That is the memory pointed to by the sub-expression foo + 1 is interpreted as storing an object of the type ...
63,003,465
63,087,564
finding leaks that disappear at exit
I'm developing a c++ program. This program seems to leak sometimes. Then it suddenly grows 2/3 times in size and keeps growing up to out of memory. "Run it in valgrind" you would say. I do, but the strange thing is that at exit, it shows leakage of "only" 0.5MB. Not the gigabytes I see using "top" (RSS). The program is...
valgrind provides various ways to track memory allocations that are later on deallocated. To see peak of memory, you can e.g. use the valgrind massif tool. To see which code allocates/deallocates a lot of memory, you can e.g. use memcheck option --xtree-memory=full and visualise the resulting file with kcachegrind.
63,003,772
63,022,124
missing arguments in __init__ when using using multiprocessing with a python object that uses a C++ class as base class
I have a class Node in C++ that I exposed to python using Boost/Python (yes, I know that Node is small but I translated it because some pretty big classes are derived from it). According to the boost/python documentation, I should be able to do this if I implement getstate_manages_dict. Here's the minimal amount of cod...
Figured it out: Seems like inheriting from C++ would break the pickle support that comes with pure Python classes. I needed to add the following methods in TestNode: __getinitargs__(self), __getstate__(self), __setstate__(self, state)
63,004,001
63,004,046
Is there any way to have struct-2 variables in struct-1, if struct-2 is declared after struct-1?
I'm having a set of points that are all part of the line segments. So I want to create a struct for the point, such that it will have a variable pointing to the line it is a part of. template<typename T> struct point{ int x,y; T* ln; }; struct line{ point U,L; }; point a; a.x = 1; a.y = 1; point b; b.x =...
You don't need templates, you just need a forward declaration. struct line; // this is a forward declaration struct point{ int x,y; line* ln; }; // ... a.ln = &seg1;
63,004,381
63,004,411
In class assign operator with std::unique_ptr,
I am having a problem with the operator= in my BitMap class. I was having some memory leaks so I decided to change from a raw pointer to a std::unique_ptr. When I did that, I noticed that whenever I use my BitMap assignment operator, I get an error: function "sp::BitMap::BitMap(const sp::BitMap &)" (declared implicitl...
You take the parameter of operator= by value, so this requires marged be copied into the argument as written. However, the implicit copy constructor is ill-formed since m_pixelMap cannot be copied. Instead, consider move-assigning since the local is going to be destroyed anyway: *this = std::move(marged); This move-c...
63,004,396
63,005,519
Initializing captured-by-reference variable in C++ lambda?
I have this C++ function object: static unsigned long long const FNV_OFFSET_BASIS = 14695981039346656037ul; static unsigned long long const FNV_PRIME = 1099511628211ul; struct fnv_hash { typedef unsigned long long value_type; fnv_hash( value_type *result ) { _result = result; *_result =...
You say the fact you can use std::accumulate is only for this specific example, but I'm skeptical. The only real difference between std::for_each and std::accumulate is that std::accumulate makes state explicit, including handling initialization. I think it is the solution in all cases. static unsigned long long const ...
63,004,404
63,008,805
Why is the 'simplified' code not vectorized
I implemented the following code which converts 32 bytes of input to uppercase: Version 1: void to_upper(char* input) { for (int i = 0; i < 32; ++i) { input[i] = (input[i] >= 'a' && input[i] <= 'z') ? input[i] - 32 : input[i]; } } Version 2: void to_upper(char* input) { for (int i = 0; i < 32; ++...
Basically optimization passes have harder time recognizing the conditional assignment in second loop. In first case GCC generates a slightly different intermediate representation which allows if-conversion pass to convert code to vectorizable form: <bb 3>: # i_18 = PHI <i_14(4), 0(2)> # ivtmp_24 = PHI <ivtmp_21(4...
63,004,841
63,004,897
C++: Move a particular number to the back, using vector
I have the following given vector: vector<int> arr = {2,1,2,2,2,3,4,2}; The goal is to move a target number all the way to the back. Say target is 2, then final result should be something like: arr = {1,3,4,2,2,2,2,2} Attempt My approach is to loop through the vector, then if I find a 2, I would use push_back to ad...
You can do this easily by using std::stable_partition: std::stable_partition(arr.begin(), arr.end(), [toMove](int i) { return i != toMove; });
63,004,961
63,005,267
Using Composite Pattern to make game menu
I'm making a game menu using a composite pattern. I want to achieve a tree structure game menu, where some leaves are pushing new state on the top of my state machine and another in options should show for example slider to change the volume without making new state and another (exit) should close the game by running s...
Here is an example of a menu state table using a struct: typedef void (*Function_Pointer)(); // Declares a synonym for Function_Pointer struct Table_Entry { char expected_selection; char * prompt; Function_Ptr processing_function; }; // Forward declarations void Turn_On_Lights(); void Turn_Right(); void ...
63,005,033
63,005,251
Python: Is there a way to filter through c++ files?
I'm currently writing a python script that searches through the company codebase to make a large list of .cpp and .hppfiles. A few of these files contain only comments and preprocessor directives. Is there a way to identify and filter out these files? Thank you
You would have to read the contents of the file f = open("path/to/file") contents = f.read() f.close() Hopefully, these files contain some sort of marking that will make them easy to find - something in the header say. if "indicative marker" in contents: # Label file Since they are only comments and preprocessor ...
63,005,412
63,005,491
How do templates avoid infinite recursion?
I am currently following this tutorial on SDL2, and have come across templates, which are entirely new to me at this point. template<typename T, typename... Args> void cleanup(T *t, Args&&... args){ cleanup(t); cleanup(std::forward<Args>(args)...); } template<> inline void cleanup<SDL_Window>(SDL_Window *windo...
cleanup(T *a, Vars&&... b) If you passed n vars to this function, the first one would go tho the first function in the body (which ends. note that there is no inner calls). And the rest n-1 would go to the second function in the body and this would call a function again but using n-1 vars. This process would continue ...
63,005,675
63,005,712
Can I use C++20 ranges to break when matched count is greater than some threshold?
Consider the following pre ranges code: std::vector<int> v(1000*1000); bool count_gt_5_v1(int val){ return std::count(v.begin(), v.end(), val)>5; } It looks nicer than the raw loop, but it can be very inefficient if val is very common in v. Is there any way to use C++20 ranges so that iteration will stop after I e...
You could do this: auto matches = v | rv::filter([=](int i){ return i == val; }) | rv::take(6); return ranges::distance(matches) == 6; Or, better: auto matches = v | rv::filter([=](int i){ return i == val; }); return not ranges::empty(matches | rv::drop(5)); This attempt: std::ranges::views::take_wh...
63,005,702
63,005,760
C++ How do i get a pointer to a class' virtual function table?
Given: Example.h struct Base { virtual ~Def() = default; virtual void accept(struct DerivedVisitor* v) = 0; }; struct Derived : Base { int num; void accept(struct DerivedVisitor* v) override; }; struct DerivedVisitor { virtual void visit(Derived* d) = 0; }; Example.cpp #include "Example.h" void...
Is this compiler specific? Yes, this is compiler specific. There is no such thing as a "virtual function table" in the C++ language. Such table is an implementation detail. Given that such table doesn't exist in the language, there is also no way to get a pointer to the table in standard C++. Assuming your compiler h...
63,005,852
63,006,938
Pthreads: shared memory monitor design
I'm doing an assignment where we are creating 4 threads that all share some memory. Just want to ask if the design of my monitor looks good, since I'm having a deadlock/ stalling somewhere in my code when I try to cancel all threads. Previously, I have identified the stalling to threads locking up the mutex when they a...
Do not use thread cancellation if you can possibly help it. It has deep problems associated with it. To break threads out of a pthread_cond_wait(), use pthread_cond_signal() or pthread_cond_broadcast(). Or use pthread_cond_timedwait() in the first place and just let the timeout expire. "But, wait!" I imagine you sayi...
63,006,070
63,028,966
How to create a ROOT Histogram from a large file containing two columns of data? I only want to create a histogram from one column of data
This is my code. Please let me know if there is a way to make the histogram without changing the code significantly. Additionally, let me know the easier way as well. Thank you. { TFile *f = new TFile("Data.root", "RECREATE"); TNtuple *t = new TNtuple("current_data", "Data from HV", "Unix:Current"); t->ReadFile("NP02_H...
Your code is not so far off. Like @PaulMcKenzie wrote there's no need to do dynamic allocations (though they are common in root usage code and prevent things from going out of scope while they are implicitly still needed ...) The creation of the TFile and t->Write() seem superfluous for just creating and plotting the h...
63,006,589
63,026,990
Interaction of fno-exceptions and POSITION INDEPENDENT CODE
I ran into a rather bizarre issue while building a dynamic library. Here are details with a small example: A simple file called static.h whose contents are: #pragma once #include <string> std::string static_speak(); static.cpp looks like this: #include "static.h" std::string static_speak() { return "I am static";...
How are exceptions and fPIC related to each other? They aren't (mostly). What happens is that compiling with -fno-exceptions changes the relocations (certain exception-related data is no longer referenced), and because of that, there is no relocation which causes the error at link time. You can confirm this by buildi...
63,006,828
63,006,856
C++11 template: How to ensure that the type inherits a class?
In Java generic, when I want to ensure that the type of some generic class must inherit a class, I can code as below: public class MyHandler<T extends Serializable> {} This means that T must extend/implement the class/interface Serializable, otherwise, the compiler will generate an error. How to get the same thing in ...
You can use std::is_base_of for checking. template<typename T> class MyHandler { static_assert(std::is_base_of<boost::archive::text_oarchive, T>::value, "T must inherit boost::archive::text_oarchive"); }; Since C++20 we can use constraint, e.g. template<typename T> requires std::is_base_of_v<boost::archive::text_...
63,007,211
63,007,674
2 to the power 2 n times incorrect
Please tell me what is wrong, the output is wrong, shows 4 to me F​1​ = 2, F​n​ = (F​n-1​)​ 2​ , n ≥ 2 i. What is the complexity of the algorithm that computes ​F​n using the recursive definition given above. #include <iostream> using namespace std; double calcFn(double,int); int main() { ...
First of all, You have recurrency, so you should not use the loop. Secondly, You do not assign return value. The corrected snippet: if (N > 0) { N--; Fn = calcFn(Fn, N); } Still, I'm not sure about the result, but You can further correct it.
63,007,241
63,007,295
Can't figure out syntax of template nested class in my c++ program
In my c++ program there is situation that I have a nested template class name outer and it holds a method get() which returns inner class pointer. I need to implement this get() method outside the outer class but i can't figure out the syntax for calling get() method. suppose : template<typename T> class outer{ cla...
Your issue is unrelated to this being a template class. The visibility of inner is inside outer, and you must therefore provide that scope when you specify it. template<typename T> typename outer<T>::inner* outer<T>::get(){...}
63,007,505
63,009,361
Using libtins to recreate IP packet change its header
I have a uint8_t* buffer which I get by doing buf.data(). It's a buffer of an IP packet. I want to change the source address and recalculate the checksum, so I recreated the packet in libtins by doing what you see below: //prints original packet for (size_t i = 0; i < buf.size(); i++) { printf("%x ", buf.data()[i...
With the sample IP packet you have provided, I've done the following: uint8_t ip_packet[] = { 69, 0, 0, 52, 0, 0, 64, 0, 64, 6, 107, 83, 192, 168, 69, 1, 172, 217, 28, 238, 0, 112, 0, 80, 0, 0, 0, 0, 0, 0, 0, 0, 128, 2, 253, 232, 164, 253, 0, 0, 2, 4, 5, ...
63,007,678
63,007,712
How do I upgrade to C++17?
I am using Atom as my IDE, my current __cplusplus = 201402 which is C++14 and my compiler is g++ (GCC) 9.2.0. How do I upgrade to C++17 or C++20? Everything I've searched up involves using another IDE (Microsoft Visual Studio).
You don't "upgrade" to newer C++ standards. You can upgrade compiler to newer version supporting latest standards. As of today, most compilers are set to C++14 by default. To change it you need to pass additional argument during compilation. For example, to compile hello.cpp with GCC for C++17 you need to execute g++ -...
63,007,760
63,009,396
Is there any possible way to extract the states of variables which causes the desirable execution path in a multi branch c program
Consider the following code: //global variables int x, y, z; // function prototypes void updateGlobalVariables(void); void func1(void); void func2(void); void func3(void); void func4(void); int main() { //changes the global variables updateGlobalVariables(); if (x > 10) fun1(); else if (x<10 && y>10) fun2();...
I'm not entirely sure this does what you need but you could create a class that holds references to your global variables that you instantiate at the start of each function (using a macro). It can then print the function name and the variable varlues when entering and exiting the function. It can also use a depth count...
63,009,250
63,009,431
What actually happens when copy initializing in C++?
Consider the following code: #include<iostream> using namespace std; class A{ public: A()=default; A(int a){cout<<"A(int) called"<<endl;} A(const A&a); ~A(){cout<<"~A() called"<<endl;} }; A::A(const A&a){ cout<<"A(const A&) called"<<endl; } int main(){ A a = 1; } When I use g++8.1 to compile with -fno-eli...
The effect of copy initialization here is, (emphasis mine) If T is a class type, and the cv-unqualified version of the type of other is not T or derived from T, or if T is non-class type, but the type of other is a class type, user-defined conversion sequences that can convert from the type of other to T (or to a type...
63,010,536
63,010,819
Why does cmake return an error when i build my c++ code?
I want to start learning OpenGL, so I learnt some C++, installed CLion (JetBrains IDE), and tried to make everything work. I work on Ubuntu 20.04. I checked that freeglut and OpenGL are installed, I don't know what else to do. This is the CMakeLists.txt file: cmake_minimum_required(VERSION 3.16) project(OpenGlmessing) ...
You might need to remove "$" inside target_link_libraries target_link_libraries(OpenGlmessing ${OPENGL_LIBRARIES} ${GLUT_LIBRARY})
63,010,614
63,012,786
Including SDL in program makes it have no output and instantly quit
I'm trying to make a program with SDL2.0 but the program doesn't show any output and it quit instantly. I am using Windows 10 x64 and I am doing this on VSCode, latest CMake version. I actually tried amd64, amd64_x86, x86, x86_amd64 toolchains, same thing happens. A normal hello world program worked well but when impor...
Solution found here. I should copy the sdl libraries under the target executable directory.
63,010,719
63,011,859
Storing variadic parameter and callback for later usage
I want to create a simple but generic callback with variadic parameters. I also need storing them, because callback will called later in time (from a different thread which uses the storage). Here's what I have until now: #include <iostream> #include <string> using namespace std; void fileMgr_DoneWithOtherstuff_DoThe...
First of all, relying on a global variable is not a really good idea, because it will give wrong results if you call readFile while a previous read is still in progress. So you really should encapsulate that whole reading process in a class. You need to use a lambda or std::bind because the parameters of callback are n...
63,010,740
63,015,021
Referencing in Operator Overloading
I'm new to the concept of operator overloading and I've just implemented a program to overload the assignment operator using a class. Here's the code I've implemented: #include<iostream> using namespace std; class Test{ private: int id; string name; public: Test():id(0),name(""){ ...
In short, const Test &operator= will give access to your object by reference. In the second case, const Test operator= will be creating a copy of your object and assigning this new object to the output variable, which is not necessary in most cases. It is done via the copy constructor. The const keyword will force the ...
63,010,795
63,010,923
My C++ attempt to convert std::vector<std::string> to JSON doesn't compile
I am trying to port a program I've written in JavaScript to C++ to make it faster. In that program, I dealt somewhat with JSONs. So, I tried to make a method for converting a vector of strings into JSON: #include <iostream> #include <vector> #include <string> class std::vector<std::string> { public: std::string JS...
First, the class std::vector<std::string> does not make sense. Second, a class is not necessary since you can just define a function similar to your member function that takes in std::vector<std::string> and return the json string. For example: #include <iostream> #include <vector> #include <string> std::string JSON(s...
63,010,865
63,011,485
terminate called recursively c++ multithreading
I am new to threading, and I face the situation that confuses me ,I try to throw exception inside the function that I put in thread and at main() function I have a try and catch block,However I still get these error : 1. terminate called after throwing an instance of 'char const*' 2. terminate called recursively Below ...
To elaborate a bit on @DeltA answer: Instead of working with std::thread and passing the exceptions with pointers, you can use std::future because it stores the thrown exceptions in its shared state: void AccumulateRange(uint64_t& sum, uint64_t start, uint64_t end) { for (uint64_t i = start; i < end; ++i) { ...
63,011,027
63,011,172
CMake Error: Unable to find package GTest
I am developing a C/C++ app using CMake. I want to use GTest in my project for unit testing. For this I have decided to use GTest as a git submodule in my repository. My directory hierarchy is as follows: / --include --lib --GoogleTest --src --Tests The GoogleTest subdirectory in lib contains the source code of GTes...
You don't have to manually download the Gtest git. Just add the following lines to your CMakeLists.txt # -------- GOOGLE TEST ---------- # Download and unpack googletest at configure time configure_file(CMakeLists.txt.in googletest-download/CMakeLists.txt) execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}...
63,011,099
63,011,226
C++ Passing lambda as function parameter with argument list
At the moment I'm trying to build something like a Java-like forEach in a class where I pass a lambda and it gets called for every item. At the moment I've implemented it like this: Foo.h class Foo { public: Foo(); void forEach(void(*lambda)(Bar*)); private: SpecialList mElements; }; Foo.cpp #include "Foo....
A lambda is not a function pointer. If it has no captured objects, it can be implicitly converted to one, otherwise it cannot. A lambda has a anonymous type, so if you want to use the type directly, you need to use templates: template<typename Callable> void Foo::forEach(Callable lambda) { for (auto& v : mElements)...
63,011,115
63,011,217
Is `delete ptr;` necessary in destructor even when memory is not dynamically allocated?
I have created the following class : class Deep { private : int *ptr; string name; int age; double marks; public : Deep() : ptr {&age}, name {"Mandeep"}, age {20}, marks {85.3} { cout<<"Deep Constructor Called for : "<<name<<endl; } ~Deep() { delete ptr; cout<<"Destru...
delete operator can only be called on objects allocated with new. If you haven't allocated new memory, you cannot call delete operator. Take the following example: int main() { int a = 20; int* ptr = &a; delete ptr; return 0; } If you compile this code, it surprisingly(??) compiles without warning. How...
63,011,557
63,011,716
Segmentation Fault when trying to copy string from one to another at particular lengths?
#include <iostream> using namespace std; int main() { string s,s_new; cin>>s; int len=s.length(); cout<<len<<"\n"; for(int i=0;i<len;i++){ s_new[i]=s[i]; } cout<<s[len-1]<<"\n"; cout<<s_new[len-1]; return 0; } I am trying to copy string 's' to another string 's_new'. String 's' is take...
s_new[i]=s[i]; has undefined behavior since s_new.size() == 0. You need to resize it to do what you are doing: s_new.resize(len); for(int i=0;i<len;i++){ s_new[i]=s[i]; } for a particular length this program is creating segmentation fault in various IDE Writing out-of-bounds always has undefined behavior. In th...
63,011,700
63,011,890
How pointers of base class are used to form derived class object?
There was this question in my quiz. Can you explain it? Pointer to a base class can be initialized with the address of derived class, because of ______. The correct answer was 'derived-to-base implicit conversion for pointers'. I have some questions related to this code: #include <iostream> using namespace std; clas...
Is it a base class object or a derived class object A derived class object was created dynamically. That is the dynamic type of the object. The derived object contains a base sub object. d1 points to the base sub object. That is the static type of the pointer. d1->~Base(); This is bad for two reasons: The behavio...
63,011,784
63,012,787
Why std::string append is not overloaded on rval ref?
I'm familiar, that the append in std::string returns std::string& and therefore it do not qualify to be moved from, so the result will not be moved. #include <string> int main() { std::string s = std::string("A").append("B"); return s.size(); } https://godbolt.org/z/M63aWW #include <string> int main() { ...
As is covered in P1165R1, the rules for allocator propagation for basic_string’s operator+ are complex and a root of inconsistencies over different library implementations. Make stateful allocator propagation more consistent for operator+(basic_string) [...] Allocator propagation for basic_string’s operator+ is haphaz...
63,011,871
63,011,980
Returning a Derived pointer from a virtual function
class Base { public: // This version of getThis() returns a pointer to a Base class virtual Base* getThis() { std::cout << "called Base::getThis()\n"; return this; } void printType() { std::cout << "returned a Base\n"; } }; class Derived : public Base { public: Derived* getThis() override { std::cout...
When calling b->getThis()->printType(); why b->getThis returns a pointer to Base ? Because b is a pointer to Base. And the type of the pointer returned by Base::getThis is pointer to Base. not to Derived ? Because Base::getThis does not return a pointer to Derived. Note that while the static type of the pointer is ...
63,012,318
63,013,191
Error triggered when reading structured values
I'm trying to figure out why this code from "Programming Principle and Practice using C++" triggers the error ("bad reading"): #include "D:\std_lib_facilities.h" /* get it from: https://github.com/ltr01/Programming- _Principles_and_Practice_Using_Cpp/blob/master/std_lib_facilities.h */ struct Reading { int day; ...
If you put two conditions to check for input stream and character read you will see the error: if (!is) { cout << "Finished" << endl; return is; } if (ch2 != ')') { // the istream it's not good cout << "Readed: " << ch2 << endl; error("bad reading"); // messed-up readi...
63,012,580
63,012,652
How would I search an element in a vector string?
I'm trying to search a vector string for certain words. For example, vector<string> sentences = ["This is a test string","Welcome to C++!"]; string searchString = "This"; I tried if (std::find(sentences.begin(), sentences.end(), searchString) != sentences.end()) { cout << "Found!"; } else { cout << "Not Found!...
for(std::string& s : sentences) { if(s.find(searchString) != std::string::npos) { //substring found } else { //substring not found } } this should work for looking for a word in each string in the vector
63,012,818
65,831,544
How to load multiple font of same familiy
I am writing an application using the Qt framework. In the display, I have to show multiple information, but using different types of font of the same family, Montserrat. What I have done so far to load the fonts is: int ultralightid = QFontDatabase::addApplicationFont(":/Montserrat_UltraLight.tff"); QString UltraFont=...
This is an old question but I was just struggling with exactly the same problem when trying to load normal, bold, ... versions of a font family in Qt. I solved the problem (although in a somewhat hacky way) by simply giving each of the ttf files a different family name. I used Typograf, simply open the font, right clic...
63,013,037
63,375,091
MinGW: winpthreads overrides .rc resource file information
My MinGW project uses the boost library and indirect pthreads. I created a .rc resource file for my project, containing version information and more. To static link my executable, I use the parameters: -static-libgcc -static-libstdc++ -Wl,-Bstatic,--whole-archive -lpthread -Wl,--no-whole-archive Sadly, pthread overwrit...
This seems to be a drawback of including all the archive (--whole-archive): -Wl,-Bstatic,--whole-archive -lpthread -Wl,--no-whole-archive (in the libpthread.a, there is a version.o containing a compiled VERSIONINFO resource) But including the whole archive is useful for linking statically the libpthread.a (i.e. not hav...
63,013,047
63,013,736
Segmentation Fault when assigning value to a pointer C++
When I run the following parallel code I get a segmentation fault at the assignment at row 18 (between the two prints). I don't really understand what is causing. This is a minimal working example which describes the problem: #include <iostream> #include <numeric> #include <vector> #include <thread> struct Worker{ ...
In addition to the vector synchronization problem mentioned by Sam, there is another problem. This line: threads[i] = std::thread([&]() { W[i]->f(); } ); captures i by reference. There is a good chance that i goes out of scope (and is destroyed) before the thread starts running. The statement W[i]->f(); is likely to r...
63,013,137
63,014,875
Unexpanded parameter pack in function signature
Newer GCC introduced a new builtin __integer_pack to help it implement std::make_integer_sequence and friends. For Reasons(tm), I am unable to use this function, so I'm trying to reimplement it (and then use #define to replace the standard library usage) It's used in the form __integer_pack(N)..., which expands its "re...
No, this is not possible. __integer_pack is not a function, it is a placeholder that is expanded by the compiler into a parameter pack. This is not something you can replicate within the language. You can look at how gcc implements replacing the call to __integer_pack with its expansion in gcc/cp/pt.c, starting at line...
63,013,825
63,014,093
Does linker link an object file with itself?
From what I read in other SO answers, like this and this, compiler converts the source code into object file. And the object files might contain references to functions like printf that needs to be resolved by the linker. What I don't understand is, when both declaration and definition exist in the same file, like the ...
It depends. Both options are possible, so are options that you didn't mention, like either the compiler or the linker rearranging the code so that none of the functions exist any more. It's fine thinking about compilers emitting references to functions and linkers resolving those references as a way of understanding C+...
63,014,028
63,014,211
Summoning and Displaying a text file, inside a menu function
I'm quite new to C++ and my assignment is pretty tough. I must create a menu (in which I'm struggling quite badly), not only that but I should also read and display a textfile. So far, the only method I used only displays the first lines of the text file. Can you help me out? Thanks in advance. The break function when ...
So far, the only method I used only displays the first lines of the text file That is because you close the file after reading the first line: while (getline(inFile, ABOUT)) { cout << ABOUT << endl; inFile.close(); // <------ here !! } You do not need to clos...
63,014,671
63,015,732
C++ template variable specialization with GCC 5.4
I have come across a strange error in the CI build of a project I'm working in. This only happens on a relatively old OS (Ubuntu 16.04) with a not-so-recent compiler (gcc 5.4.0). The code causing the error is similar to the following: (https://godbolt.org/z/MhY6sv) #include <limits> #include <string> #define DEFAULT_I...
We may minimize the OP's overly bloated example into: template <typename T> struct A {}; template <typename T> const T defaultValue = 0; template <typename T> const A<T> defaultValue<A<T>> = A<T>{}; struct S { S() : a1{defaultValue<decltype(a1)>}, a2{defaultValue<decltype(a2)>} {} A<char> a1; A<...
63,014,768
63,015,223
How to convert uint32_t number to char[8]?
Suppose we have a string s = "453acd0f". Now I want to do something like this: uint32_t res = 0; for (size_t i = 0; i < 8; ++i) { res |= ConvertCharToHexNumber(s[8 - i - 1]) << (i * 4); } But how I should do this if I have a uint32_t var variable which I read from a binary file?
The simplest way to convert a 4 byte uint32_t into char[8]: uint32_t var = 100; char res[8]{}; res[0] = (var >> 28) & 0XF; res[1] = (var >> 24) & 0XF; res[2] = (var >> 20) & 0XF; res[3] = (var >> 16) & 0XF; res[4] = (var >> 12) & 0XF; res[5] = (var >> 8) & 0XF; res[6] = (var >> 4) ...
63,015,173
63,015,601
std::enable_if is generating error when used on functions of same name inside a template class
Problem description I am trying to call a function that returns 1 or 2 depending on whether the type is signed char or unsigned int. For this purpose, I wrote the following code. If I compile the code without the code inside the main. I get no compilation error. But when I compile the code with the instantiation of an ...
Like @Evg mentioned you have to need the member function to be templated as well. In addition, you need to provide default values for them, like usual nullptr defaulting. See a demo #include <iostream> #include <type_traits> template<typename T> class Coverage { public: Coverage(T type) :_type(type) {} //signed...
63,015,664
63,016,130
Use QProcess to Start Another exe and Generated file with Wrong Path
I met a question recently. I use QProcess class to start B.exe in A.pro. The absolutely path of A.pro is C:/QT/A/A.pro. I use windeployqt to package B.exe, and put the package folder in C:/QT/A/B/B.exe. In B.exe, the program will generate a file named test.json. The test.json's path is the same as B.exe. But I use foll...
If you look into QProcess::startDetached, it reads as follows: The process will be started in the directory workingDirectory. If workingDirectory is empty, the working directory is inherited from the calling process. You need to set working directory for QProcess. When you run B.exe by "double clicking" it. Your OS s...