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 |
|---|---|---|---|---|
74,579,071 | 74,579,154 | Concept for using statement inside class | I have a class like this:
struct FooImpl {
public:
using Bar = int;
};
I would like to declare that FooImpl::Bar is an int through a concept.
This does the job:
template<typename Foo>
concept FooConcept = requires(Foo foo) {
{ std::vector<typename Foo::Bar>() } -> std::same_as<std::vector<int>>;
};
static_assert... | First, the reason { (typename Foo::Bar)() } -> std::same_as<int>; doesn't work is because of most vexing parse typename-specifier can’t be a declarator, and cannot be used within a C-styly-cast parentheses.* To make it work, you should use a brace init instead:
template<typename Foo>
concept FooConcept = requires(Foo f... |
74,579,182 | 74,579,344 | C++ decltype failed on vector elem | template <typename T>
void F(T&) { std::cout << __FUNCTION__ << "\n"; }
template <typename T>
void F(vector<T>&) { std::cout << __FUNCTION__ << "\n"; }
int main()
{
int x = 0;
F<decltype(x)>(x); // this line compile and works fine
vector<int> v;
F<decltype(v[0])>(v); //... | First, you do not have a v[0]. Even if you do have elements in v,* decltype(v[0]) will be int&, hence F<decltype(v[0])>(v) fails.
Note*: more in the comment about why having elements in v or not doesn't matter.
Second, remove_reference<decltype(v[0])> is the name of a struct, not a type. To properly get the type from ... |
74,579,458 | 74,579,541 | Opening a file in home directory | Say you have a program you run, and it has the following lines of code:
#include <fstream>
using std::fstream;
int main() {
fstream someFile;
someFile.open("~/someFile");
if(!someFile.is_open()) {
// Make the file
}
}
I'm trying to open a file in the home directory (i.e. "~" on Unix dev... | open has a second parameter: openmode, so you may want something like
someFile.open ("somefile", std::fstream::out | std::fstream::app);
if you want to append.
For the home directory you can check HOME environment variable and getpwuid:
const char *homedir;
if ((homedir = getenv("HOME")) == NULL) {
homedir = getp... |
74,579,511 | 74,579,580 | Why does my for loop print out a memory location | I'm doing a USACO prompt and when I print out the variable i it keeps on outputting a memory location(i think?). Each time I run it, it outputs something different at the end. I'm not sure if there is an uninitialized value since I'm not sure what variable it could be.
`
#include <fstream>
#include <iostream>
#include ... | When you do cout << doo, your printing the memory location of where doo starts. You need to print a specific index inside of doo to get the value.
For example, cout << doo[0] will print the first value inside your array (if it exists). cout << doo[1] will print the second element, and so on.
|
74,579,643 | 74,579,722 | Why does the starting directory matter when launching a OpenGL executable? | I am doing a openGL porject and readering my shaders from .vert and .frag glsl files. I am using CMake with an extension for auto ninja file generation as well. This is my readfile code:
std::string readFile(const char *filePath) {
std::string content;
std::ifstream fileStream(filePath, std::ios::in);
if(!... | If you run a program from a command line the current directory is whatever directory is current in that command prompt. If you run a program from explorer the current directory is the directory that houses the executable.
You could use a function like GetModuleFileName (with NULL as the hModule parameter) to get the pa... |
74,579,938 | 74,580,464 | Preserve References in C++ During Functioncalls | I want to preserve references during function calls in C++. In The following example the function baz creates two classes: Foo and Bar. The class foo is then passed to Bar as reference but instead of keeping foo until Bar is destroyed, it is destroyed after function execution.
In all other cases the foo references stay... | There is nothing that will allow you to extend the lifetime of a reference like you want. A reference does not give you that. Pointers are how we share and transfer ownership because it is only through a pointer that we can take on responsibility of deleting an object.
When we accept a reference as a parameter, we are ... |
74,582,018 | 74,582,265 | Ambiguous call when overloaded methods take reverse iterators in arguments | I'm trying to write an overloaded method that returns non-const result only when both the object on which it is called is non-const and iterator passed in the argument is non-const.
(Think of it like the standard methods begin() and begin() const that additionally take an iterator argument.)
I made a version for normal... | Oh the joys of overloading resolution rules and SFINAE.
The methods are equivalent to free functions:
void bbaz(Foo&,std::vector<int>::reverse_iterator){}
void bbaz(const Foo&,std::vector<int>::const_reverse_iterator){}
and your usage becomes:
int main()
{
std::vector<int> v;
Foo foo;
bbaz(foo,v.crbegin())... |
74,583,017 | 74,588,694 | I'm using PropertyChanged to update textblock, but when clicked, crashed: Application called an interface that was marshalled for a different thread | Now I'm trying to use PropertyChangedEvent to test update the textblock, but when I click, it crashed: WinRT originate error - 0x8001010E : The application called an interface that was marshalled for a different thread.
//in WordArray.cpp
namespace winrt::Lexical_Frequency::implementation
{
WordArray::WordArray(wi... | You'll frequently encounter this error when dropping code written for Microsoft's "Modern" UI platform (that never got a name) into a WinUI 3 application.
A bit of historic context: Alongside the "Modern" UI platform, Windows 8 introduced a variation of the STA, the Application STA (wildly undocumented1, no surprises t... |
74,583,083 | 74,585,146 | Awaiting a predicate with C++20 coroutines | We started using the modern C++20 coroutines on our project recently. There is a list of coroutines referred to as Tasks in the Executor, which steps through them one by one resuming them. All of this is done on a single thread. Sometimes coroutines need not to be resumed until some predicate is satisfied. In some case... | The "await" style of coroutines is intended for doing asynchronous processing in a way that mirrors the synchronous equivalent. In sinchronous code, you might write:
int func(float f)
{
auto value = compute_stuff(f);
auto val2 = compute_more_stuff(value, 23);
return val2 + value;
}
If one or both of these fun... |
74,583,288 | 74,583,375 | Cannot include .cpp and .h files in Visual Studio 2022 | I have created a class Dialog and separated it into .cpp (Dialog.cpp) and .h (Dialog.h).
My cpp file looks like this:
#include "Dialog.h"
#include <iostream>
using namespace std;
namespace Model1
{
void Dialog::initialize ()
{
cout << "initialization";
}
}
And here is my h file:
using namespace ... | The problem is that in the header file you've defined class Dialog in global namespace while you're trying to define the member function Dialog::initialize() in Model1 namespace.
This will not work because the out-of-class definition for the member function of a class must be in the same namespace in which the containi... |
74,583,543 | 74,585,508 | What is the expected lifetime of lpszClassName in WNDCLASS(EX)? | When creating a WNDCLASS(EX) in C++, one might do as follows:
WNDCLASSEX wndClass {};
wndClass.lpszClassName = "MyWndClass";
The data backed by the string literal is available for the whole program's lifetime.
So what if the data was only available during the invocation of RegisterClassEx?
{
char className[] = "MyWn... |
So what if the data was only available during the invocation of RegisterClassEx? Would this still work?
Yes, it is perfectly fine. The values that you register are copied by the OS until the class is unregistered at a later time. The actual WNDCLASSEX instance itself is no longer needed once RegisterClassEx() returns... |
74,584,065 | 74,584,290 | Benefit of promise/future compared to return by reference | I'm new to C++ threads concept and is trying to comprehend the benefit of the promise/future abstraction. With promise and future, I understand that it allows an async function to "return" like a regular subroutine does. However, it is not clear to me what it offers beyond using referenced argument to do the same thing... |
This is safe as I only grab the value after thread is join
Well, that's kind of the point, isn't it? Is it really "safe" if all it takes for some code to become "unsafe" is for someone to inadvertently use the variable at the wrong time? If the difference between "safe" and "completely broken" is changing the order o... |
74,584,691 | 74,584,834 | How to turn verilog gate-level code to C++ tree representation? |
module circuit(input a1, b1, d1, d2, output OUT);
wire a, b, c, d, e, f;
NOT A(a, a1);
NOT B(b, b1);
NOT C(c, a);
NAND D(d, d1, d2);
NAND E(e, b, c);
NAND F(f, d, e);
NOT G(OUT, f);
endmodule
Is there any method that is able to convert the above code to tree(in the attached the image shows the tree I want to con... | The Verilog syntax looks similar to C++ so you could try to shoehorn it into proper C++ although I doubt it would be a good idea :-D :
#include <vector>
#include <iostream>
enum class Op {
NOT, NAND
};
struct wire {
std::vector<wire*> inputs;
Op op;
bool constantValue = false;
bool evaluate() {
if (in... |
74,584,783 | 74,584,910 | Cannot use BOOST_STRONG_TYPEDEF with std::string | I'm using Boost's (v 1.71) strong typedef to differentiate a std::string but I'm having a few problems.
BOOST_STRONG_TYPEDEF(std::string, StrongString);
First, I would like to use StrongString with unordered_map, but when I overload the hash:
std::unordered_map<StrongString, int, std::hash<StrongString>> umap;
I get ... | The aim of BOOST_STRONG_TYPEDEF macro is generating a class that wraps and instance of a primitive type and provides appropriate conversion operators in order to make the new type substitutable for the one that it wraps.
std::string is not a primitive type.
The possible impl:
struct StrongString {
StrongString(const ... |
74,585,594 | 74,585,998 | partial_sum() position of previous | Using partial_sum(), I am trying to get the position from previous during the recurrence. I don't understand the result. I was expecting to get :
recurrence i=0
recurrence i=1
...
As the recurrence unfolds. But I am getting :
recurrence i=-48115006
recurrence i=-48115006
...
What am doing wrong ?
#include <vector>
#i... | The implementation for partial_sum that you are using is probably similar to the one described in cppreference, Possible implementation, Second version:
template<class InputIt, class OutputIt, class BinaryOperation>
constexpr // since C++20
OutputIt partial_sum(InputIt first, InputIt last,
OutputI... |
74,585,610 | 74,606,905 | Strange behavior from decrypt EVP envelope_open() | I have a simple program that encrypts files in a directory. I can iterate through and everything works perfectly. This is using pub/priv key pair. When decrypting one file at a time, it works as it should. However, if there are multiple files in a directory, or even if I put the filenames in a vector and fopen them for... | I was overwriting the key and iv returned from envelope_seal(). I looked over the fact it was unique. Each file must have this key and iv along with the private key and passphrase on the key to be able to decrypt a file. So this is definitely secure ... until someone cracks AES 256 of course.
|
74,586,138 | 74,586,221 | Simplifying rationals during assignment | I'm trying to assign the numerator and denominator values to a rational object, but need to reduce them to their smallest corresponding numbers. Say for example I input 10 for the numerator, and 20 for the denominator, I need them reduced down to 1/2. Below is my constructor that takes a numerator and denominator and a... | SUGGESTION:
Save the return value of "gcd()" into a temp variable
Step through the debugger to ensure each of the three variables are updated correctly:
Rational::Rational(int num, int denom) {
try {
int g = gcd(num, denom); // <-- Set bkpt here, step through in debugger
this->num = num / g;
... |
74,586,333 | 74,638,533 | (SOLVED) SFML-Audio LNK2001 error, linking error, I linked all the libraries but it doesn't work | when I try to use the SFML-Audio library, I get this error:
Severity Code Description Project File Line Suppression State
Error LNK2001 unresolved external symbol "__declspec(dllimport) public: __cdecl sf::SoundBuffer::~SoundBuffer(void)" (__imp_??1SoundBuffer@sf@@QEAA@XZ) War-Tech C:\Users\domon\Doc... | Just include sfml-audio.lib instead of sfml-audio-d.lib
|
74,586,572 | 74,586,756 | Is it legal to initialize a POD member of a base class before its constructor is called when it's not going to be initialized by it? | In the following code:
class Base
{
protected:
int v;
Base( void * ) { /* doesn't touch v at any point */ }
};
class Derived: public Base
{
public:
// Changes Base::v before calling Base::Base
Derived(): Base( ( (void )( v = 42 ), nullptr ) ) {}
};
Derived::Derived changes a POD member variable Base::v befor... | No, that is not valid:
class.cdtor/1
For an object with a non-trivial constructor, referring to any non-static member or base class of the object before the constructor begins execution results in undefined behavior.
Also see the example below the above paragraph:
struct W { int j; };
struct X : public virtual W { };... |
74,586,965 | 74,604,313 | How to get around not passing a copyable object to the MATCHER within MOCK_METHOD? | I am attempting at having a MOCK_METHOD BarClass::Bar throw an exception however I seem to be running into a following error
error: call to implicitly-deleted copy constructor of 'FooMock'
And it's probably happening at the == inside MATCHER_P.
It seems as though MOCK_METHOD creates a data member that's not copyable ... | Arguments to matchers are passed by copy per default. This is somewhat documented here. You can fix this by wrapping your argument in std::ref() or better std::cref() so you can't accidentally modify it:
EXPECT_CALL(barMock, Bar (Matcher(std::cref(*fooMock))))
.Times(1)
.WillRepeatedly(MyThr... |
74,587,129 | 74,587,291 | How to convert std::function to function pointer? | I need to use std::qsort() to sort an arry of nd-Point. But I get an error:
no known conversion from 'function<int (const void *, const void )>' to '__compar_fn_t' (aka 'int ()(const void *, const void *)')`
How to solve it, or sort it by dir in another method?
#include <iostream>
#include <functional>
int d, n;
str... | If you must use std::qsort then you are basically writing in C, not C++. This might be one of the few situations where a global variable is the least bad approach.
static thread_local int dir;
int cmp(const void *a, const void *b) {
auto a_ = (const Point *)a;
auto b_ = (const Point *)b;
return a_->x[dir]... |
74,587,411 | 74,587,437 | Why static global variables initialized to zero, but static member variable in class not initialized? | static int counter // will initalized to 0
but if I make that variable inside a class, it's not initialized and I have to initialize it outside of class
class Test {
static int counter; // not initialized
};
...
Test::counter = 0;
I know the static variables are stored in BSS segment in memory and initialized by def... |
Why static global variables initialized to zero, but static member variable in class not initialized?
Because the declaration for a non-inline static data member inside the class is not a definition.
This can be seen from static data member documentation:
The static keyword is only used with the declaration of a sta... |
74,587,807 | 74,588,550 | Cmake custom command conditional on build | I have an issue with cmake. Iv'e tried seraching all online but no answers and Ive tried many possible solutions and nothing has worked.
Im trying to copy a dll file into the executable directory automatically after the build and only if the dll file exists.
code Ive tried:
1.
add_custom_command(TARGET Game PRE_BUILD C... |
in checkFile.cmake
Do not add_custom_command in the script. It's in script mode, not cmake configuration. Actually copy the file. In checkFile.cmake:
if(EXISTS "${FROM}")
FILE(COPY "${FROM}" "${TO}")
endif()
and pass variabels:
add_custom_command(TARGET Game POST_BUILD
COMMAND ${CMAKE_COMMAND}
-P ${CM... |
74,587,853 | 74,588,131 | Binary files get corrupted while unzipping with libzip | I was required to unzip .zip files in my Qt project. So I installed libzip. I wrote a function to unzip a .zip file given its location and destination directory path. The function is correctly able to unzip plain text files (like .json, .txt, and others) but it always corrupts any type of binary files like PNGs or MP4s... | Instead of this:
int totalFileDataLength = 0;
while (totalFileDataLength != (long long) zippedFileStats.size) {
int fileDataLength = zip_fread(zippedFile, bufferStr, 100);
This:
zip_uint64_t totalFileDataLength = 0;
while (totalFileDataLength != zippedFil... |
74,587,930 | 74,587,950 | Storing multiple strings in nested structure | I have 2 structures named Phone and Patient, respectively:
struct Phone{
char description[4];
char number[10];
};
struct Patient{
int id;
char name[15];
struct Phone phone;
};
Now, on creating a patient's array like:
struct Patient patient = [
{1024, "Shaggy Yanson", {"CELL","3048005191"} },
]... | Yes it is. The problem is that C-style strings require one extra character to store a nul terminator. This is the character '\0' which is placed at the end of every C-style string. So, to store a string like "CELL" requires an array of size 5, not 4.
Of course, you can still store the 4 characters 'C', 'E', 'L' 'L' in ... |
74,588,501 | 74,588,733 | Sorting two arrays using C++23 zip view | There is a rather typical task of sorting two arrays simultaneously, assuming that same indexed elements of the arrays form virtual pairs, which are sorted. Such questions appear at least 10 years ago: boost zip_iterator and std::sort
Now this task can be solved using range-v3 library:
#include <array>
#include <range/... | At least the trunk version of libc++ (llvm) supports this:
std::ranges::sort(std::views::zip(x, y), [](auto&& a, auto&& b) {
return std::tie(std::get<0>(a), std::get<1>(a)) <
std::tie(std::get<0>(b), std::get<1>(b));
});
Demo
If you use three ranges instead of two, it works without having to supply a u... |
74,588,869 | 74,593,670 | What is decl-reachable in C++ 20? | §10.4/3 gives all the possible situations of decl-reachable in detail. However, I can't fully understand it. Consider the example described in §10.4/6:
Source file "foo.h":
namespace N {
struct X {};
int d();
int e();
inline int f(X, int = d()) { return e(); }
int g(X);
int h(X);
}
Module M interface:
mo... | N::f is decl-reachable from use_f due to rule 10.4.3.2.
In determining whether N::g is reachable from use_g, we find that neither 10.4.3.2 nor 10.4.3.3 applies.
10.4.3.2 does not apply because g((T(), x)) is a dependent call and thus, at the point of declaration of the template use_g, it can't be determined yet which ... |
74,588,958 | 74,591,625 | define anonymous enum with x-macros produces compilation error | Im working on a big project and I have a lot of errno macros.
I want to write a helper functions for the logger that stringify each of these errno to a string. i decided to use x-macros but Im getting compilation errors
in the first place the code was like this:
// project_errno.h
#define PROJECT_ERR_KEY_FAILURE ... | I'd follow the recipe shown in the Wikipedia page about X Macros:
Implementation
An X macro application consists of two parts:
The definition of the list's elements.
Expansion(s) of the list to generate fragments of declarations or statements.
The list is defined by a macro or header file (named, LIST) which generat... |
74,589,477 | 74,589,976 | Can a pointer to a memory be used as initialized trivial type? | Is it undefined behavior to use a trivial type without initialization?
void* mem = malloc(sizeof(uint64_t)*100);
void* num_mem = mem + sizeof(uint64_t)*31;
//does the lifetime of uint64_t starts here:
uint64_t* mynum = reinterpret_cast<uint64_t*>(num_mem); //?
*mynum = 5; //is it UB?
std::cout << *mynum << std::endl; /... | All of the following is following the rules of C++20, although the implicit object creation is considered a defect report against earlier versions as well. Before C++17 the meaning of pointer values was very different and so the discussion in the answer and the comments might not apply. All of this is also strictly abo... |
74,589,652 | 74,589,948 | Can you convert a pointer to an element in std::forward_list to the iterator to this element? | Since the std::forward_list is implemented as a single-linked list, its iterator should be just a pointer to the underlying element ± some offset.
Is there a way to convert a pointer to an element on a list to the iterator to this element without iterating through the entire list?
#include <forward_list>
template<type... | Short answer: Yes, I could hack a function makeIterator that does that:
template<typename T>
typename std::forward_list<T>::iterator makeIterator(T *element)
{
typedef typename std::forward_list<T>::iterator Iter;
typedef decltype(Iter()._M_node) NodeType;
static int offset = learnOffset<T>();
auto node = reint... |
74,589,757 | 74,589,961 | QT SQL Create table with placeholder as name | I want to create Tables which use the actual year as name.
All I tried ended up returning an empty file.
First I tried to convert the variable to hex:
query.prepare("CREATE TABLE " + year.toUtf8().toHex() +
"(buy_date DATE, "
"category VARCHAR(28), "
"price FLOAT, "
... | Well,
It does work as it should.
Can't use numbers as Table name:
query.prepare("CREATE TABLE '" + year + "' "
"(buy_date DATE, "
"category VARCHAR(28), "
"price FLOAT, "
"comment TINYTEXT)");
Or:
query.prepare(QString("CREATE TABLE %1 "
"(buy_da... |
74,589,767 | 74,589,842 | Function returning a pointer to the same function | In this code a function returns a pointer to itself
typedef void (*voidfunc)();
voidfunc f(int) {
return (voidfunc) f;
}
and generates the assembly was expecting, but uses a cast to a different function type to do so. How can this be done without casting in C++?
In other words what can be placed instead of ??? in... | It is impossible since the type of the function would need to be contain an infinite recursion.
The version with the cast is also not useful. Any actual use of the return value would need to cast back to the actual function type.
Without additional information about the use case it is difficult to make a recommendation... |
74,590,155 | 74,590,248 | Expected ";" before Object_name C++ | I have two files. One a header file named shape.h. I wanted to call the shapes from the class through the header file. But the file is not compiling.
#include <iostream>
#include <graphics.h>
using namespace std;
class Shape{
protected:
int x;
int y;
public:
Shape(){
x =0;
... | You need to but the case statements with declarations in { ... } blocks. You also need to add breaks to not fallthrough to the next case statement.
You also need to take the choice input from the user. You currently use choice uninitialized.
Example:
while (std::cin >> choice) {
switch (choice) {
case 1: {
... |
74,590,457 | 74,591,014 | CUDA deep copy with other data | I'm trying to copy my struct Test to the GPU, change the data, and upload it back to the CPU. This is what I've tried so far, note that my code crashes on the last, commented out, line:
struct Test {
int x, y;
int* data;
};
// Test kernel
static __global__ void TestKernel(Test* d) {
const uint32_t index =... | After you cudaMemcpy into the host struct back from the GPU, you override the data pointer in it with an invalid GPU data pointer.
In order to fix it you need to restore the original data pointer (and then copy the actual data).
Working version:
struct Test
{
int x, y;
int* data;
};
static __global__ void T... |
74,590,672 | 74,590,713 | How to include asio boost in cmake project | I'm trying to include asio boost using CMakein my project but I'm getting this error. libraries linking is working in VS but I don't know how to link them in Cmake project.
Working Solution with VS:-
asio boost version: 1.24.0
VS ScreenShot
cmake_minimum_required(VERSION 3.10)
project(networking_examples)
#set(CMAKE_... | When you use target_include_directories there is not target named networking_examples. You add that target after.
Order matters, and just like in C++ symbols must be defined before they can be used.
So you need to change to:
add_executable(
networking_examples
./src/index.cpp
)
# Asio library header directory
targ... |
74,590,755 | 74,591,152 | Shipping Python interpreter with C++ project | Problem description:
I have a Visual Studio 2022 C++ project that involves live python script interpretation. Naturally, I need a valid Python installation to do this. However, I intend to ship this as an application, so I'd like to have a localized Python installation, to avoid consumer-side installation, but that doe... | To embed python into your application, you need two things:
Initialize isolated python
This will not let user's system interfere with your app.
https://docs.python.org/3/c-api/init_config.html#init-isolated-conf
Deploy python stuff with your application
On windows, you need:
Python DLL (python311.dll).
Python standard... |
74,591,455 | 74,591,486 | How can I make an array of method pointers? | I want to create an array of pointers to methods, so I can quickly select a method to call, based on a integer. But I am struggling a little with the syntax.
What I have now is this:
class Foo {
private:
void method1();
void method2();
void method3();
void(Foo::*display_functions[3... | Yes, you can, you just need to take the address of them:
void(Foo::*display_functions[3])() = {
&Foo::method1,
&Foo::method2,
&Foo::method3
};
... however, it's likely better if you have virtual methods for an interface or a simple method that calls them all for a mu... |
74,593,059 | 74,593,486 | Protocol-Buffers C++ can't set variables | I'm new to C++ (and programming overall). Trying to understand protobuf and have some issues.
Here is the proto file:
syntax="proto3";
message FullName{
string Surname = 1;
string Name = 2;
optional string Patronymic = 3;
}
message Student{
FullName sName = 1;
repeated int32 Grade = 2;
int32 A... |
Student has no Name field, thus Student::set_name() cannot be available.
Student has FullName sName, FullName is not a base type, thus the setter is Student::set_allocated_sname(::FullName* sname).
Student sInfo = 1 is repeated values of not a base type in StudentsGroup, thus it should be accessed through the mutable ... |
74,593,507 | 74,593,908 | const&& binding to ref in lambda capture: clang vs gcc? | In the following code:
int foo() {
int a = 5;
auto l = [&r = std::move(std::as_const(a))] { return r; };
return l();
}
clang compiles just fine
gcc produces error.
error: cannot capture 'std::move<const int&>((* & std::as_const<int>(a)))' by reference
I need community help to argue about this case from C++ st... | Seems to be a GCC bug. The init-capture should behave as if declaring a corresponding variable with auto prefixed and which is then captured (exactly as in your quote from the standard):
auto &r = std::move(std::as_const(a));
This would deduce auto to const int so that the variable has type const int& and initializati... |
74,594,151 | 74,594,313 | How to enable structured bindings for a std::tuple wrapper class? | I'm trying to implement a wrapper class for another class that has a private std::tuple member and enable structured bindings on the wrapper class. Here's the class with the private tuple:
class widget {
friend class wrap;
std::tuple<int, double> m_tuple {1, 1.0};
};
Here's my attempt at the wrapper class after re... | In your second example usage you have
auto& [i_ref, d_ref] = wrap(w);
The auto& is the type for the invisible variable bound to the expression on the right side of the = which is a temporary. It's like doing
wrap& wr = wrap(w);
I learned this from T.C. in 2016, see that answer for all the relevant citations.
We can p... |
74,594,393 | 74,605,059 | Thread-safe stack in C++: combined top() and pop() | In his excellent book "C++ Concurrency in Action" (2nd edition including C++17) Anthony Williams discusses the implementation of a thread-safe stack.
In the course of this, he proposes an adapter implementation of std::stack, which, among other things, would combine the calls of top() and pop() into one. The separation... | std::optional does solve all of the mentioned problems, and using it to control lifetime can be quite valuable, although it would appear a bit strange in
std::optional<T> o;
st.pop(o);
to have o always engaged.
That said, with a stupid scope-guard trick it's possible in C++17 to safely return T even without requiring ... |
74,594,599 | 74,594,674 | p > nullptr: Undefined behavior? | The following flawed code for a null pointer check compiles with some compilers but not with others (see godbolt):
bool f()
{
char c;
return &c > nullptr;
}
The offensive part is the relational comparison between a pointer and nullptr.
The comparison compiles with
gcc before 11.1
MSVC 19.latest with /std:c++1... | 7.6.9 states, "The lvalue-to-rvalue ([conv.lval]), array-to-pointer ([conv.array]), and function-to-pointer ([conv.func]) standard conversions are performed on the operands. .... The converted operands shall have arithmetic, enumeration, or pointer type."
None of the specified conversions is applicable to the literal n... |
74,594,632 | 74,594,690 | How to change 1 or 0, into a true or false output | I have this hw assignment that I have completed. I am using a bool value in order for it to print 1 or 0. My question is how do I make it print out true or false, instead of the 1 or 0.
My output:
1 = true, 0 = false
------------
c1 >= c2 : 1
c1 <= c2 : 0
c1 != c2 : 1
c1 < c2 : 0
c1 > c2 : 1
c1 == c2 : 0
My code
int m... | It looks like we have some good options (ordered by time of submission):
std::cout << (compare ? "true" : "false");
std::cout << std::boolalpha << compare;
const char *s[] = { "false", "true" }; std::cout << s[compare];
|
74,594,651 | 74,594,694 | How to update a pointer member variable in C++ | This is the rough outline of my code. I've left out some details so let me know if you need more context.
class A;
class B;
class C {
public:
C(int dat, int idx) {
data = dat;
i = idx;
}
friend class A;
friend class B;
private:
int data;
int i;
... | You correctly wrote getPtr(int idx) (if I understand your spec. correctly). Now, the return value is C* there, which is not C*& or C**, so it won't be updated if you change the result afterwards - think of it as a return i; won't expose int i; member if return type is int.
So either:
you need to change the return type... |
74,594,653 | 74,594,747 | I have a question about merge sort algorithm | I've looked at the merge sort example code, but there's something I don't understand.
void mergesort(int left, int right)
{
if (left < right)
{
int sorted[LEN];
int mid, p1, p2, idx;
mid = (left + right) / 2;
mergesort(left, mid);
mergesort(mid + 1, right);
p1 ... | I'm a developer working in the field.
I was surprised to see you embodying merge sort.
Before we start, the time complexity of the merge sort is O(nlogn).
The reason can be found in the merge sort process!
First, let's assume that there is an unordered array.
Merger sorting process:
Divide it into an array of 1 size b... |
74,594,809 | 74,594,856 | the largest element in the array outputs as -858993460 [C++] | im trying to let the user input a number for each person. the console then outputs the maximum value in the array. everything works fine but the max always outputs as -858993460. i tried multiple combinations but i cant seem to figure it out
im new to arrays so any help would be appreciated as well as an feedback on ho... | int people[10];
This declares an array of ten int values. None of the values are explicitly initialized. This is how plain values that get declared in automatic scope work in C++, they are not initialized to any values. It is the code's responsibility to initialize them.
int max = people[0];
This sets the value of ma... |
74,594,984 | 74,594,989 | "./main: not found" (C++, RP 3/B, Geany IDE) | I'm attempting to write a simple program that calls a function written in a pair of Header and CPP files.
I'm doing this on a Raspberry Pi 3 Model B, and the Geany IDE v1.37.1.
Compile Command:
g++ -Wall -c "%f" -c test.cpp
Build Command:
g++ -Wall -o "%e" "%f" -o test test.cpp
main.cpp:
#include "test.h"
int main()... | Notice the compile command:
-o test
This means that the output binary will be test, so you can execute the application in your terminal or shell via ./test.
|
74,595,339 | 74,595,459 | How to declare and access method functions from different class files | So I'm writing a POS system for a project at school and I'm having trouble declaring the call method for each file to access the said methods
main.cpp
#include <iostream>
#include <windows.h>
int main()
{
AppUI UI;
SecuritySys SecSysFunc;
EditBook BookFunc;
UI.MainMenu();
}
AppUI.cpp
#include <iostrea... | You are getting a multiple definition error because you are just redeclaring the objects UI, SecSysFunc and BookFunc. You need to make it clear to the compiler that these identifiers point to the same object. You can do so by picking one of the four declarations to be the definition, leave those lines as is. But to the... |
74,595,458 | 74,597,610 | Should B-Tree nodes contain a pointer to their parent (C++ implementation)? | I am trying to implement a B-tree and from what I understand this is how you split a node:
Attempt to insert a new value V at a leaf node N
If the leaf node has no space, create a new node and pick a middle value of N and anything right of it move to the new node and anything to the left of the middle value leave in t... | Even if you don't use recursion or an explicit stack while going down the tree, you can still do it without parent pointers if you split nodes a bit sooner with a slightly modified algorithm, which has this key characteristic:
When encountering a node that is full, split it, even when it is not a leaf.
With this pre-em... |
74,596,501 | 74,596,572 | How to get values for the variables inside a class using a friend functions | #include <iostream>
#include <string>
using namespace std;
class person {
string name;
int age;
public :
person() {
name = "no data found";
age = 0;
}
person(string x, int y) {
name = x;
age = y;
}
friend void getdata(person);
friend void printdat... | You have to pass the person object by reference:
class person {
// ...
friend void getdata(person&);
friend void printdata(person const&);
};
void getdata(person& x) {
// ^
std::cout << "Enter name : " << std::endl;
getline(std::cin, x.name);
std::cout << "Enter age : " << std::... |
74,597,018 | 74,597,360 | Weird "╠" characters output in console from c++ console application (possibly char arrays?) | I'm trying to make a program that reads input from a file (it is named grades.txt) and make an output of (image attached)
.
Apparently, I'm converting strings to char arrays and my program's output quite unexpected (image attached) I have checked twice, the IDE doesn't show any errors as well.
I'm using this as the sou... | There are a few different problems in your code, but the main ones is that:
You start with inData.get(name, MAXNAME + 1) which reads only a part of the first line
You iterate over the whole array no matter its string length
The character array converter is just too small to fit a full line including the null-terminato... |
74,597,058 | 74,635,435 | Does ATR indicator include the current bar | I understand from the MQL4 documentation on the ATR indicator, that it can return the the value of the indicator for the current bar if 0 is used for the shift argument. However, when looking at the MQL5 documentation for the indicator, I notice that there doesn't appear to be any way to determine this. Possibly, this ... | According to @PaulB, index 0 always represents the current bar. Ergo, this code:
double values[];
int handle = iATR(Symbol(), PERIOD_D1, 10);
CopyBuffer(handle, 0, 0, 1, values);
was retrieving the Daily ATR for the current day, which includes the current bar. In order to fix this, I simply had to change the shift fro... |
74,597,682 | 74,597,704 | How to sort a UDT vector in descending order? | #include <bits/stdc++.h>
using namespace std;
class Point
{
public:
int x;
int y;
Point(int x = 0, int y = 0)
{
this->x = x;
this->y = y;
}
bool operator>(const Point &p1)
{
return (x + y) > (p1.x + p1.y);
}
};
int main()
{
vector<Point> v = {{1, 2}, {3, ... | Add the word const to your operator> method so that its signature becomes
bool operator>(const Point &p1) const
instead of
bool operator>(const Point &p1)
Adding const to this method means that you inform the compiler that the method won't modify the object that the method is associated with. That is required because... |
74,599,137 | 74,599,426 | When inheriting a Base class privately, can I declare the Base classes Basse class public? | I have a class "SuperBase" with public methods and a class "Base", that derives from SuperBase, also with public methods. I cannot alter these, as they come from an external project.
I want my own class "Derived" to inherit privately from Base, but still keep SuperBase public.
External Code (cannot be changed):
class S... | You could not actually derive from Base or SuperBase at all but rather use composition and cast operators:
class Derived
{
private:
Base mBase;
public:
void print() const
{
std::cout << "Derived Class\n";
}
operator SuperBase const&() const
{
return mBase;
}
operator SuperB... |
74,599,245 | 74,599,382 | rvalue Reference not matching | I have this exercise in which we try various combinations of rvalue and lvalue references using a template class, I am getting two assertion errors; if someone could guide.
#include <assert.h>
typedef int& IntLRef;
typedef IntLRef& IntLLRef;
typedef IntLRef&& IntLRRef;
typedef int&& IntRRef;
typedef IntRRef& IntRLRef... | This is called reference collapsing:
It is permitted to form references to references through type
manipulations in templates or typedefs, in which case the reference
collapsing rules apply: rvalue reference to rvalue reference collapses
to rvalue reference, all other combinations form lvalue reference
(emphasis adde... |
74,599,752 | 74,599,816 | Getting "exited with code=3221226356" error (STATUS_HEAP_CORRUPTION) while opening a output file stream | As evolution of a school exercise I'm making a program that writes a file in every subfolder starting from the location where the program is executed.
So there is a recursive function and another function called inside that writes the file.
If I execute this I get "exited with code=3221226356" error the second time I'm... | These two lines are a likely problem:
char * file_name_path = strdup(path);
strcat(file_name_path, separator);
The strdup call allocates enough memory for the string you want to duplicate, not a single byte more.
That means the strcat call will cause your program to write pout of bounds of the allocated memory, leadin... |
74,600,130 | 74,600,204 | How to make a class derived from the same base class twice, in C++? | Assuming that there is a class A.
I want my class to derived from A twice, in order to manage two A segment and visit their protected methods.
Like:
typedef A yetA;
class D: public A, public yetA {};
This doesn't work. Is there a method to do that?
| First off all... I'd caution you to rethink this design, because (barring any other details) it seems a little dodgy. I'm willing to bet composition may very well work better to manage those multiple instances.
But... if you are gonna do this, you can achieve it by intermediate inheritance. Can't have the same direct b... |
74,601,281 | 74,608,810 | [hiredis]Multiple hincrbys only return one result(REDIS_REPLY_INTEGER) | When using hiredis, use redisAppendCommand to put multiple hincrby commands, the reply->type result of redisGetReply is REDIS_REPLY_INTEGER, and only one of the results is returned.
But when I use hmget, the result of reply->type is REDIS_REPLY_ARRAY.
| Since you call redisAppendCommand multiple times, you should call redisGetReply the same number of times to get all replies. For each reply, it's of type REDIS_REPLY_INTEGER. Because the reply type of hincrby is integer type, or array type.
The reply type of hmget is array reply, and that's why you get REDIS_REPLY_ARRA... |
74,601,373 | 74,603,447 | Is owning the lock required to request a stop while waiting on a condition_variable_any with stop_token? | While waiting on a condition variable, the thread changing the state of the predicate must own the lock, so the update isn't missed during the wakeup. According to the documentation, this is necessary, even while using atomic variables.
However I'm not certain if request_stop() already handles it correctly.
So the ques... |
While waiting on a condition variable, the thread changing the state of the predicate must own the lock, so the update isn't missed during the wakeup.
... do not specify, if the interrupt of the wait is guaranteed register the change in the stop state.
The issue isn't exactly missing the update, but going back to s... |
74,601,482 | 74,601,821 | How to merge two numbers from two sorted files into a third file in ascending order | I'm trying to merge two files that contain some numbers into a third file but I'm not getting the right result.
This is my code:
void merge(string input_file1, string input_file2, string output_file){
fstream fs1;
fstream fs2;
fstream fs3;
int n1, n2;
fs1.open(input_file1);
fs2.open(input_f... | If n1 < n2, you do fs1 >> n1 twice (once immediately and then once in the loop condition) and discard both the first value and n2; if n1 >= n2, you do fs2 >> n2 twice and discard both its first value and n1.
You can't do any unconditional reading in the "selection loop", as you should only replace the smallest number.
... |
74,601,668 | 74,602,289 | Is it possible to terminate (compute) shader execution in OpenGL? | I have a compute shader that computes the Mandelbrot set. For deeper zooms this can take minutes. Is it possible to terminate the compute shader (for example if I pan or change zoom while it computes)? I'm using C++.
I guess I could let the shader do its computation in stages and check on the CPU-side if parameters hav... | There is no valid way to affect the execution of any OpenGL operation after it has already been told to execute. If you dispatch the work, you dispatched the work. You can't take it back later.
|
74,602,153 | 74,602,220 | C++ Parenthesis Operator Overloading Error | I am getting an unexpected error trying to implement ()-overloading according to the following get_chessman() method in a chessboard class: "expression preceding parentheses of apparent call must have pointer to function type". Am I overloading in the wrong way?
Minimal example code:
In chessboard header:
class Chessbo... | Just like you dereference cb in cb->get_chessman(7,4), you must dereference it in the line in question, like (*cb)(7, 4).
Side note: the way you code is reminiscent of Java where everything is a pointer. You should probably make use of simple variables, references, and standard containers (among other things) when codi... |
74,602,934 | 74,603,981 | how does this template parameter deduction work? | How did compiler decide to call bar function without knowing the type of template parameter T of foo function?
Usually when we call foo(2), T is deduced as int based on argument 2.
Here T is deduced based on parameters of function bar to which foo is passed.
#include <iostream>
template<typename T>
void foo(const T& a... | When you have an overload set like foo, meaning that the result of name lookup for foo results in (potentially multiple) non-template functions or function templates and the overload set has its address or a reference taken (here implicitly by passing it as a function argument), then the compiler will try to do overloa... |
74,603,194 | 74,605,112 | Is it possible to get a HMONITOR Handle from a Windows Object Manager Path? | I have a path that looks like this:
\\?\DISPLAY#IVM1A3E#5&1778d8b3&1&UID260#{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}
From that I would like to get a HMONITOR handle.
Using WinObj I can see under GLOBAL?? that it's a Symbolic link to some \Device\<number>.
How would I go about doing something like that?
Edit:
The path can... | You can use Connecting and configuring displays (CCD) API, especially the The QueryDisplayConfig function which retrieves information about all possible display paths for all display devices, or views, in the current setting.
With the following code, you'll get the correspondance between a Device Path and a Monitor (an... |
74,604,020 | 74,604,315 | File not updating after reading and writing | I am trying to read and write to a file.
My file contains just one line that has a value.
and this is my code where I am trying to calculate a mean value and write it in the file instead of the first one, but the file keeps containing 37.
long int moy;
std::string line;
std::fstream file;
long int x = 35 + ( std::rand... | The simple way is to close the file before reopening it for writing.
file.open ("C:/Users/MSI/Desktop/omnetpp-6.0.1/samples/inet4/src/inet/applications/udpapp/B1.txt", std::ios::in);
std::getline(file, line);
file.close();
std::cout<<line<<endl;
moy=(x+stoi(line))/2;
file.open ("C:/Users/MSI/Desktop/omnetpp-6.0.1/sampl... |
74,605,126 | 74,605,903 | Compile and execute cpp in xcode, and add additional execution instructions, Such as iconv command | Sorry, I'm new to Xcode and not very familiar with it, I use Xcode (command line tool project with external build system) to compile cpp files and automatically execute cpp unix executable files. After the program is compiled (command+R), I set the settings as shown in the screenshot below to automatically execute. Is ... | On the same place where you setup the build scheme, you can also add a post-build script.
Go to the left of the panel, and expand Build
Select Post-actions
Near the bottom center, click on + -> New Run Script Action
Add script like you would run them in terminal
Note the current directory will not be where the projec... |
74,605,269 | 74,605,874 | How does GCC optimize this `switch` | Today I discovered that GCC does some amazing magic for optimizing switches in this code:
StairsType GetStairsType(uint8_t tileId, uint8_t dlvl)
{
if (dlvl == 0)
return StairsType::Part;
if (tileId == 48) {
return dlvl >= 21 ? /* Crypt */ StairsType::Down : /* Caves */ StairsType::Part;
}
... | Both compilers compile this part in the obvious way:
if (dlvl == 0)
return StairsType::Part;
When it comes to this part:
if (tileId == 48) {
// This ID is used by both Caves and Crypt.
return dlvl >= 21 ? /* Crypt */ StairsType::Down : /* Caves */ StairsType::Part;
}
gcc checks til... |
74,605,459 | 74,605,468 | C++ - How to use preprocessor if statements(#if, #elif, #endif) inside a macro? | I am currently developing a program that I intend to be portable. I have access to both Windows and macOS, and I would like to be able to debug easily on both. When error handling, I want to have debug breaks in there to make it easy(__debugbreak() for MSVC). Since I intend to develop and test on multiple platforms, I ... | You can't. But you can do this:
#ifdef DEBUG
#ifdef _MSC_VER
#define DEBUG_BREAK __debugbreak();
#else
#define DEBUG_BREAK __builtin_trap();
#endif
#else
#define DEBUG_BREAK /*nothing*/
#endif
|
74,605,769 | 74,605,833 | Can't multiply two matrices, where hight and width are defined by template | I wrote Class Matrix, parameters of which I define by template. So when I tried to declare operator* between two matrices, I found out? that Cpp counts matrices with different parameters as different classes (For example 7x3 and 3x5). How can I avoid this?
Here is my class
template <size_t N, size_t M, typename T = int... | Template arguments are part of the type; otherwise they couldn't be considered in type resolution and SFINAE. Thus, there are two choices:
either make N, M runtime arguments of e.g. Matrix (or can even be deduced from current input), thereby making it non-template, or
you live with the fact that the concrete class de... |
74,606,432 | 74,606,521 | how to run consecutive commands in CMD when the first command starts a different instance (e.g. mysql -u root) | I'm stuck on a problem where I can't find a reasonable work around.
I'm trying to run multiple commands in the Windows CMD from inside a C++ Program using
CreateProcessW(NULL,L"mysql -u root -ptoor && source C:\Users\IEUser\Documents\SWE-Software\Datenbank\datenbank-build.sql", ... );
The Problem is that when i run th... | Update:
It turns out there is another problem that masked what will become a follow-on problem with &&:
Your mysql -u root -ptoor command enters an interactive session, which requires manual exiting before processing continues.
Once you make this call non-interactive, you need to apply the cmd /c fix described below... |
74,606,679 | 74,606,758 | Why are you allowed to re-define a extern variable in c++? | I have an extern variable declared in driver.h:
namespace org::lib {
extern bool myVar;
void myFunction();
}
I also have it defined in driver.cpp:
#include driver.h
namespace org::lib {
bool myVar = false;
void myFunction(){
if (myVar){
//....
}
}
}
Now I hav... | You don't define the variable in main, you assign it a new value
|
74,606,777 | 74,607,051 | Enabling certain template parameters based on user provided template arguments | Consider the following class template:
template<class T, std::size_t S, SomeEnum = SomeEnum::NOT_DYNAMIC>
class Foo {
Where SomeEnum would be defined as
class SomeEnum { NOT_DYNAMIC, DYNAMIC };
This class has a private std::array, but based on the value passed by the user to SomeEnum, I would like to instead use std:... | A similar situation in the standard library exists with std::span<T, N> or std::span<T>: Omitting the template parameter entirely defaults the size to std::dynamic_extent ((std::size_t) -1), which you can use to have a std::vector instead of a std::array:
template<class T, std::size_t S = std::dynamic_extent>
class Foo... |
74,607,691 | 74,607,817 | Substituting a reserved value dynamically doesn't work | I am trying to copy one dynamically reserved array into another, both of which are placed in a vector. But it does not work. Why?
struct A {
int *p;
};
int main()
{
vector<A> v;
A test;
test.p = new int[5];
//fill the array
for (int i = 0; i < 5; i++)
test.p[i] = i;
v.push_back(te... | The only thing in A is a pointer. When you push a copy of test to the vector, notice that the copied version in the vector will have a pointer pointing to the same location as the one that's not in the vector.
So later, when you delete the data from the outside copy, you are also deleting the data from the one in the v... |
74,608,229 | 74,609,229 | Do two consecutive DirectX 12 Dispatch() calls run sequentially or concurrently on the GPU? | When running two Dispatch() calls consecutively, like:
m_computeCommandList->Dispatch(111, 1, 1);
m_computeCommandList->Dispatch(555, 1, 1);
Is it guaranteed that the second Dispatch() will run after the first Dispatch() on the GPU? Or, could they run concurrently on the GPU?
Just to clarify, there is no more C++ cod... | Like in other graphics API, when you execute command calls on CPU side it leads to putting these commands to a command queue. It guarantees that commands will be processed in the order of queue, First-In-First-Out.
However, on GPU everything becomes massive parallel and concurrent. We can't know on what processing unit... |
74,608,299 | 74,608,300 | How can I use the control key as a wxWidgets accelerator on a Mac? | wxWidgets seems biased towards Windows, as 'Ctrl' binds to the control key on a Windows machine, but is converted to the command key on a Mac.
menuFile->Append(CONNECT_KEYSTROKE, wxT("&Connect\tCtrl-R"));
The code above shows up as ⌘R in your menu.
How do you bind to the control key on a Mac?
| Use 'RawCtrl'
menuFile->Append(CONNECT_KEYSTROKE, wxT("&Connect\tRawCtrl-R"));
The code above shows up as ^R in your menu.
|
74,608,824 | 74,609,365 | Difference between "using namespace name::space;" vs "namespace name::space{}"? | I have a namespace defined in A.h
namespace org::lib{
bool xyz = true;
}
I have B.cpp
#include A.h
namespace org::lib {
void function() {
if (lib::xyz){
//....
}
}
}
Why is lib::xyz in void function() able to correctly find 'xyz'? Since I'm already unde... | Name lookup proceeds from the scope the name is used outwards.
In the first example, the definition of function is nested inside namespace lib which is nested inside namespace org. When lib is looked up, first the function itself is searched, then org::lib, then org, and naturally lib is there.
In the second example, n... |
74,608,858 | 74,609,002 | Find max in pair vector c++ | I have a pair vector in c++
std::vector<std::pair<long, long>> currNodeAndChain
I want to find the maximum of the second element. Then push the first element to another vector corresponding to the max second element.
for (const auto& p : currNodeAndChain){
if (total_longest_chain(currNodeAndChain.begin(),... | you can try this:
// #include <algorithm> for sort
std::sort(currNodeAndChain.begin(), currNodeAndChain.end(),
[&](const auto& lhs, const auto& rhs)
{
return lhs.second > rhs.second;
});
result.push_back(currNodeAndChain.front().first);
|
74,608,902 | 74,609,155 | How to make `enable_if` a hard requirement | This answer contains the following code:
#include <type_traits>
template<
typename T, //real type
typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type
> struct S{};
int main() {
S<int> s; //compiles
S<char*> s; //doesn't compile
}
The requirement that T satisfy is_arithmetic can ea... |
Is there a way to foreclose this possibility?
Yes, there is as shown below. In particular, we can make the second parameter a non-type parameter with a default.
template<
typename T,
//make the second parameter a non-type parameter with default
typename std::enable_if<std::is_arithmetic<T>::value, nullpt... |
74,609,137 | 74,609,223 | Is there any case that the atomicity of std::atomic is not guaranteed, when is_lock_free() == false? | Even if is_lock_free() == false , typically maybe, the atomicity of std::atomic can be guaranteed. Is that right?
I wander that there are computer environments or cases where the atomicity is not guaranteed, when is_lock_free() == false.
| Non-lock-free atomics aren't address-free, so shared memory between two processes would mean they don't respect each other's lock. (Same for two virtual mappings of a page holding the same atomic object in the same process, unless the hash table of locks is only indexed on the low bits of the address, the offset-withi... |
74,609,303 | 74,634,992 | How to deallocate Ada Record from CPP | I am attempting to free a heap allocated Ada tagged record from cpp. I have used the code AdacoreU as a starting place.
I receive the following error when running the code below.
20
double free or corruption (out)
raised PROGRAM_ERROR : unhandled signal
Am I overthinking things? Do I need an Ada based deallocation me... | The problem is with the in out parameter to Del_Animal and its mapping to the C world.
Your intention with Del_Animal is that it should behave like Ada.Unchecked_Deallocation, in other words that the parameter is set to null (or 0!) after the call, but that means that what you have to pass is the address of the actual.... |
74,609,901 | 74,613,740 | How create a big array in shared memory with boost::interprocess::managed_shard_memory in fast way? | I created an instance of "boost::interprocess::managed_shared_memory" and constructed an array of char with "2 * 1024 * 1024 * 1024" elements. Unfortunately it took time more than 50 seconds.
namespace bip = boost::interprocess;
auto id_ = "shmTest"s;
size_t size_ = 2*1024*1024*1024ul;
auto ashmObj_ = make_unique<bip:... | Sidenote: I don't think the size calculation expression is safe for the reason you seem to think (ul): https://cppinsights.io/s/c34003a4
The code as given should always fail with bad_alloc because you didn't account for the segment manager overhead:
A puzzle about boost::interprocess::managed_shared_memory->size
Share... |
74,610,092 | 74,665,674 | (Windows) fatal error: sqlite3.h: No such file or directory | I am trying to build a c++ application that uses sql.
For that I need sqlite3 header. I have already installed sql in my system and
sqlite3 in terminal gives:
SQLite version 3.36.0 2021-06-18 18:36:39 Enter ".help" for usage hints. Connected to a transient in-memory database. Use ".open FILENAME" to reopen on a persist... | I found the solution to this problem:
included two files(*): sqlite3.0, sqlite3.h in same folder as my main code.
added #include "sqlite3.h"
compiled using the command: g++ sqlite3.o main.cpp -o main
This finally resolved my error.
*(these were downloaded from sqlite.org)
|
74,611,249 | 74,611,654 | std::promise::set_exception with type non extending std::exception calls terminate | In the following snippet
#include <iostream>
#include <future>
int main()
{
auto ep = std::make_exception_ptr( X ); // (1)
std::promise<int> p;
p.set_exception(ep);
try {
p.get_future().get(); // (2)
} catch(const std::exception& exc) {
std::cout << exc.what();
}
return 0;
... | As noted in comments, the problem is not catching the right type of exception, e.g. using catch(...).
|
74,611,284 | 74,612,057 | if user enter 5 then display the last 5 elements of linked list vise versa | i am stuck in my uni assignment....
i have an linked list of 20 elements, i have to take the value from user and if user enter 5 then print the last 5 elements of linked list
void traverse(List list) {
Node *savedCurrentNode = list.currentNode;
list.currentNode = list.headNode;
for(int i = 1; list.next... | For what little code you have, a review:
// Why are you passing the list by value? That is wasteful.
void traverse(List list) {
// I don't see you taking a value anywhere; surely you know how to do that
// What is happening here? Can't you just assign the head to something
// directly?
Node *savedCurre... |
74,611,503 | 74,612,625 | Why does QColor use 32-bit signed int to represent e.g. rgba values? | QColor can return rgba values of type int (32-bit signed integer). Why is that? The color values range from 0-255, don't they? Is there any situation where this might not be the case?
I'm considering to implicitly cast each of the rgba values returned by QColor.red()/green()/blue()/alpha() to quint8. It seems to work b... | I assume you are talking about QColor::rgba() which returns a QRgb.
QRgb is an alias to unsigned int. In these 32 bits all fours channels are encoded as #AARRGGBB, 8 bits each one (0-255, as you mentioned). So, a color like alpha=32, red=255, blue=127, green=0 would be 0x20FF7F00 (553615104 in decimal).
Now, regarding ... |
74,611,579 | 74,616,777 | coredump when calling virtual method of a dynamic allocated object | The snippet below will coredumped in fun() method. Why calling c->b.f() works in main() but failed in the function call?
class A {
public:
inline virtual void f() const {printf("A\n");}
};
class B : public A {
public:
inline void f() const override {printf("B\n");}
};
class C {
public:
B b;
};
void fun(cons... | You are allocating memory for class C using malloc, but this doesn't create any object of class C. your program don't have any valid object and have undefined behavior.
As it is undefined behavior, your program may fail or may not be at c->b.f();
If you really want to use malloc, you should use placement new in your pr... |
74,612,412 | 74,612,490 | g++ failing when trying to use GDAL library | I just want to compile this easy example of the GDAL library in my Ubuntu 22.04 system using the system-packed g++, version 11.3.0:
#include <iostream>
#include "gdal_priv.h"
#include "cpl_conv.h"
#include "gdal.h"
using namespace std;
int main(int argc, char* argv[])
{
GDALDataset *poDataset;
GDALAllRegis... |
Include paths have nothing to do with the symbols.
-I/usr/include/gdal -L/usr/lib both are not necessary as they are set by default. But you should use #include <gdal/gdal.h>, not just <gdal.h> and certainly not "gdal.h".
Move -lgdal after all other cpp/object files.
In general, it should be g++ <OPTIONS> <OBJECTS>... |
74,613,359 | 74,615,623 | What is the correct way to get beginning of the day in UTC / GMT? | ::tm tm{0, 0, 0, 29, 10, 2022 - 1900, 0, 0}; // 10 for November
auto time_t = ::mktime(&tm);
cout << "milliseconds = " << time_t * 1000 << endl;
Above code outputs 1669660200000, which is equivalent to 2022 November 29, 00:00:00. But it is in local timezone. How to get the UTC time for the aforementioned date?
A mode... | There's a nit picky weak point in your solution (besides the thread safety issue): The members of tm are not guaranteed to be in the order you are assuming.
The tm structure shall contain at least the following members, in any order.
Using C++17 you can use this C++20 chrono preview library. It is free, open-source... |
74,614,005 | 74,614,511 | How to get class member variable that require lock without manual lock and unlock? | [EDIT]
Does anyone know how to get a class member container that require lock from outside properly?
Writing to a class member can be done as below if critical section is used for locking.
EnterCriticalSection(&m_cs);
// write
LeaveCriticalSection(&m_cs);
However, if it is necessary to lookup this container to find da... | If what concerns you is caller potentially missing lock/unlock calls, then a RAII pattern might be of help:
class CObjectManager
{
private:
CRITICAL_SECTION m_cs;
std::map<unsigned long long, CObject> m_mapObject;
public:
CObjectManager()
: m_cs{}
, m_mapObject{}
{
InitializeC... |
74,614,564 | 74,614,831 | Input Handler not working as intended C++ | I am trying to make a program that reads from the keyboard a number corresponding to an index of an answer for a question and returns an error message if the type of date entered is wrong.
float Handlers ::InputHandler(string Question, unsigned short int Number_of_Answers)
{
float Answer;
cout << Question << ... |
It is as if from 1ddga it read 1, and the rest was stored somewhere
That's completely correct, if by 'stored somewhere' you mean that it remains in the console buffer waiting to be read next time around. This is how operator>> on an float is defined to work. It reads characters until it finds a character which cannot... |
74,614,615 | 74,625,693 | How can I make single object larger than 2GB using new operator? | I'm trying to make a single object larger than 2GB using new operator.
But if the size of the object is larger than 0x7fffffff, The size of memory to be allocated become strange.
I think it is done by compiler because the assembly code itself use strange size of memory allocation.
I'm using Visual Stuio 2015 and config... | Use a compiler like clang-cl that isn't broken, or that doesn't have intentional signed-32-bit implementation limits on max object size, whichever it is for MSVC. (Could this be affected by a largeaddressaware option?)
Current MSVC (19.33 on Godbolt) has the same bug, although it does seem to handle 2GiB static object... |
74,616,199 | 74,616,331 | Why is my compiler "optimizing" this for loop into an infinite loop when compiled with -O3 in C++ | I am trying to understand what optimization process causes the following code to produce an infinite loop when compiled with the -O3 optimization flag. To get it out of the way, I understand that the real root cause of the issue is the lack of a return in this non void function, I happened on this interesting behavior ... | Undefined behaviour results in time travel.
Your code is a good example of it.
You have undefined behaviour after the loop (a function that must return a value doesn't). Since the compiler is allowed to assume that UB never happens, it assumes that the loop never terminates, and compiles it accordingy.
|
74,616,783 | 74,619,790 | SWIG: Passing a list as a vector<double> pointer to a constructor | Trying to use swig to pass a python list as input for c++ class with a (one of many) constructor taking a std::vector<double> * as input. Changing the C++ implementation of the codebase is not possible.
<EDIT> : What I am looking for is a way to "automatically" process a python list to a vector<double> * or say for exa... | The Python list passed into the non-default constructor gets converted to a temporary SWIG proxy of a vector<double>* and that pointer is saved by the constructor into SampleClass's m_v member, but the pointer no longer exists when the constructor returns. If you create a persistent doublevector and make sure it stays... |
74,616,809 | 74,622,173 | "imwrite" within CC Dynamic Android Library not found when beeing called from C-Code | I am using OpenCV 4.6.0 Android SDK which I downloaded from sourceforge and use it within my shared library/.so. This library is called from within my android app (aarch64). Building works fine using my android.toolchain.cmake :
...
set(CMAKE_C_COMPILER /home/username/Android/SDK/ndk/25.1.8937393/toolchains/llvm/prebui... | It's not about mangling, you just didn't link with all the OpenCV libraries that you need.
You're using OpenCV version 4.6.0. I see that you're calling imwrite, and you're linking with the highgui module. Well, once upon a time (in 2.4.x) that would have worked, but IIRC since 3.x (and definitely in 4.x) this function ... |
74,617,047 | 74,617,113 | How to use the type mentioned in input for creating an object? | Say I have a templatized class
template<class T>
class MyClass
{
...
}
Now let's say for the sake of simplicity, that the input explicitly mentions that the following data shall be of what type:
for example
int
1 2 3 4 5
or
float
1.5 2.3 4.2 5.9
Now I want to create an object based on the type mentioned in the inpu... | You can't:
template are compiler time, the specific content between < .. > is replaced when you build, and that can not be modified runtime based on the input.
The solution to your problem (about having different types defined runtime) is to use an other mechanism, like std::variant.
|
74,617,148 | 74,621,289 | How do I register my Clang Static Analyzer checker | I am fully aware that this question has previous answers. However, those answers are old and don't reflect what is happening in the current code base.
I have followed the steps in this guide for developing the checker, registering it with the engine, and testing it.
After some work, I was able to compile the code but w... | UPDATE: A Clang contributor provided me a helpful answer that fixed my problem. via the llvm discorse
|
74,618,586 | 74,625,453 | Can you mock C functions with Googlemock without creating a global mock instance? | The generally used approach of wrapping free C functions in a "Mockinterface" class with a child class "Mock"(that calls MOCK_METHOD) results in the need of a global mock variable in order to use it in a TEST.
Is there another design approach that does not need a global Mock object/pointer so we could use a local Mock ... | It doesn't matter whether the mock object is globally static, locally static, or locally dynamic. You just need to make sure that it exists when the mocked C function is called and wants to call the method of the mock object.
The important part is that the per-se static C functions need to access that mock object. In c... |
74,618,642 | 74,619,396 | Can runtime and constexpr nan comparisons disagree? | I was writing a constexpr bool isfinite(Float) function because I'm not on C++23 yet and so my std::isfinite isn't constexpr. But CI said MSVC didn't like something.
In general, nan should compare false with anything with all comparisons other than != which should always be true: https://en.wikipedia.org/wiki/NaN#Compa... |
Am I into implementation-defined behavior?
From C++ perspective: Yes, sort of. The non-finite floating point comparisons are not defined by the C++ standard. That said, static_assert(std::numeric_limits<float>::is_iec559) brings in another standard into consideration.
From IEC 559 aka IEEE-754 perspective: No, the co... |
74,618,780 | 74,618,825 | how to create specialization of method inherited from class template instantiation | I have a base class template and a class deriving from an instantiation of it:
template<typename T>
class Bar
{
template <T t>
void Foo();
};
class Derived : public Bar<int> {};
How should one implement Derived::Foo<0>() for example?
when trying this out:
template<>
void Derived::Foo<0>() { /* impl.. */}
i get... | You cannot specialize it in the descendant; you can only add a signature that'll serve as an overload and delegate as necessary:
template<typename T>
class Bar
{
template <T t>
void Foo();
};
class Derived : public Bar<int> {
using Base = Bar<int>;
template <int t>
void Foo()
{
if constexpr(t ... |
74,618,938 | 74,619,026 | inspecting 2D array inner type | I am trying to check if the type of an array element is a specific type. See the following.
#include <type_traits>
#include <cstdint>
#include <iostream>
int main() {
using arr = std::int32_t[2][2];
std::cout << std::is_same_v<decltype(std::declval<arr>()[0][0]), std::int32_t> << std::endl;
}
>>> 0
Why is t... | The type of the expression is lvalue reference to std::int32_t. You can use remove_reference to get the expected std::int32_t:
#include <type_traits>
#include <cstdint>
#include <iostream>
int main() {
using arr = std::int32_t[2][2];
std::cout << std::is_same_v<decltype(std::declval<arr>()[0][0]), std::int32_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.