question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
70,702,698 | 70,702,849 | Is std::move required to move using co_yield? | Say I have a std::vector that is declared in a loop's body and co_yielded:
some_generator<std::vector<int>> vector_sequence() {
while (condition()) {
std::vector<int> result = get_a_vector();
result.push_back(1);
co_yield std::move(result); // or just: co_yield result;
}
}
Quite obviou... | The implicit move rule ([class.copy.elision]/3) applies to return and co_return statements and to throw expressions. It doesn't apply to co_yield.
The reason is that, in the contexts enumerated in [class.copy.elision]/3, the execution of the return or co_return statement or throw expression ensures that the implicitly ... |
70,702,860 | 70,702,980 | C++ class size template deduction | I have the following function:
template <uint8_t N1, uint8_t N2, uint8_t N3>
Shape<N3> func(const Shape<N1> &shape1, const Shape<N2> &shape2)
{
return Shape<N3>();
}
Definition of Shape:
template <uint8_t N> class Shape;
Is there a way to deduce N1 and N2 by the Shapes passed to the function?
Shape<3> shape1 = {1... | You should arrange your template parameters so that the ones that need to be explicitly specified are at the beginning, and the ones that can be deduced from the arguments are at the end:
template <uint8_t N3, uint8_t N1, uint8_t N2>
Shape<N3> func(const Shape<N1> &shape1, const Shape<N2> &shape2)
{
return ...;
}
... |
70,702,875 | 70,703,229 | How can I iterate through a vector to generate new objects? | I've generated a vector from a relatively large CSV file and need to make objects out of each row. Problem is, there are 102 columns, so manually writing the object parameters is out of the question.
Data colNames;
for (int i = 0; i < 1; i++) {
for (int j = 0; j < content[i].size(); j++) {
string column = ... | Have you looked at std::vector?
A row is a container of columns. The container to use is std::vector.
We'll use two structs: Data_Headers and Data_Rows:
struct Data_Headers
{
std::vector<std::string> column_headers;
};
struct Data_Rows
{
std::vector</* data type */> column_data;
};
You can access the row's d... |
70,703,574 | 70,703,957 | US phone number verification in QT Creator | I am having a hard time getting a verification system for a US phone numbers working.
Please note that I am a self studied 'dev' that is just trying some things for curiosity and that my knowledge is very limited
okay so as mentioned i am trying to validate a US phone number from a LineEdit, the number should be in the... | I got this working using a site that someone on discordd suggested:
https://ihateregex.io/expr/phone/#
turns out my REGEX
("^\\+?(1 |)[0-9]{3}+(-|)[0-9]{3}+(-|)[0-9]{3}+(-|)[0-9]{4}$")
has one to many
[0-9]{3}
iterations... and these where also stated incorrectly:
+(-|)
after some testing I got this to to work for m... |
70,703,592 | 70,704,006 | Iterate over keys in map from largest length to smallest length | I am trying to iterate over all keys in a map. I have this code:
map<string, array<string, 3>> dat;
array<string, 3> dt({ "var","TEXT","" });
dat["atest"] = dt;
array<string, 3> at({ "var","DATA","" });
dat["testplusalot"] = at;
array<string, 3> t({ "var","NONE","" });
dat["testalot"] = t;
for (const auto& p : dat) {
... | Since you want to order the keys by length, and then if the lengths are the same, order them alphabetically (the simplest fall-back ordering), then the following can be done:
#include <map>
#include <string>
#include <array>
#include <iostream>
// Create a type that describes the sort order
struct strCompare
{
bo... |
70,703,713 | 70,703,779 | Qt C++, connect class instance signal to Widget main class | My code contains a function which takes a lot of time to compute. To make it feel more responsive, I wanted to visualize every tenth of the progress with a progress bar. However, the function is implemented in another class other than my Main Widget class and I cannot access the ui elements of the Widget class. I tried... | Hard to say without the minimal example, but I guess the problem lies in your call to connect:
connect(Dataset::calculateNew(), SIGNAL(valueChanged(int)), this, SLOT(updateProgressBar(int))); //second Error here
Provided your dataset object is called ds, it should look like this:
connect(&ds, SIGNAL(valueChanged(int)),... |
70,703,927 | 70,713,195 | C/C++ getnameinfo ai_family not supported only on macOS | the following code does not work on macOS anymore if IPv6 or some virtual interfaces are available.
i got always the error getnameinfo() failed: Unknown error (ai_family not supported)
any idea whats wrong with this? i only need a correct network interface with ipv4 and internet.
The problem first appeared with macOS S... |
i got always the error getnameinfo() failed: Unknown error (ai_family not supported)
Based on the origin of that message in your code, it seems clear that it arises from a case where
s2 = getnameinfo(ifa->ifa_netmask, sizeof(struct sockaddr_in), subnet, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
fails with erro... |
70,703,967 | 70,718,514 | Is $ORIGIN/lib a reasonable RUNPATH for libraries? | Background
I have a third-party library that has this structure:
lib
βββ liba.so
βββ libb.so // libb.so is NEEDED by liba.so
Both have their RUNPATH set to $ORIGIN/lib and liba.so depend on libb.so.
In my first-party project I have the following structure:
bin
βββ liba.so
βββ libb.so
βββ myexecutable
where myexe... |
If .so-files from the same third-party library are expected to live side-by-side in some directory, in presence of NEEDED inter-dependencies, mustn't the .so-files with dependencies on other .so-files always have $ORIGIN in their RUNPATH?
Yes.
The 3d party vendor who built them with RUNPATH of $ORIGIN/lib didn't know... |
70,704,458 | 70,704,499 | std::thread::hardware_concurrency() does not return the correct number of Logical Processors in AMD Ryzen threadripper 3990x | I am using thread library in different machines (including Linux and Windows, and also both Intel and AMD CPUs and with clang++, GNU and MSVC). in all of them, std::thread::hardware_concurrency() returns what is called Logical Processors in Windows or the maximum number of threads including the hyper threads, however i... | The idea of std::thread::hardware_concurrency is to tell you what kind of concurrency std::threads can experience. Since std::thread can only put threads into your default processor group, you will get the number of logical processors in your default processor group. This is not going to be greater than 64 on Windows u... |
70,704,513 | 70,706,652 | How to get a list of available resolutions for every camera on Windows C++ | I have multiple cameras in my Windows 11 system and I am wondering how to get all avaiable resolutions for them. I am not intending to make a video capture, but I am willing to just get these properties.
Also, I don't care which API to use, be it DirectShow or MMF (Microsoft Media Foundation).
I haven't used any of the... |
Also, I don't care which API to use, be it DirectShow or MMF (Microsoft Media Foundation). I haven't used any of these before either.
You generally do care because the data might be different.
With Media Foundation, see How to Set the Video Capture Format
Call IMFMediaTypeHandler::GetMediaTypeCount to get the number... |
70,704,526 | 70,704,577 | Swapping Polymorphic Objects | I have a base class A and derived class of B. What I want to be able to is to swap the objects they point to. Applying std::swap on the underlying base objects of the pointers only swaps the base object contents and not that of the derived object as well. How do I fix that to get std::swap to work properly.
#include <i... | In the example, you have two A* variables (misleadingly) named a and b, both pointing to B objects. You want std::swap(*a, *b) to swap the full B objects. If you had a way to do it, what would you want it do if a was actually pointing to an object of type A?
You cannot swap A and B because the objects have different si... |
70,704,890 | 70,808,634 | ranges::views::enumerate capturing by reference or by value? How can we tell? | In the following code, auto [i, e] and auto&& [i, ee] both bind std::pair<int, T&> rather than std::pair<int, T>. Could some explain how could have known this without testing empirically? I assume it's the range-v3 implementation. Is there a case where you would want to use auto&& rather than auto?
auto container = std... | Edit: use static_assert(std::is_reference_v<decltype(variable_name)>);
I was confused because typically in the ranged for loop when the * operator is called on the iterator it returns a T&, so you must add a ref-qualifier to get a reference rather than a copy.
for(auto& el : container)
---------------
auto& el = *it;... |
70,705,614 | 70,706,209 | Iterator(of a vector or string) minus n (iter - n) for c++ | Some detail description for my question:
Create an iterator of vector or string in c++ 11.
Do iterator arithmetic, iterator minus n
Question: Will c++ 11 keep the iterator minus n bigger than begin()? (if n is big enough, will the compiler ensure that the iter - n do not exceed the legal range of iterator?)
| According to cppreference, iter - n is effectively the same as:
vector<T>::iterator temp = iter;
while(n--) --temp;
return temp;
Assuming iter was a iterator from a vector named container. If n is larger than distance(container.begin(), iter), then at some point from the last while loop, --temp would be equivalent of:... |
70,705,821 | 70,706,491 | partial template specialization for non type member function pointer values | I would like to partially specialize a structure for a non-type template parameter, specifically for member function pointers known at compile time.
As an example, I start with int and non int values and that works fine and prints
false true
but when I un-comment adap, I get the following compile error
callable.cc:9:3... | When you create a partial specialization for a template, you have to provide template argument(s) to the primary specialization that signal when your partial specialization should be used. The primary template for adap takes a non-type template parameter: a value. So your partial specialization needs to provide a value... |
70,705,831 | 70,705,863 | Risks of upgrading VC2019 projects from C++14 to C++17 | We have a legacy system that contains around 30 VC++ projects that are currently set to C++14. To support a new requirement we have had to update one of the projects, a library project shared across most of the others, to C++17.
I'm aware of the VC++ 2017-2019 upgrade docs, but what about the language change itself fro... | The binary doesn't care what was the syntax of the original text from which it was created. If you're using a binary .lib file in all your other projects - it doesn't matter if it was compiled in C++14 or C++17 mode to them. So in that regard there's no dependency.
So you should be able to change the settings of only t... |
70,706,152 | 70,706,384 | Question regarding Static Initialization Order Fiasco | I am currently going through the old version of Nicolai Josuttis' book on C++ templates. My question is regarding the initialization of static data members of the SortTracer as implemented here.
Specifically, in tracer.hpp, we have:
class SortTracer {
private:
int value; // integer value to be sort... | All global variables (including class-level statics) are guaranteed to be initialized before main(). The order in which they are initialized between different source files is undefined.
Global Initialization Order Fiasco refers to the situation where global variables in one file are initialized with global variables fr... |
70,706,645 | 70,736,093 | QMediaDevices::videoInputs() does not list OBS virtual camera as avaliable on Windows | I'm writing an application that takes in input from webcams and does some image processing on it. Currently I use Qt for the video capturing and display. I get the list of available cameras using QMediaDevices::videoInputs().
However, this function seems does not support OBS virtual camera. The following code should du... | Over the weekends. I read the Qt6 change logs and found that they dropped DirectShow support. While OBS Virtual Camera is DShow only. OBS Virtual Camera can only work in Qt once they support Media foundation.
|
70,706,698 | 70,706,819 | C++ casting char into short | Pardon me for this newbie question. I recently found that a strange thing when casting char into short. Basically, if the char is overflowed, when casting into short the binary number is prepended with 11111111. If the char is not overflowed, it will be prepended with 00000000.
For example,
char a = 130;
short b = (sho... | Read up on: 2's complement for how negative numbers are encoded in binary.
In a signed char, assuming an 8-bit char width and 2's complement arch, a char can hold a value between -128 to +127.
When you say:
char a = 130;
That's out of range.
130 as integer in 32-bit binary is: 00000000 00000000 00000000 10000010
In H... |
70,706,712 | 70,706,834 | How is OutputIterator related to std::back_inserter and std::ostream_iterator? | While looking at std::copy_if details at here, the 3rd argument is an OutputIterator.
template <class InputIterator, class OutputIterator, class UnaryPredicate>
OutputIterator copy_if (InputIterator first, InputIterator last,
OutputIterator result, UnaryPredicate pred);
I have below code wh... | OutputIterator here is an exposition-only name for the template parameter. It has no specific functionality.
The linked site unfortunately doesn't specify which types are allowed as template argument for OutputIterator. If you take instead e.g. the cppreference.com page for std::copy_if, you see that it specifies that ... |
70,706,794 | 70,707,029 | How to print superscript 3 in C++ | I am looking for a way to print superscript 3, I googled a lot and I found a way to print superscript 2:
const char expo_square = 253;
void main () {
std::cout << expo_square;
return;
}
After some more googling, I came across the Alt Keycode for superscript 3, which is:
Alt + 0179
The problem with this is th... | Unicode superscript 3, or Β³ is \u00b3 in utf-16 and \xc2\xb3 in UTF-8.
Hence, this would work with cout, assuming your console is UTF8.
#include <iostream>
int main()
{
std::cout << "\xc2\xb3" << std::endl;
return 0;
}
To set your console in UTF-8 mode, you can do it in a number of ways, each is OS dependent,... |
70,707,292 | 70,716,287 | How to mock a template method that's in a template class in GTest? | I want to mock myFunction in google test and am having issues with the two templates.
template <class Outer>
class MyClass{
template <class T>
void myFunction(const int a, T * b);
};
| First of all, Outer template type isn't an issue here since it is not used in myFunction signature.
To handle type T you will need to fully specialize mocked method for all types used during testing.
Imagine you want to test that method with T=std::string:
template <class Outer>
class MyClassMock {
public:
MOCK_MET... |
70,707,431 | 70,707,552 | Is there an idea to notifiy all the client-process a resource is ready on windows (using C++)? | I have a shared-memory for other process to read, the number of reading processes could be more than one.
I need a lock, its locked at most of the time. When an updated is applied on the shared-memory, it will be unlocked and quickly locked again.
The reading process could use this lock to receive update-notification. ... | There are different synchronisation primitives for different use cases. A lock is intended to ensure one single access at a time for a resource. But to signal a bunch of readers that some data is ready, you should rather use an event.
From Microsoft doc about Event objects:
[Applications can use] event objects to prev... |
70,707,860 | 70,708,061 | TCP send struct not working Unhandled exception | So I want to send a char and a const char from the tcp client to the server, but the code I have below
This is the sender
struct packet {
char caseRadio;//1byte
const char* path;//4byte
};
packet* clientPacket = new packet;
string a = "C:\\Users\\Desktop\\Project phoneedge\\ForJen";
clientPacket->caseRad... | Send a const char * over TCP does not make sense. A const char * is only the address of a string in the memory of the sender process. It cannot magically point to something interesting in the reader process. Furthermore, sending a struct over the network is not reliable, because different compilation options could lead... |
70,707,900 | 70,708,214 | Python bit manipulation to get usable data out of a lidar sensor | I am trying to write a python driver for a lidar sensor that only has a package for robot OS.
I was able to get the communication working on a Raspberry Pi and I am getting the data that I need.
I never really worked with bytearrays before and even python is pretty new to me.
The received data looks like this (png), bu... | So here's one solution (maybe not the cleanest but it's bit-manipulation so...):
arr = [0x5D, 0xC7, 0xD0]
byte_0 = arr[0] << 4 | (arr[1] >> 4)
byte_1 = (arr[1] & 0xF) << 8 | arr[2]
I'll try to go over this step by step. The three bytes are, in binary representation:
0b0101_1101
0b1100_0111
0b1101_0000
The << operator... |
70,708,170 | 70,708,188 | How the compiler decides the value and data type of variable b here? | I am unable to understand how the memory allocation is working for variable b , is there some logic behind it or its just an another UB . The data type of b also becomes integer. \
int a = 5,b;
cout<<b; // 16
| You can declare several variables of the same type in a single statement, where the variables are separated by commas. So, b is declared to be an int, and is uninitialized, so it has an indeterminate value, and using its value is undefined behavior.
The recommendation is to declare a single variable per statement, and ... |
70,708,722 | 70,710,561 | OpenCL: array of arrays of variable lengths | I am trying to process an array of arrays of variables lengths with OpenCL 1.2 in C++. In each instance (workitem?) I want to process one sub array.
Below I've tried to treat the array of arrays as a 1D array, but it does not work - random parts of the data are not processes.
Host:
vector<cl::Platform> platforms; cl::P... | Updated code that works. I have no clue about the performance of this method.
vector<cl::Platform> platforms; cl::Platform::get(&platforms); _ASSERT(platforms.size() > 0); auto platform = platforms.front(); //get the platform
std::vector<cl::Device> devices; platform.getDevices(CL_DEVICE_TYPE_GPU, &devices); _ASSERT(de... |
70,709,144 | 73,448,837 | How to make Qt Creator use Rosetta and x86 compiler on Mac M1? | I am using Qt 5.15.2 on my Mac mini with M1 chip. This works fine (due to Rosetta). Below is the list of compilers Qt Creator found on this computer, and among them is the C++, x86 64bit that I use. No problem.
I would like to use the same settings on a (somewhat newer) Mac Book Pro (also with M1 chip). Below is th... | A few tips that can help, I just setup a project using Qt 5.15.2 on a 2021 M1 Mac.
Note this will likely be different for Qt >= 6.
Can I somewhere tell Qt Creator that the deployment target is x86?
Yes, you can do this using specific argument in the build settings of your kit.
Add the QMAKE_APPLE_DEVICE_ARCHS="x86... |
70,709,293 | 70,709,492 | map with double keys C++ | I have different stocks with their prices and I want to store them in the, for example std::map or std::unordered_map:
struct Stock
{
...
};
using stock_price_t = double;
std::map<stock_price_t, Stock> ordered_stocks;
std::unordered_map<stock_price_t, Stock> unordered_stocks;
Is it good idea use double keys in t... | A std::map has no issue with using doubles as key. It uses < to compare keys and two keys are equivalent when !(a < b) && !(b < a). That's fine. The issues do arise when you expect floating point numbers to be exact when in fact they are not.
For example:
std::map<double,int> m{{0.3,0},{1.0,2},{2.0,2},{3.0,3}};
for (co... |
70,709,422 | 70,709,536 | Compilation error in a simple function template | While experimenting with this stackoverflow answer I encountered a compilation error I don't understand.
With #if 1 the compilation fails with following error log whereas with if 0 the compilation is OK.
Full error log:
Output of x86-64 gcc 11.2 (Compiler #1)
<source>: In function 'void remove(std::vector<T>&, size_t)'... | The error message says it all:
error: dependent-name 'std::vector<T>::iterator' is parsed as a non-type, but instantiation yields a type
I.e., whilst for you as a programmer it is apparent that std::vector<T>::iterator is a type, for the compiler it is not, and the lack of a leading typename means it parses the depen... |
70,709,717 | 70,730,045 | C++ type aliases in anonymous namespace | I understand the general use of anonymous namespaces to contain code that should be only visible to the current source (i.e. non-header) file. However, I'm not able to find any information on what happens in the case below:
// In foo.cpp
#include <vector>
// Choice #1
template <typename T>
using Vec1 = std::vector<T>... | Anonymous namespaces primarily affect linkage. A type alias alone has no linkage, so in your case the two are identical.
That said, it is possible some included header also defines a template type alias with the same name but it's aliasing a different type. Then there is a difference; if you keep all of your implementa... |
70,710,012 | 70,710,955 | /clr and /experimental:module are incompatible options | Does someone knows what is the reason that I can't use the /clr options with the /experimental:module option with the msbuild compiler?
Is there some way to bypass it?
Thanks.
| The reason is that /clr compiler option of MSVC means that what you are compiling is not C++ but a different language C++/CLI. Lot of C++ and headers will be rejected under /clr option because it is not supported as C++/CLI.
The way to bypass it is that C++/CLI can #include headers written in (subset of) C++ and call t... |
70,710,488 | 70,711,139 | explicit instantiation with default template/function arguments | I'm trying to explicitly instantiate a templated function that has a default template argument as well as a default value for the corresponding parameter but I can't find the right syntax. What I'm trying is the following:
// in .hpp
template<typename T = std::function<void(int,int)>> void foo (T &&t = [](int,int)->voi... | The problem is that you did not keep the signature consistent. The declaration in the header accepts by rvalue reference, the implementation file by value, and the instantiation is for a function with absolutely no parameters (a default argument doesn't mean a function has no parameters).
You need to stick to the same ... |
70,710,597 | 70,710,901 | How to compute the position of the 4th corner of a rectangle? | I have 3 corners of an axis aligned box, I must find the 4th corner.
How can I compute it more efficiently:
if (loc[0].first != loc[1].first && loc[0].first != loc[2].first)
x = loc[0].first;
else if (loc[1].first != loc[0].first && loc[1].first != loc[2].first)
x = loc[1].first;
else
x = loc[2].first;
if ... | Assuming you have 2 identical (integral) numbers and a third one, xor might give you the expected one:
x = loc[0].first ^ loc[1].first ^ loc[2].first;
y = loc[0].second ^ loc[1].second ^ loc[2].second;
if type is not integral (so no xor), it seems more readable to check for equality (that also does one check for equ... |
70,710,664 | 70,710,727 | Can a copy constructor have a non-const lvalue parameter? | class Complex{
int x,y;
public:
void setdata(int x,int y)
{
this->x=x;this->y=y;
}
Complex add(Complex &c)
{
Complex temp;
temp.x=this->x + c.x;
temp.y=this->y + c.y;
return temp;
}
Complex(Complex &c) // copy constructor
{
... | The problem is that the add member function returns an rvalue expression of type Complex and you're trying to bind a non-const lvalue reference Complex& to that rvalue.
You can solve this error by replacing Complex(Complex &c) with:
Complex(const Complex &c) //const added here
Note the const added in the above stateme... |
70,710,903 | 70,711,183 | Freopen not writing output after a function call | I was doing a programming question and was using freopen to redirect the streams. The problem I am facing is that the printf command is not printing on the output file after stdout redirection. I even tried using fflush but couldn't get any results.
Here is my code
#include<iostream>
#include<vector>
#inclu... | The code like yours produces pointer to uninitialised memory cast into pointer of vector:
vector<int>* touch_circles = (vector<int>*)malloc(sizeof(vector<int>*)*size);
That is just undefined behaviour to use such vectors also the memory alloated is likely insufficient. It probably crashes or hangs your program and no ... |
70,710,940 | 70,710,978 | why i cant use args as a constant expression in c++ | I have this simple code, I want to send a two args to this function, one is "i" and the other is "n", when try to switch "i" in case of equal to 'n' I failed, because he say 'n' is not a constant expression, I read about this problem, I want to find a method to make 'n' is a constant expression.
this is the function:
f... | Function arguments aren't constant expressions. n and i are not initialized in your code. You can make n a template argument:
#include <iostream>
template <int n>
float east_coefficient(int i){
switch(i){
case 1:
return 0;
break;
case n:
return 0;
bre... |
70,711,528 | 70,719,591 | Can I add a string type parameter to a SQL statement without quotes? | I have a C++Builder SQL Statement with a parameter like
UnicodeString SQLStatement = "INSERT INTO TABLENAME (DATETIME) VALUES (:dateTime)"
Can I add the parameter without quotes?
Usually I'd use
TADOQuery *query = new TADOQuery(NULL);
query->Parameters->CreateParameter("dateTime", ftString, pdInput, 255, DateTimeToStr... | Why are you defining the parameter's DataType as ftInteger when your input value is clearly NOT an integer? You should be defining the DataType as ftDateTime instead, and then assigning Now() as-is to the parameter's Value. Let the database engine decide how it wants to format the date/time value in the final SQL per i... |
70,711,580 | 70,765,552 | static constexpr vs constexpr in function body? | Is there any difference between static constexpr and constexpr when used inside a function's body?
int SomeClass::get(const bool b)
{
static constexpr int SOME_CONSTANT = 3;
constexpr int SOME_OTHER_CONSTANT = 5;
if(b)
return SOME_CONSTANT;
else
return SOME_OTHER_CONSTANT;
}
| The main difference between those two declarations is the lifetime of the objects. When writing the question, I thought that using constexpr instead of const would place that object into the .rodata section. But, I was wrong. The constexpr keyword, here, only provides that the object can be used at compile-time functio... |
70,711,684 | 70,722,596 | Calling a class with an abstract base class from a derived class --safely | I'd like to call the class Foo which has the abstract class Base in its ctor. I'd like to be able to call Foo from Derived which is derived from Base and use Derived's overriding methods rather than Base's.
I'm only able to do this by using a raw pointer as indicated. Is there any way to do this without raw pointers? I... | The code can be rewritten with const reference to Base as
#include <iostream>
class Base {
public:
Base() {
std::cout << "Hello from Base." << std::endl;
}
virtual void show() const = 0;
};
class Foo {
public:
explicit Foo(const Base& b) : s(b) { // member initialization list to set s
... |
70,711,748 | 70,713,801 | LTTNG: using with a popular library | I have a trivially simple question that I could not find the answer yet.
Say, I have a shared library X that is used by 100 simultaneously running applications A0, A1, ... A99. I had instrumented my library and with LTTNG using "X-Provider" as the provider name. How can my user distinguish between X-Provider events th... | With the lttng command-line utility, add the vpid context field to be recorded to your event records, for example:
$ lttng add-context -u -t vpid
This targets all the user space channels of the current recording session; you can of course select a specific recording session and/or channel (see lttng-add-context(1)).
Y... |
70,712,181 | 70,713,345 | Force compile time check for correct object instantiation | How do I force the compiler to give errors if the user instantiates an object of some class incorrectly?
For example:
Polynomial a("x^2 + 2x + 1"); //this is a valid Polynomial object
Polynomial b("3xy + 2 - 5/z"); //this is not valid, force compiler error
static_assert seems to not work with function arguments and t... | I did read and read your question and comments and maybe I am confused what you want but why simple solution using constexpr constructor does not suit you:
#include <iostream>
struct Polynomial {
const char* str;
constexpr Polynomial(char const* arg)
: str(arg) {
// if check fails when constru... |
70,712,266 | 70,712,359 | Impact of namespaces on C++ template deduction priority | while trying to implement a metafunction, which needs to exist only if the "abs" function exists for some type, i ran into the folowing problem:
Here are two examples of code i would expect to yield the same results but in fact, they do not:
First example
#include <iostream>
#include <cmath>
using namespace std;
stru... | In the second case the using directive places declared names in the nominated namespace in the global namespace for unqualified name lookup. So within the namespace Foo the unqualified name abs declared in this namespace is found. That is the name abs declared in the namespace Foo hides the name abs declared in the glo... |
70,712,797 | 70,712,889 | Is it safe to bind an unsigned int to a signed int reference? | After coming across something similar in a co-worker's code, I'm having trouble understanding why/how this code executes without compiler warnings or errors.
#include <iostream>
int main (void)
{
unsigned int u = 42;
const int& s = u;
std::cout << "u=" << u << " s=" << s << "\n";
u = 6 * 9;
std... | References can't bind to objects with different type directly. Given const int& s = u;, u is implicitly converted to int firstly, which is a temporary, a brand-new object and then s binds to the temporary int. (Lvalue-references to const (and rvalue-references) could bind to temporaries.) The lifetime of the temporary ... |
70,713,342 | 70,732,195 | WinUI 3 C++ - Choose appo theme | I'm developing a WinUI 3 C++ app for Windows 11 and the app automatically defaults to the theme chosen by Windows. Is there any way to change that?
| The simplest way to change the overall app theme to the windows default theme is:
if (Window.Current.Content is FrameworkElement rootElement)
{
rootElement.RequestedTheme = ElementTheme.Default; //Also: Dark or Light
}
|
70,713,414 | 70,715,158 | How to contruct non-copyable, non-moveable class in a nested vector? | I want to construct a vector using a non-default constructor of a non-copyable, non-movable class. With the default constructor it works fine, and I can construct a vector, as long as I don't resize it. But somehow with a non-default constructor it seems to have to copy. Does anyone know if I can avoid the copy operati... | You can use std::vector<std::mutex> directly, because the type requirements when using standard library containers are restricted to only those required by the functions called on them.
Once you have constructed a std::vector<std::mutex> with some elements, only the operations that might add new elements or erase old o... |
70,713,679 | 70,714,142 | OpenGL Texture Showing Wired Lines instead of solid color | My Code
void SetPixel(int x, int y)
{
unsigned char* offset = mImageData + (x + mImageHeight * y) * sizeof(unsigned char) * 3;
offset[0] = 255;
offset[1] = 0;
offset[2] = 0;
}
And
for (int j = imageHeight - 1; j >= 0; j--)
{
for (int i = 0; i < imageWidth; i++)
{
... | By default OpenGL assumes that the start of each row of an image is aligned to 4 bytes. This is because the GL_UNPACK_ALIGNMENT parameter by default is 4. Since the image has 3 color channels (GL_RGB), and is tightly packed the size of a row of the image may not be aligned to 4 bytes.
When a RGB image with 3 color chan... |
70,713,735 | 70,717,386 | Inconsistent output from gcount() | I have written the following simple MRE that regenerates a bug in my program:
#include <iostream>
#include <utility>
#include <sstream>
#include <string_view>
#include <array>
#include <vector>
#include <iterator>
// this function is working fine only if string_view contains all the user provided chars and nothing ext... | The basic problem you have is with the operator<< functions. You've tried two of them:
operator<<(ostream &, const char *) which will take characters from the pointer up to (and not including) the next NUL. As you've noted, that may be a problem if the pointer comes from a string_view without a terminating NUL.
oper... |
70,714,111 | 70,717,496 | Possible scenarios to justify heap-allocated variables scoped locally? | I encountered the following code snippet.
int main() {
auto a = new A(/* arguments */);
// Do something
delete a;
}
Here A is a very nontrivial class I cannot easily reason about (highly parallelized and networking involved). Because x is instantiated in main (or possibly any other function) and then delet... | First of all there is no reason to not use a smart pointer here, i.e.
auto a = std::make_unique<A>(/* arguments */);
but as to why you would want to heap allocate rather than creating the object on the stack, reasons include
Size. Class A might be huge. Stack space is not inexhaustible; heap space is much much larger... |
70,714,289 | 70,714,339 | trying to graph a mathematical function using a sf::vertexArray that contains sf::Quads, but my quads do not display correctly | In my constructor I have:
function.setPrimitiveType(sf::Quads);
numOfPoints = ((XUpperLimit - XLowerLimit) / .001) * 4;
function.resize(numOfPoints);
and my graph function:
void Window::graphFunction() {
double YVal;
for (double XVal = XLowerLimit, index = 0.0; XVal < XUpperLimit; XVal += 0.001, index += 4) {... | From the documentation:
The 4 points of each quad must be defined consistently, either in clockwise or counter-clockwise order.
The ordering of your points do not satisfy this requirement.
Swapping your first two coordinates would fix this.
Alternately, swapping the last two coordinates would also fix this.
|
70,714,588 | 70,714,655 | How to initialize a template object inside a class C++? | I want to create a template Node class like this
template <class T>
class Node {
public:
Node() {
val = T;
// Does not work: new T, NULL, 0, ""
}
// ...
private:
vector<Node<T> *> children;
T val;
Node<T> * parent = NULL;
}
The constructor is supposed to have no initial value as... | Either you can write
Node() : val() {}
or
Node() : val{} {}
Or in the class definition to write
T val {};
|
70,714,789 | 70,715,482 | std::chrono::system_clock + now() to milliseconds and back different behavior | I'm a bit puzzled to find a portable way to convert milliseconds to std::chrono::system_time::time_point. I looks like the code :
https://godbolt.org/z/e7Pr3oxMT
#include <chrono>
#include <iostream>
int main ()
{
auto now = std::chrono::system_clock::now();
auto now_ms = std::chrono::time_point_cast<std::chro... | The problem is probably
long duration = value.count();
The type long isn't necessarily 64 bits wide. The C++ standard does not define the exact size of integer types besides char. Visual Studio uses 32 bits for long even in an x64 build, for example.
Anyway, try
uint64_t duration = value.count();
in your code or just... |
70,714,962 | 70,715,006 | (C++) declaration of 'std::string fil' shadows a parameter | I am trying to make my own compiler(yes) and c++(cpp version of cc) is giving me an error saying: error: declaration of 'std::string fil' shadows a parameter.
Code:
#include <iostream>
#include <cstring>
#include <string>
int compile(std::string fil)
{
std::string cmd = "cc ", fil; // error here
system(cmd);
... | Not Sure what is your question - but compiler is correct:
<source>:7:30: error: redefinition of 'fil'
std::string cmd = "cc ", fil; // error here
^
<source>:5:25: note: previous definition is here
int compile(std::string fil)
You have a redefinition of parameter. You should rename one ... |
70,715,420 | 70,716,356 | c++ 17, is it possible to parameterize uniform initialization of vector? | I have a vector of 2N lines where the second half (N lines) is basically the same as the first half but with a single character changed, e.g.:
std::vector<std::string> tests{
// First half of lines with '=' as separator between key and value
"key=value",
...
// Second half of lines with ' ' as s... | Since this is tagged c++17 and you said the strings are known at compile-time, it is technically possible to perform uniform initialization by leveraging a variadic function-template and unpacking the parameters twice, and this would produce the modified string at compile-time.
The idea, in the simplest form, is to do ... |
70,715,474 | 74,102,267 | Where to find information about the exact binary representation of floating point values used by avr-gcc when compiling for 8-bit processors? | I need to find out the exact binary representation for floats and doubles in a C++ project built with Platformio for an Atmega328 using the Arduino framework. I don't have access to the actual hardware so I can't check it myself.
The micro does not have an FPU and is 8-bit so it's pretty much all up to the compiler (or... | Floating-Point Format
In any case, the floating-point format is:
IEEE-754, binary, little-endian.
In the encoded form, respective parts of the representation will occupy:
32-Bit Floating-Point
64-Bit Floating-Point
Sign
1 bit (31)
1 bit (63)
Biased Exponent
8 bits (30β23)
11 bits (62β52)
Encoded Mantissa
2... |
70,716,296 | 70,716,342 | A problem with cin after a getline makes my while loop never end at the second iteration in c++ | If I replace the getline for a cin, just as a test, it works as I want. But the moment I introduce the getline it creates a never-ending loop at the second iteration. I think it has something to be with the buffer but I don't know how it works so I need help.
This is the code:
while(true)
{
alumno++;
cout<<... | After this statement
cin>>nota;
insert
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
You will need to include the header
#include <limits>
|
70,717,471 | 70,719,113 | Is there is a difference between two constructs | If there is a difference between two constructs
I would like to know
std::string name = std::string("Eugene");
and
std::string name = "Eugene";
| C++11
First lets consider the statement:
std::string name = std::string("Eugene");
For the above shown statement there are 2 possibilities in C++11.
A temporary object of type std::string is created using "Eugene" on the right hand side. Then, the copy/move constructor of std::string is used to construct the object n... |
70,718,183 | 70,726,798 | Return key for element that has max int at location [r][c] from a map of 2d vectors | I have multiple 2d arrays (all same dimension) of integers that are stored within a map, each array contains a unique character that is assigned to the array. E.g., I have std::map<std::array<std::array<int>> , char>.
I am trying to find the array that has the maximum integer for a specific 2d coordinate, and return th... | It is impossible to do this without looking at every 2D array in your map because you need to compare all of them in order to find out which one has the largest integer at your given coordinates. (Using a loop is unavoidable)
Consider a map myMap that has the properties you described, i.e. it has type std::map<std::arr... |
70,718,248 | 70,729,960 | pybind11: segfault on process exit with static py::object | I am using pybind11 to create a module in C++ and then importing it into a Python program. This is running through a normal script in CPython, not an embedded interpreter.
In my module, I have a function that defines a static py::object :
void some_function() {
static const py::object my_object = ...
}
This works f... | Two possible solutions:
Instead of a local static object, you can define a static member of a pybind11 module or class. Then the object's lifetime is tied to the bindings, which are managed by the python interpreter and destructed correctly.
Another way is to manually destruct the object using a pythonic atexit callbac... |
70,718,289 | 70,718,390 | Swap with temp variable is not giving any output but swap() is giving an desired output output. c++ | Swap with temp variable is not giving any output but swap() is giving an desired output.
I am trying to swap arr[i] with arr[arr[i]+1].
This code is giving the desired output
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n],i,temp;
for(i=0;i<n;i++) {
cin>>arr[i];... | The different results is because std::swap does not use a temporary variable this way, it works slightly differently. Hence the different results.
To understand the different results consider the most simple case when the array has two values:
+---+---+
arr: | 0 | 1 |
+---+---+
arr[0] is 0 and arr[1] is 1... |
70,718,720 | 70,718,836 | Why is the output order different from the call order when using fprintf with stdout or stderr? | My environment is Debian GNU/Linux 11.
The fprintf function with param stdout or stderr gives unexpected output order.
int main() {
std::cout << "Hello, World!" << std::endl;
fprintf(stderr, "22222\n");
fprintf(stdout, "111\n");
printf("3333 \n");
printf("44444 \n");
return 0;
}
I've run this m... | The output is never like β‘ because output to stderr isn't buffered so 22222 will be flushed immediately and would be before any other numbers. Output to stdout may be line-buffered (default on Linux) or full-buffered (default on Windows)
The output shouldn't be like β either because you're already flushing with std::en... |
70,718,722 | 70,720,630 | Why does my ATSP function using dynamic programming enters infinite loop? | Global variables:
int verNum = 0, minimum = INT_MAX;
double st;
Initializing function in main
ATSP(graph, visited, start, 0);
Where:
vector<vector<double>> graph; -> contains costs of travels
vector<bool> visited; -> has the size equal to the number of cities
int start = (rand() % verNum);-> random starting p... | Programs works now, read EDIT for more info.
|
70,718,900 | 70,718,954 | Including two header files in c++ | I have a project I'm working on and I'm currently working on the header files. For simplicity let's say I have two header files so far.
fileX.h and fileY.h
The code I have in both is just class definitions. But, fileX needs fileY's class definitions and fileY needs fileX. I tried having inside of fileX a #include "file... |
How can I fix this ?
By breaking the circular dependency. Its simply impossible for A to depends on B's definition while also B depending on A's definition. You must get rid of one of the dependencies.
|
70,718,983 | 70,719,085 | std::osyncstream outputs garbled text and causes seg fault | This code when using osyncstream outputs garbage characters, isn't alway in sync, and seg faults. When output is to std::cout directly the output isn't in sync but output is good and does not seg fault.
#include <atomic>
#include <chrono>
#include <iostream>
#include <syncstream>
#include <thread>
std::osyncstream syn... | That's not how osyncstream is supposed to be used. Every thread needs to construct its own osyncstream; there is no synchronization on access to the osyncstream itself. Only the transfer performed by emit is synchronized, and then only with respect to the streambuf it wraps.
Having a global osyncstream is therefore ent... |
70,719,167 | 70,719,201 | Selecting ambiguous constructor manually | When a call to a function (member class function or free function) is ambiguous, we can select it easily using static_cast<> to the function type we calling:
struct S {
void f(uint32_t, uint8_t) {
std::cout << "1\n";
}
void f(uint32_t, uint32_t) {
std::cout << "2\n";
}
};
int main() {
... | Is this what you had in mind?
S s1(static_cast<uint32_t>(1), static_cast<uint32_t>(2));
S s2(static_cast<uint32_t>(1), static_cast<uint8_t>(2));
This disambiguates the constructor-calls by specifying the types explicitly in the arguments.
|
70,719,314 | 70,719,348 | Friend function from another namespace | /** module.h */
#pragma once
class A {
friend void helpers::logValue(const A &);
int _val;
public:
A() {}
};
namespace helpers {
static void logValue(const A &a) {
std::cout << a._val; // <== ERROR: '_val' is not accessible
}
}
How do I declare the friend function in another namespace?
| One possible way of solving this is as shown below:
class A;//forward declaration for class A
namespace helpers{
static void logValue(const A &a); //declaration
}
///////////////////////////////////////////
class A {
friend void helpers::logValue(const A &);
int _val;
};
namespace helpers {
static void lo... |
70,719,383 | 70,719,397 | why does it complain integer constant is too large for its type | I am writing a hamming weight calculator but why does the number 3 is too large for uint32_t ?
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
Note:
Note that in some languages, such as Java, there is no unsigned integer type. In this case, t... | To enter literals in binary format you need to have the prefix 0b, as in 0b11111111111111111111111111111101.
For comparison, 0 is the prefix for octal numbers (011 is not even 11 decimal, it's decimal 9) and 0x is the prefix for hexadecimal numbers.
|
70,720,236 | 70,720,504 | Enforce exact invokable signature in C++ | i have a function that takes an invokable, and i want to make sure that the signature of the passed invokable is exactly the specified one.
#include <type_traits>
#include <cassert>
#include <iostream>
template<typename F>
requires std::is_invocable_v<F, float&>
float fn(F&& f) {
float v;
f(v);
return v;
}... | You may add another constraint to fn:
template<typename F>
requires std::is_invocable_v<F, float&>
and (not std::is_invocable_v<F, float>) // <--
float fn(F&& f) {
//...
}
Live here.
|
70,720,403 | 70,720,486 | Can template partial specialization narrow the argument type in C++? | In the next program, struct template A<int> has a specialization A<char>:
template <int>
struct A { constexpr operator int() { return 1; } };
template <char c>
struct A<c> { constexpr operator int() { return 2; } };
int main() {
static_assert( A<1000>{} == 1 ); //ok in Clang and GCC
static_assert( A<1>{} == 2... | The active CWG issue 1647 mentions exactly this case of specializing an int non-type template parameter to a char.
It also mentions that the standard is currently lacking wording to handle type mismatches between non-type template parameters in primary templates and their partial specializations and that there is imple... |
70,720,482 | 70,720,531 | Run time error: "/home/keith/builds/mingw/gcc........" in VS Code while working with strings | This code is running properly in other online C++ compilers but is throwing an unexpected error in VS Code. Please point out the problem in my code. (The Error has also been attached below)
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input;
int size;
cout << "Enter the s... | string input; is empty so input[i] accesses the string out of bounds which makes your program have undefined behavior. You could resize it to size to make it work - or create the string with the correct size after you've entered what size you want it to have.
Example:
#include <iostream>
#include <string>
int main() {... |
70,720,804 | 70,720,977 | class is not nothrow constructible but is nothrow destructible | I have a class like below:
#include <iostream>
#include <type_traits>
#include <concepts>
#include <vector>
class Foo
{
public:
Foo( )
: m_member1( 1 ), m_member2( 2 ), m_member3( std::vector<char>( 1 * 2, '-' ) )
{
}
// ~Foo( ) is not defined (i.e. implicitly declared by the compiler)
private:
... | Destructors are special. For the implicit destructor as well as user-declared destructors without noexcept specification, the destructor is noexcept(true) by default if all destructors of members and base classes are noexcept(true).
To get a potentially-throwing destructor, you need to explicitly declare it noexcept(fa... |
70,721,104 | 70,730,126 | How to prevent lifetime issues between completion of background task and UI in Qt | When using QtConcurrent::run to run code in the background from a UI the
QFuture::then(QObject *context, Function &&function) can be used to update the UI because you can pass the window object as context to make function execute on the GUI thread. This is very convenient however there is one problem. When the window i... | One simple option would be to use a QPointer to track/monitor the QWidget of interest. A copy of the QPointer can be captured by whatever lambdas or functors are used by QtConcurrent::run or QFuture::then.
/*
* Set up the QWidget that we need to monitor.
*/
auto w = std::make_unique<QLabel>("Working...");
w->show();... |
70,721,441 | 70,721,499 | Is there any difference typecasting between (Parent&)child and (Parent)child in c++? | I was just implementing a function and I recognized that there was an error (type error) when a variable was typecasted as (Parent)child. But the error fixed when it was typecasted as (Parent&)child. Then I checked the type of the variables typecasted and both are same type. Is there a difference or is it probably just... | Yes, there is a difference. Casting to an object produces a new prvalue. Casting to a reference produces an lvalue that refers to the base sub object.
P.S. Prefer using C++ style casts (static_cast) instead of C-style casts.
|
70,721,826 | 70,721,846 | Dot function in unreal c++ | This is the code in Unreal C++
float GetT( float t, float alpha, const FVector& p0, const FVector& p1 )
{
auto d = p1 - p0;
float a = d | d; // Dot product
float b = FMath::Pow( a, alpha*.5f );
return (b + t);
}
Does this line means "float a = d | d; // Dot product" dot product of FVector d with it... | Look for documentation of FVector. Search "operators". Look for |. Find:
float
operator|
(
const FVector& V
)
Calculate the dot product between this and another vector.
Yes. d | d calculates the dot product of the vector with itself.
|
70,721,888 | 70,743,155 | Unable to set QQmlApplicationEngine rootContext Property | I've got the following code that I thought should make a "backend" C++ object available in QML elements of my GUI, but seems to be failing, resulting in a property of my QML objects that is null.
//Initialize the engine, register the Data_Client object and set the "client" property
QQmlApplicationEngine engine;... | In theory, setContextProperty can be called at any time, but any QML files that are already loaded at that time probably will not see that new property. QML files loaded after that point will see it. So calling setContextProperty before you call engine.load() should fix the problem for you.
|
70,722,207 | 70,722,324 | c++ HMAC sha512 bad coding | I'm trying code a openssl HMAC SHA512 encryption but i compare my result with some online pages such HMAC-SHA256 Online Generator Tool and the result is not the same I can not figure out what i'm doing wrong, its my first time coding c++ with openssl encryption.
this is my code until now:
char *key = "apiPrivateKey";
c... | Don't know how to debug your code, here's a working one.
std::string b2a_hex(const std::uint8_t* p, std::size_t n) {
static const char hex[] = "0123456789abcdef";
std::string res;
res.reserve(n * 2);
for (auto end = p + n; p != end; ++p) {
const std::uint8_t v = (*p);
res += hex[(v >> 4... |
70,722,490 | 70,722,539 | Getting Extra characters at the end when Creating std::string from char* | I have just started learning C++. Now i am learning about arrays. So i am trying out different examples. One such example is given below:
int main()
{
const char *ptr1 = "Anya";
char arr[] = {'A','n','y','a'};
std::string name1(ptr1); //this works
std::cout << name1 << std::endl;
std::str... | The problem is that you're constructing a std::string using a non null terminated array as explained below.
When you wrote:
char arr[] = {'A','n','y','a'}; //not null terminated
The above statement creates an array that is not null terminated.
Next when you wrote:
std::string name2(arr); //undefined behavior
There ar... |
70,722,524 | 70,726,689 | Initializing a member pointer with a dynamically allocated pointer | Is it possible and good practise to initialize a member pointer with a dynamically allocated pointer? Should I delete the pointer in the destructor?
class Apple
{
public:
Apple(int* counter) : counter_(counter);
~Apple(); // should I delete counter_ here?
private:
int* counter_;
}
int main()
{
somept... | Yes, it's possible to initialize a member pointer with a pointer to dynamically allocated data. I've seen this done in instances where a class needs access to an instance of another (dynamically allocated) class.
It's good practice only if you absolutely need to do it. If it's simply an integer we're dealing with (as i... |
70,722,700 | 70,723,646 | Deleting calling signal from callback boost::signals c++ | I have the following code that deletes the signal during one of the callbacks from the signal:
#include <iostream>
#include <boost/signals2/signal.hpp>
struct Foo {
boost::signals2::signal<void(int)> signal;
};
std::vector<Foo> foos;
foos.emplace_back(Foo());
std::vector<int> values;
auto connect... | // delete the foos here, where we will be calling from below
That's a misleading comment. The deletion (clear()) only happens after raising the signal, so the control flow is in the reverse order from the lines of code.
To me, this code looks valid, unless you destroy connection (e.g. connection.release();) from insd... |
70,722,994 | 70,723,354 | statemachine using variadic template overloading | I am trying to build a statemachine in C++ using variadic templates.
class Event {};
template<typename... TEvents>
class StateMachineActionHandler
{
public:
void action() = delete;
};
template<typename TEvent, typename... TEventRest>
class StateMachineActionHandler<TEvent, TEventRest...> : public StateMachineActi... | You need to use using-declaration to introduce the default implementation into the derived class definition
class StateA : public State<EventA, EventB>
{
public:
using State<EventA, EventB>::action;
void action(const EventA& event) override { std::cout << "new A A" << std::endl;}
void enterAction() overrid... |
70,723,419 | 70,723,504 | What kind of type should r-value reference parameter be in doxygen? [in] or [in, out]? | /**
* @param[?] u
*/
T func(U&& u);
The parameter u may be modified by func, while the modified status should be ignored seeing it's an r-value reference.
I haven't found any information about that, including the Doxygen Manual.
| You should not think in terms of "it's a reference, so that means X". You should think in terms of what u means to the function and what the function is doing with it. Merely moving from u is not enough to declare it an [inout] parameter. [inout] or [out] should be used when the function is deliberately setting a value... |
70,723,906 | 70,725,184 | Captured shared_ptr released while executing the lambda body | I have a nested lambda in C++, which is to say, an inner lambda contained in a middle lambda, which is also contained in an outer lambda.
I created a shared_ptr in the outer lambda, which I passed by value to the middle lambda, inside which I created the inner lambda, after declaration of which the captured shared_ptr ... | When you call c.next(c) the first time, you are running the function c.next which will cause c.next to be replaced by a new lambda, the one that owns a shared pointer. After the first c.next(...) call this shared_ptr owning lambda will be the new c.next.
When you then call c.next(c) again you are replacing that lambda ... |
70,724,035 | 70,724,300 | C++ Win32 Getting a registry key | const char* Launcher::GetProjectName()
{
PVOID data;
LPDWORD pcbData;
HKEY OpenResult;
LSTATUS status = RegOpenKeyEx(HKEY_CURRENT_USER, L"Environment", NULL, KEY_READ, &OpenResult);
if (status != ERROR_SUCCESS)
{
LOG(ERROR) << "Could not found registry key 'Environment'";
}
else... | I think there's a mismatch of ANSI and Unicode expectations. Your code is likely compiling for ANSI, but you're passing a wide-char buffer. Let's just explicitly call the A version of the Registry functions so you can stay in the ANSI string space.
Instead of this:
WCHAR value[255];
PVOID pvData = value;
DWORD size = ... |
70,724,158 | 70,725,518 | Corrupting the heap while writing an object to a binary file | I have this class with a constructor and destructor
class Monster
{
char* nume;
double hp;
float* dmgAbilitati;
int nrAbilitati;
public:
Monster(const char* nume, double hp, int nrAbilitati, float* dmgAbilitati)
{
if (nume == nullptr)
throw new exception("Nume invalid!\n");... | The problem is in citireFisierBinar: while there is a reallocation for the nume array member, there is no reallocation (or at least check for sufficient memory) for the dmgAbilitati array member.
There are some other isuues in your code, for example:
Throwing exceptions: ctor code throws a pointer; it should throw a ... |
70,724,468 | 70,724,588 | differences between std::for_each and std::copy, std::ostream_iterator<T> when printing a vector | Recently, I have come across code that prints a vector like so
std::copy(vec.begin(), vec.end(), std::ostream_iterator<T>(std::cout, " ");
comparing that to what I am used to (for_each or range based for loop)
auto print = [](const auto & element){std::cout << element << " ";};
std::for_each(vec.begin(), vec.end(), pr... |
No, the ostream_iterator uses the std::ostream& operator<<(std::ostream&, const T&); overload and will not create additional copies as can be seen in this demo.
The ostream_iterator is a single-pass LegacyOutputIterator that writes successive objects of type T. The destination range can be seen as the Ts printed on st... |
70,724,532 | 70,724,590 | How to check if object is in viewport Directx 11 | I'm trying to check if an object is currently on the screen in directx. I have the view matrix and the projection matrix and the x y z of both the object and the camera.
This seems like a common issue people have but Ive tried looking all over google and cant find anyone talking about this in directx only about javascr... | For a perspective projection, this is a 'frustum' vs. 'box' bounding-volume intersection test.
For a orthographic projection, this is a 'box' vs. 'box' bounding-volume intersection test.
The DirectXMath library (it's also in the Windows SDK) includes functions to perform these tests in the DirectXCollision.h header. Cr... |
70,724,553 | 70,724,934 | how to create a c++ recursive function to return a node custom object? | how are you?
I created a C++ recursive function in order to iterate over a binary tree and print out all the NODEs where the property COMPLETED = TRUE;
ItΒ΄s working pretty fine because the type of the function is VOID and I am only printing out the result.
This is the way that works fine:
void findAndPrintFirstComplete... | You seem not to be familiar how returning values works.
The result of the lines
findAndPrintFirstCompletedNodes(lastNode->left);
findAndPrintFirstCompletedNodes(lastNode->right);
is ignored in your code.
Only in the case that the input in the first recursion is completed, anything is returned. Frankly, I wonder why yo... |
70,724,857 | 70,944,159 | C++ SFML src/Utility/FileSystem.hpp:8:36: fatal error | I tried to install SFML with the help of this tutorial because I couldn't find a way to install it myself. After I did CTRL + B and Run build & debug I got this error:
⬀ Build & Run: Debug (target: sfml-vscode-boilerplate.exe)
src/PCH.hpp
In file included from src/PCH.hpp:66:0:
src/Utility/FileSystem.hpp:8:36: fat... | Okay it was just bad version of GCC and G++
|
70,725,560 | 70,725,575 | return reference in cpp function returns a copy | I am trying to return the reference of the argument in the function test, but when I assign another value to the returned reference, the original doesn't change:
#include <iostream>
using namespace std;
int& test(int& n) {
return n;
}
int main() {
int n = 1;
int m = test(n);
m = 2;
cout << n << e... | Make m an lvalue reference:
int& m = test(n);
You can also bind to temporaries like this:
int test(int& n) { // return by value
return n;
}
int main() {
int n = 1;
int&& m = test(n); // rvalue reference binding to a copy of `n`
m = 2;
std::cout << n << std::endl;
return 0;
}
Although the abo... |
70,725,739 | 70,725,807 | std::cin , unwanted behaviour. and how can I fix this? | I tried to play with some code to test overloading functions. The overloading part went well, however, I learned something about std::cin that made me feel stupid for not noticing it before!
#include <iostream>
void read (int *var){
std::cout<<std::endl<<" input :";
std::cin>>*var;
}
void read (float *var){
... | This is not a strange behaviour what really happens is when this line is executed in the read int function:
std::cin>>*var;
it expects an integer from your keyboard buffer and when you enter this as input:
1.2
the cin object reads the first digit until the decimal point because it is the integer part and leave the r... |
70,725,858 | 70,725,938 | Use stdlib and rand with Node native module (node-gyp) | This is just an example of the problem.
Let's say I have utils.cc
#include "../headers/utils/utils.h"
double sum()
{
double result = 1 + 1;
return result;
}
double multisum(int n)
{
double result = 0;
for (int i = 0; i < n; i++)
{
result += rand();
}
return result;
}
and this file... | You forward declare your helper function like this:
static void ReturnResult(int result, const FunctionCallbackInfo<Value> &args);
// ^^^
but then implement it like this:
static void ReturnResult(double result, const FunctionCallbackInfo<Value> &args)
// ^^^^^^
So fix which... |
70,726,811 | 70,734,044 | CLion Not Finding GLUT with CMake | I have a problem that I can't seem to find the settings to modify.
When attempting to find the GLUT package using CLion's CMake utilities on Ubuntu, it does not find GLUT. Using command-line CMake and Makefile commands, however, finds the dependencies perfectly and allows the following to generate and compile:
# CMakeL... | Alternative solution
CLion was installed through the Software Center via Flatpak, which uses some kind of filesystem sandboxing that may be interfering with paths. I tried explicitly allowing /usr and related paths, but had no effect.
I have reinstalled via JetBrains's official archive, which correctly detects GLUT and... |
70,727,088 | 70,727,539 | Why can't I use an arbitrary nesting of braces to construct most classes? | Given the following code:
struct A;
struct B {
B() {}
B(A &&) {}
};
struct A {
A() {}
A(B &&) {}
};
Then I can use as many braces as I want to construct A or B.
// default construct A
auto a = A{};
// default construct B, forward to A
auto b = A{{}};
// default construct A, forward to B, forward to A... | There's a special case that precludes D{{}}. It's a very particular set of conditions, so I imagine it's there specifically to prevent this exact recursion.
[over.best.ics]/4 However, if the target is
(4.1) β the first parameter of a constructor
...
and the constructor ... is a candidate by
...
(4.5) β the second phas... |
70,727,184 | 70,727,205 | shmat(3) function returns 0xffffffffffffffff address | I have been struggling with using IPC shared memory. I am trying to write simple server / client programs communication through BSD TCP Sockets. The server is multithreaded and services multiple parallel chess duels between users. Each thread is associated with only one user. To share data about moves and duel status I... | From man:
shmat() returns the address at which the shared memory segment has been mapped into the calling process' address space when successful, shmdt() returns 0 on successful completion. Otherwise, a value of -1 is
returned, and the global variable errno is set to indicate the error.
The 0xffffffffffffffff pointer... |
70,727,235 | 70,727,271 | Shouldn't strict-aliasing kick in in this code? | Take this toy code:
void f(const int& a, int* dat) {
for (int i=0; i<a; ++i )
dat[i] += a;
}
Observe that the compiler is afraid that dat[i] might alias with a, i.e. writing to dat[i] might change the value of a - and so it feels obliged to re-load a on every loop iteration (that's the 'movslq (%rdi),... | Imagine the following:
struct myInt {
int i;
myInt& operator+=(int rhs) { i += rhs; return *this;}
};
void f(const int& a, myInt* dat)
{
for (int i=0; i<a; ++i)
dat[i] += a;
}
int main()
{
myInt foo{ 1 };
f(foo.i, &foo);
}
In this program, a and dat.i actually alias. They are the same variab... |
70,727,244 | 70,727,398 | Segfault when passing vector of vectors to SSBO using glBufferData | I am trying to pass a vector of vectors to an SSB0, however I get a segfault when passing it through with glBufferData. The structure in C++ is:
const uint16_t MAX_NODE_POOLS = 1927;
union Node
{
uint32_t childDescriptor;
uint32_t material;
};
struct NodePool
{
NodePool() : mNodes({0}) {}
std::array<N... |
uint16_t ID;
std::vector<NodePool> mNodePools;
std::vector<uint16_t> mNodeMasks;
...
glBufferData(GL_SHADER_STORAGE_BUFFER, getMem(), mBlocks.data(), GL_DYNAMIC_DRAW);
You cannot do that. You cannot do a byte-wise copy of most C++ standard library types into OpenGL (or at anything else for that matter). As a general... |
70,727,277 | 70,727,581 | Error during the Initializing a vector from an arraty of ints | Am presently reading the book C Primer 5th Addition by Stanley B. Lippman, JosΓ©e Lajoie, Barbara E. Moo. While reading the book, I came across a line stating,
we can use an array to
initialize a vector. To do so, we specify the address of the first element and one
past the last element that we wish to copy
The code p... | begin and end are defined in namespace std. So you have to be in the scope of that namespace. Which is what we do when we write std:: .
So to solve your problem,
Replace begin by std::begin. Similarly replace end by std::end
|
70,727,474 | 70,727,910 | /bin/bash: no: command not found: when trying to use a make:model command with J.DepP | When trying to run a Makefile from J.DepP, I keep getting /bin/bash: no: command not found. Does anyone know how to fix this? Is there a no program to install?
// Command that fails (split into 2 lines for readability)
find /home/jdepp-2015-10-05/KNBC_v1.0_090925/corpus1 -type f -name "KN*" | LC_ALL=C sort | xargs cat ... | This was actually an issue because python wasn't installed and J.DepP's makefile didn't return a fail for a critical dependency.
Install python, run make clean && ./configure and the issue with disappear.
|
70,727,819 | 70,727,882 | warning: definition of implicit copy constructor even though I didn't call copy constructor | I am trying to run this example in https://en.cppreference.com/w/cpp/language/copy_assignment, but when I delete the default constructor and default copy constructor: A() = default; A(A const&) = default;, clang++ says that warning: definition of implicit copy constructor for 'A' is deprecated because it has a user-pro... | This invokes A's copy constructor since other is a value copy.
inline A & operator=(A other)
Change it to
inline A & operator=(const A& other)
Then drop the swaps and simply assign other's member variables to *this
n=other.n;
s1=other.s1;
This removes the requirement for a copy constructor. However, defining an assi... |
70,727,914 | 70,728,281 | Segmentation fault when creating dynamic arrray | I'm doing work for school and my professor specifically asks for a dynamic array created without using a vector. The work I'm doing is a game that is played on an island and I need to use the dynamic array to create the island.
The island is a class that consists of an array of cells (which is another class). When I'm ... | In the Island class, you have a pointer to pointer Cell** zone. You will have to allocate memory twice. Once for Cell* and then for Cell. You will have to do something like this (probably!):
map->zone = new Cell*[rows];
for (int i = 0; i < rows; ++i)
map->zone[i] = new Cell[cols];
Then free the memory when d... |
70,727,970 | 70,738,024 | How to print a Binary Tree diagram (vertical) and ensure fairly unbalanced trees are not improperly printed? | I'm trying to write functionality to print a vertical binary tree diagram,
I've got the correct breadth-first search algorithm written, and it outputs the BFS-ordered tree traversal to an integer vector. The code can be seen below:
void bst::printlist(Node* node)
{
std::queue<Node*> travQueue;
std::vector<int>... | Here's a great answer, thanks to @NicoSchertler:
"You can push prev and next to travQueue even if they are nullptr. When you reach a nullptr in your iteration, add the dummy value to the result and two more nullptr to travQueue for the non-existing children."
And here's my code for it:
std::queue<Node*> travQueue;
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.