question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
71,369,225 | 71,369,259 | No access to static (non-primitive) members in constructor of global variable in C++ | The following code works fine when using e.g. int instead of std::string, std::map etc.
I have a global variable that needs an entry of the static member when using the default constructor, but this string is empty here. The variable "test" does not have to be inside the class itself. I think there is some initializati... | The order in which objects with the static storage duration are initialized in different compilation units relative to each other is unsequenced.
From the C++ 14 Standard (3.6.2 Initialization of non-local variables)
...Otherwise, the initialization of a variable is indeterminately
sequenced with respect to the initi... |
71,369,601 | 71,369,680 | C++ Modifying pointer in Range based for loop | I tried to modify pointer of object in array like this.
array<unique_ptr<Object>, OBJ_SIZE> OtherList; // All Object were allocated already.
array<Object*, OBJ_SIZE> ObjectList;
Object* GetPointerFromOtherList(int i) { return OtherList[i].get(); }
for(int i = 0; Object* obj : ObjectList)
{
// Store pointer of p... | With Object* obj : ObjectList, obj is a copy of the pointer element of ObjectList. Assigning to that copy with obj = GetPointerFromOtherList(i); doesn't change anything in the container, since obj is just a completely independent variable.
With Object*& obj : ObjectList, obj is a reference to the pointer element in Obj... |
71,369,661 | 71,370,568 | How to delete faces from mesh using openmesh? | Pretty much the title I am trying to delete a few faces of a mesh using open mesh, like this:
MyMesh mesh;
char fname[1024];
sprintf(fname, "box_%i.obj", 0);
if (!OpenMesh::IO::read_mesh(mesh, std::string(fname)))
{
std::cerr << "read error\n";
exit(1);
}
MyMesh::FaceIter ... | I think iterator being invalid after removing an element in it.
for (v_it=mesh.faces_begin(); v_it!=v_end; ++v_it)
{
mesh.delete_face(*v_it, true);
v_it = mesh.faces_begin(); //<- add this to test
}
|
71,369,807 | 71,369,937 | Is it safe to assign pointer from multiple threads in below situation? | I have a struct Node. Inside is a pointer to next Node (Node *next).
My graph is such that every next pointer can only point to one node and the same node that is already present in the graph.
In my example multiple threads can operate on nodes. Consider below example, while knowing that nodes a and b are safely added ... | Unsynchronized concurrent writes to the same non-atomic variable cause undefined behavior.
[intro.races]/2:
Two expression evaluations conflict if one of them modifies a memory location ([intro.memory]) and the other one reads or modifies the same memory location.
[intro.races]/21
... The execution of a program cont... |
71,369,830 | 71,372,852 | how do I get consistent execution times? | I am preparing for a coding challenge, where the fastest calculation of pi to the 10000th digit wins. all calculations will be run on a raspberry Pi4 running linux during competition.
I want to know which code runs the fastest, so I can know which function to submit.
so I wrote a little program named "lol" to try and e... |
instead of executing a program, measure a function completion in a single program:
auto start = high_resolution_clock::now();
//function being timed:
my_func();
// After function call
auto stop = high_resolution_clock::now();
you are using chrono header. so why usleepwhen you can use ... |
71,370,203 | 71,370,242 | How can I render RGBA4444 image in OpenGL? | I try to render my image in RGBA4444 without converting to RGBA8888,but....
// Define vertices
float vertices[] = {-1.f, 1.f, 0.f, 0.f, 1.f, // left top
1.f, 1.f, 0.f, 1.f, 1.f, // right top
-1.f, -1.f, 0.f, 0.f, 0.f, // left bottom
1.f, -1.f, 0.f, 1... | 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 a pixel of an image with the format GL_UNSIGNED_SHORT_4_4_4_4_REV only needs 2 bytes, the size of a row of the image may not be aligned to 4 bytes.
When the im... |
71,370,463 | 71,371,468 | What does multimap find() return in existence of multple objects with same Key? | Is multimap find(key) guaranteed to return an iterator to the FIRST element with key "key" ?
I couldn't find a proper answer in documentation anywhere.
| std::multimap::find(key) returns an iterator on any element whose key compares equal to key:
Finds an element with key equivalent to key. If there are several elements with key in the container, any of them may be returned.
|
71,370,466 | 71,371,590 | How to specialize templated method within class template? | I'm trying to do some Resolution struct which simply holds my width_ and height_ of screen.
I will use it a lot in certain ways, and some methods will require a vector like data and some will require and internal structure-like data.
Example:
template<typename InternalType>
struct Resolution
{
InternalType width_;
... | In the example shown, I don't see a need for any specialization, partial or otherwise. This is sufficient:
template <typename Ret>
Ret vectorRepr() {
return {width_, height_};
}
Demo
|
71,371,958 | 71,372,001 | infinite loop on linked list | The while statements are kept on running even when I set the statement != 0.
The displayLinkedList uses iteration which works normally,
the displayLinkedListRe uses recursion, which is running as an infinite loop. Also, the function sizeOfLinkedList which is supposed to return a linked list is also running as an infini... | There are multiple problems:
The loop in createLinkedList runs one time too much: you should write
for (i = 1; i < n; i++)
The functions displayLinkedList() stops too soon. You should write:
void displayLinkedList(struct node *p) {
while (p != NULL) {
cout << "the element is " << p->data << endl;
... |
71,372,399 | 71,372,517 | Why do functions disabled by C++20 `requires` clauses still cause ill-formed type errors? | Working with C++20's requires statements, I've noticed that using requires to selectively disable a function definition breaks if a type in that function would be ill-formed -- even though the function is not enabled.
The simplest example I've found for this is anything with a T& where T may be void, for example:
templ... | The problem is that the function signature is syntactically invalid. void const & is not a legitimate type in C++. So the compiler never gets to the requires clause for the function. It never gets to consider whether the function should or should not be discarded because the function is not a legal function signature.
... |
71,372,437 | 71,372,555 | Making this function more like C++ and less like C | I have this function which opens /dev/urand and reads into a pointer of size; however it's very C like and not very C++ like. I want to make the function look more like modern C++.
void URand::getrandom(uint64_t* r,uint8_t s){
FILE* f = fopen("/dev/urandom","rb");
assert(f);
switch (s) {
case 8... | I would probably do something like this:
template<typename Unsigned>
Unsigned dev_urandom()
{
Unsigned u;
std::ifstream("/dev/urandom", std::ios::binary).read((char*)&u, sizeof(u));
return u;
}
int main()
{
std::cout << dev_urandom<unsigned int>() << '\n';
}
Or, if you prefer:
template<typename Unsign... |
71,372,504 | 71,373,448 | strcpy function with dynamic allocated char array | I am facing problems to make this piece of code work:
char **createCharArray() {
char **charArray = new char*[PARAM_COUNT];
for (int i = 0; i < PARAM_COUNT; ++i) {
charArray[i] = new char[MAXSIZE];
}
return charArray;
}
void deleteCharArray(char **charArray) {
for (int i = 0; i < PARAM_COU... | There are a few things I find troublesome. First, you've seen people say you should use std::string instead of char arrays, and that's true. But new programmers should understand the entire language, and so understanding how to use char arrays has value.
So let's ignore C++ strings and look at your code:
char ** test =... |
71,372,599 | 71,372,679 | C++ destructor called timing for returned value | Consider C++ code as below:
struct V {
int s;
V(int s): s(s) {}
~V() { cout << "Destructor\n"; }
};
V f() {
V x(2);
return x;
}
int main(){
V a = f();
cout << "Function End\n";
return 0;
}
The execution result shows that the destructor is called only once.
Function End
Destructor
However, if I add a... | In the first example, NRVO (Named Return Value Optimization) may kick in and elide the copy in return x;.
When you have two exit paths, not returning the same variable, NRVO is less likely to kick in and you'll actually get a copy, even though if(false) is never going to be true.
The below would most likely also elide ... |
71,372,680 | 71,372,828 | polyBasePtr->~PolyBase() : is this really a virtual call? | Since destructors are rarely called explicitly, I wonder if standard guarantees
that calling explicitly a virtual destructor on a base class pointer
will invoke a dtor of the most derived object.
In cases I checked, this is indeed what happens in gcc, clang and msvc,
but I would still like to know that it is really gua... |
[class.dtor]/14 In an explicit destructor call, the destructor is specified by a ~ followed by a type-name or decltype-specifier
that denotes the destructor’s class type. The invocation of a destructor is subject to the usual rules for member functions (12.2.1)
[ Example:
struct B {
virtual ~B() { }
};
struct D : B ... |
71,372,734 | 71,372,815 | How to print the elements of an array of structures? | I am new to c++ , I was trying to print the fields of a structure using an array.
I know the compiler is not able to understand what is inside deck[1] in the line for(int x:deck[1]), since deck[1] is an unknown data type (a structure datatype defined as 'card'). So x is not able to scan the elements within this data ty... | Note that you can't loop through the data members of an object of a class type such as card. You can only print out the data members individually. So you can use operator overloading to achieve the desired effect. In particular, you can overload operator<< as shown below.
#include <iostream>
struct card
{
int face... |
71,373,002 | 71,373,131 | SetWindowLongPtrA callback function | I want to use the Windows API to get keyboard input from a window. From what I have heard, I can create a callback function that will be called when some events happen. I just don't know how.
ModuleManager::ModuleManager() {
HWND getGameWindow = FindWindow(NULL, TEXT("GameName"));
wndProc = (WNDPROC)SetWindowLo... | It seems i figured it out.
The callback function must be a static function for some reason.
So the correct code is following:
ModuleManager::ModuleManager() {
HWND getGameWindow = FindWindow(NULL, TEXT("GameName"));
wndProc = (WNDPROC)SetWindowLongPtrA(getGameWindow, GWLP_WNDPROC, (LONG_PTR) &ModuleManager::Wnd... |
71,373,263 | 71,396,161 | OPENCV C++: Sorting contour by using their areas | Few days back ive found a code which is sorting a contours inside vector by using their areas.But i could not understand the code very well especially in comparator function. Why does the contour 1&2 are convert into Mat in the contourArea parameter? Can anyone explain me the whole code in step by step. Your explanatio... | Your input image is binary, so it only exists of 0 and 1. When you use cv::findContours it searches for points with the value '1' and are touching other 1's, this makes a contour. Then puts all contours in std::vectorstd::vector<cv::Point> contours.
When you would take a grid and draw the points of one contour in it, y... |
71,373,418 | 71,373,647 | To byte conversion in c++ | i tried making a c++ function that takes in a pointer and then returns a pointer to a char array representing the bytes
char* toBytes(void* src, int byteSize) {
char convertedToBytes[byteSize];
memcpy(&convertedToBytes, src, byteSize);
return _strdup(convertedToBytes);
}
though when using i... | I suggest using a std::string:
template<class T>
std::string toBytes(const T& src) {
return {reinterpret_cast<const char*>(&src),
reinterpret_cast<const char*>(&src) + sizeof src};
}
or if you don't need to be able to change the content, a std::string_view:
template<class T>
std::string_view toBytes(co... |
71,373,675 | 71,395,859 | Differentiate between appending objects with similar color | I am trying to detect each ball, count how many there are, and get their location. I am currently using Canny Edge Detection for that which works pretty well if the balls don't touch each other:
The problem I have is that if the balls are touching, it is not possible to differentiate between them anymore and they are ... | What you could try is to filter the frame on red and green, so you get the contours of your balls. Then use a watershed algorithm to separate the contours.
Watershed example: https://docs.opencv.org/4.x/d2/dbd/tutorial_distance_transform.html
|
71,373,716 | 71,378,361 | Achieving Time Complexity O(n) - Searching Preorder Binary Tree C++ | Binary Search Tree LCA
Have the function BinarySearchTreeLCA(strArr) take the array of strings stored in strArr, which will contain 3 elements: the first element will be a binary search tree with all unique values in a preorder traversal array, the second and third elements will be two different values, and your goal i... | The algorithm you have implemented is indeed not O(n). The buildTree function has in fact a O(nlogn) time complexity.
In order to solve this challenge with a linear time complexity, you could even omit building the binary search tree all together.
Instead, take these observations into consideration:
If a node is a com... |
71,374,216 | 71,376,544 | std::vector, char *, and C API | I want to use some C API that requires a buffer of char, I'm thinking of using std::vector as the backer buffer. What I have in my mind for now is
obtain the size required by the C API
create a vector and reserve its size accordingly
feed the vector to the C API
get the number of bytes written by the C API
resize the ... | What you have is very close, but it could use some subtle changes:
auto buffer = std::vector<char>{};
buffer.resize(required_size);
can be reduced to
std::vector<char> buffer(required_size);
And buffer.capacity() needs to be either required_size or buffer.size().
int main(){
auto required_size = get_required_buffer... |
71,374,293 | 71,374,552 | Pass parameterized function and list of parameters using c++20 Concepts | I have a function foo that take one parameter of any type like this:
void foo(int& x)
{
x = 4;
}
Now i want to create a templated function bar that takes a function with 1 parameter and a list of parameters to call the function with.
template<typename Func, typename Params>
void bar(Func func, Params params)
{
... | You solve this by using the tools the standard library gives you. You use theinput_range and the invocable concepts, providing the range_reference_t type of the given range as the parameter to the invoked function.
template<typename Func, std::ranges::input_range Rng>
requires std::invocable<Func, std::ranges::range_... |
71,374,410 | 71,374,486 | Do pointer return types always needs to be allocated on heap? | I am new to C++ and I am currently learning Heap and Stack. In our class we had a problematic function like this
int* Problematic(int capacity) {
int data[capacity];
// do something
return data;
}
I know this won't return anything but a dangling pointer(is it?) since stack will deallocate everything in ... |
Yes. Returning a local non-static address has little value. Such returned addresses are unusable for dereferencing. You can still printf("%p\n",(void*)the_address) them but that's about all you can do with them. (Returning the address of a local static makes sense, though. Such a returned local address is safe to dere... |
71,374,433 | 71,374,956 | AnimateWindow not calling WM_PAINT | I need to animate the display of the rendered window, I have a WM_PRINTCLIENT and WM_PAINT event, but the window is not rendered during the animation, only if RedrawWindow is used after the animation is shown
WNDCLASSW Wcc;
MSG Msg;
Wcc.style = CS_HREDRAW | CS_VREDRAW;
Wcc.lpfnWndProc = &this->_ChildWndProc;
Wcc.cbClsE... | I have adopted your code, so that I can run it in isolation. I do get debug output WM_PRINTCLIENT during animation.
void foo(HINSTANCE hInst, HWND hParent) {
static const wchar_t* className = L"myClassName";
WNDCLASSW Wcc = {};
MSG Msg;
Wcc.style = CS_HREDRAW | CS_VREDRAW;
Wcc.lpfnWndProc = ChildWnd... |
71,375,460 | 71,377,822 | Is there a way to specify a function's return type as a template parameter | I have a function template that I'm writing, which deals with a lot of objects of type N (which can only be a couple of different things, but there's a lot of logic in this template which I don't want to duplicate in separate functions). In several places in this function, I also have declarations like auto somevar = S... | As some others have said, you should use decltype. So you'll write std::unordered_set<decltype(SomeFunction(someobject))> as your return type.
Sidenote: You might find mention online of typeof which the GCC compiler added support for before C++11 added decltype. typeof works in the same way as decltype but isn't part o... |
71,375,931 | 71,376,216 | template needs typename declared with each class member functions returns yet not able to link when compile? | I have a class with template and class member with return type of the template class.
// in header
namespace A
{
template<class Data>
class Tree
{
enum class InsertionStatus
{
INSERT_LEFT,
INSERT_RIGHT,
NO_INSERTION,
INSERTION_COMPLETE
};
struct Node
{
... | Each template function is a unique function from the point of view of the linker.
Consider the module where the function is being called. Whenever you call the function, the compiler generates the call to the Tree<Data>::insertNode function where Data is a concrete type known in the module. If you define the template f... |
71,375,998 | 71,376,096 | A class has incomplete type | #include<bits/stdc++.h>
using namespace std;
class B;
class A{
public:
int a_i=10;
void A_lookup(B b){
cout << b.b_i <<endl;
}
};
class B{
public:
int b_i=20;
void B_lookup(A a){
cout << a.a_i <<endl;
}
};
int main(void){
A a;
B ... | The problem is that when you wrote:
void A_lookup(B b){ //this statement needs B to be a complete type
cout << b.b_i <<endl; //this also needs B to be a complete type
}
In the above member function definition, the parameter b is of type B. And for B b to work, B must be a complete type. Since you h... |
71,376,574 | 71,376,644 | How can we insert a character to a string in c++? | INPUT STRING
ABCE
INPUT CHAR
D
OUTPUT STRING
ABCDE
It should run for all sizes , and it should be a standard procedure ie run for all the cases.
Can anyone Help me with this? Any help would be appreciated.
| You should try the std::string::insert(..). Check out the documentation
#include <iostream>
#include <string>
int main() {
std::string str("ABCE");
std::cout << str << std::endl; // ABCE
str.insert(3, 1, 'D');
std::cout << str << std::endl; // ABCDE
return -1;
}
|
71,376,632 | 71,376,796 | error: no matching function for call to ‘take_view(std::stringstream&, long unsigned int)’ | I want to extract a maximum of N + 1 strings from a std::stringstream.
Currently, I have the following code (that needs to be fixed):
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <string_view>
#include <vector>
#include <iterator>
#include <ranges>
#include <algorithm>
int main... | Note that the following aliases are in effect:
namespace views = std::views;
namespace rng = std::ranges;
There are a few issues and oddities here. First of all:
std::ranges::take_view { ss, expectedTokenCount + 1 }
It's conventional to use the std::views API:
ss | views::take(expectedTokenCount + 1)
The more glarin... |
71,377,153 | 71,378,984 | SaxonC EE 11.2's "SaxonProcessor::newXslt30Processor()" returns a Debug Assertion Failed : "vector subscript out of range" | I am using the cpp and hpp files from the C API in Saxon EE , I just compiled and ran these lines :
SaxonProcessor* processor = new SaxonProcessor(false);
Xslt30Processor* xslt = processor->newXslt30Processor();
It shows the error when I create a XSLT30Processor.
Also I'm not using a license.
Ive Debugged it and the f... | I figured it out , my cpp files werent including the files in the write order. I cant beleive it
|
71,377,612 | 71,377,682 | Deleting items in TListBox using a separate button on RAD Studio | I am creating a simple calculator app to learn how to use RAD, but could not figure out how to delete items in the ListBox by clicking "CLR". The "CLR" button should be able to clear out both the input box and the answer box. I am using C++ not Delphi. If you need anything more in the codes please let me know.
| TListBox has a public Clear() method, eg:
void __fastcall TForm1::ClrButtonClick(TObject *Sender)
{
InputListBox->Clear();
AnswerListBox->Clear();
}
|
71,377,640 | 71,406,686 | Crashing when calling QTcpSocket::setSocketDescriptor() | my project using QTcpSocket and the function setSocketDescriptor(). The code is very normal
QTcpSocket *socket = new QTcpSocket();
socket->setSocketDescriptor(this->m_socketDescriptor);
This coding worked fine most of the time until I ran a performance testing on Windows Server 2016, the crash occurred. I debugging wi... | After researching for a few days I finally can configure the Windows Server 2016 setting (registry) to prevent the crash.
So basically it is a limitation of the OS itself, it is called desktop heap limitation.
https://learn.microsoft.com/en-us/troubleshoot/windows-server/performance/desktop-heap-limitation-out-of-memor... |
71,378,249 | 71,378,417 | how to std::move heap allocated char array to std::string | Is it possible to std::move a heap allocated char array(>= 10000 size) to std::string. I'm trying to prevent copying (std::string str(c_arr)) of char array data to std::string where c_arr is heap allocated.
|
how to std::move heap allocated char array to std::string
By having allocated the char array as part of another std::string. Example:
std::size_t char_count = 10000;
std::string str1(char_count, '\0');
char* c_arr = str1.data();
std::string str2 = std::move(str1);
If the heap allocated char array wasn't created by ... |
71,378,561 | 71,378,719 | shared_ptr with given C-like allocation and deallocation functions | I was given an API for some library (nng to be exact)
it has a C-like interface for allocating and deallocating a message object:
int nng_msg_alloc(nng_msg **, size_t);
void nng_msg_free(nng_msg *);
I'm trying to create a C++ interface for the library.
I would like to create a shared_ptr of a nng_msg object, but I'm s... | You only have to pass the allocated pointer and the custom deleter to std::shared_ptr, for example:
std::shared_ptr<nng_msg> new_nng_msg(std::size_t size) {
nng_msg* ptr;
auto res = nng_msg_alloc(&ptr, size);
// example error handling, adjust as appropriate
if(res != 0)
throw std::bad_alloc{};
... |
71,378,635 | 71,378,702 | Base class function being called instead of overridden function defined in Derived class | Here are my code
#include <iostream>
using namespace std;
class BaseClass
{
public:
BaseClass() {}
void init(const int object) { cout<<"BaseClass::init"<<endl; }
void run(const int object) { cout<<"BaseClass::run calls =>"; init(object); }
};
class Derived : ... |
Why "BaseClass::init" is being called instead of "Derived::init" ?
Because init is a non-virtual member function. To have the desired effect, you need to make init a virtual member function as shown below:
class BaseClass
{
public:
BaseClass() {}
//NOTE THE VIRTUAL KEYWORD HERE
virtual void init(const int... |
71,378,674 | 71,378,733 | C++ Why are the changes to my class attributes in my class methods not saving? | I have a class that has x, y, and mass (which acts as radius) attributes. All of which are floats. I also have this method:
float shrink(float attackerMass) {
float shrinkAmount = attackerMass * GetFrameTime();
mass -= shrinkAmount;
return shrinkAmount;
}
This method is called when another circle is touch... | Here:
for (Blib blib : blibs)
Simply change to:
for (Blib &blib : blibs)
You want a reference, otherwise you are just changing a temporary variable that disappears at the end of each for loop iteration.
PS: I usually prefer:
for (auto &blib : blibs)
PPS: Your function signature also needs to be a reference:
void che... |
71,378,759 | 71,381,002 | Call JS functions in v8 from c++ | What I want to do is call already compiled functions in JS/v8 from c++. I'm doing this for a game engine I'm writing that uses V8 as the scripting back-end.
This is kinda how a script would be formatted for my engine:
function init(){ //this gets called at the startup of the game
print("wambo");
}
var time = 0;
fu... | I did port the sample from the other answer to the latest V8 version - 10.1.72
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "libplatform/libplatform.h"
#include "v8.h"
#include <iostream>
#... |
71,378,775 | 71,380,169 | How to read large files in segments? | I'm using small files currently for testing and will scale up once it works.
I made a file bigFile.txt that has:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
I'm running this to segment the data that is being read from the file:
#include <iostream>
#include <fstream>
#include <memory>
using namespace std;
int main()
{
ifstream fil... | The problem is that you don't override the buffer's content. Here's what your code does:
It reads the beginning of the file
When reaching the 'YZ', it reads it and only overrides the buffer's first two characters ('U' and 'V') because it has reached the end of the file.
One easy fix is to clear the buffer before each... |
71,378,847 | 71,379,063 | How to correctly initialize the `pFuncton` pointer | How to correctly initialize the pFuncton pointer?
#include <iostream>
class CTest
{
public:
void Function(int);
int (*pFuncton)(int);
void Test();
};
void CTest::Function(int Int)
{
std::cout << Int;
};
void CTest::Test()
{
pFuncton = Function;
pFuncton(1);
};
int main()
{
CTest test... | The type of the member function is void (CTest::*pFuncton)(int); and you need special syntax to call a member function via a member function pointer:
#include <iostream>
class CTest
{
public:
void Function(int);
void (CTest::*pFuncton)(int);
void Test();
};
void CTest::Function(int Int)
{
std::cou... |
71,379,404 | 71,474,109 | Eclipse: Behavioral differences between "linked Resources" and "Build->Setting->include" of a head file | I am using Eclipse and do not understand what are the differences between "setting include paths in project setting" and "add linked resources in project setting" for a header file.
How do they work?
I encountered the following scenario:
I want to use a header file "functions_api.h", which is provided in a SDK. I have ... | Comment from @user7860670 has solved the problem.
|
71,379,610 | 71,379,798 | Exporting a c++ dll class unexpected behavoir | I am farily new to c++ language and have an extensive c# background.
I have setup a solution in visual studio 2022 consisting of a console executable project and a dll project, with the excutable depending on the dll project.
The dll depends on some other static libs to ultimatly provide httpclient like functionality.
... |
So I decided to make an interface class with only a public constructor and key public functions in a seperate clean headerfile; this class has the same name and inside the same name space as the full class
That violates the one-definition-rule and causes your program to have undefined behavior. Definitions of the sam... |
71,379,846 | 71,379,973 | Rewind a stream, both ifstream as well as strstream | I want to write a HEX file reader. It should support two different formats: Intel HEX and a "ROM" file format where each line contains a pair of address and 16 bit hex value. The reader shall identify the format. For that purpose it must read at least some lines to check if it's at least one valid format.
The file stre... | Call stream.clear(); stream.seekg(0, std::ios_base::beg);. That should rewind any stream that can be rewound. Of course some istreams cannot be rewound, such as std::cin, so you'll want to check for an error after seekg().
|
71,380,156 | 71,380,182 | c++ linked list, removing element disconnects the rest of the list | I was trying to implement this simple linked list project for my homework. When I tried to implement the removeByKey function, I ran into the problem that it disconnects the rest of the list entirely when it finds the key to be removed.
Here's the class:
class LancElem
{
private:
int key;
LancElem* next;
public... | Ask yourself:
What is n->next after the line n->setNext(n->getNext()->getNext()); ? What does the line delete n->getNext(); delete?
You don't want to delete the just updated next but you want to delete the to be removed element:
auto to_be_deleted = n->getNext();
n->setNext(to_be_deleted->getNext());
... |
71,380,215 | 71,380,475 | Saxon C how to run multiple xslts on a cached xml | I want to run several Xslts with one cached xml . However I can only find ways to run several xml files with
a cachedxslt , but thats not what I want . As well as an XsltExecutable for Xslt , can there be an XsltExecutbale for Xmls, so that i can cache an xml , and run several xslts on it.
| You can create a DocumentBuilder and use parseXmlFromFile (https://www.saxonica.com/saxon-c/doc11/html/classDocumentBuilder.html#a4fd6acc79cbed4ae3aa9bd062ffa080f) to parse your XML input file once into an XdmNode, then you can feed that XdmNode as the input to any transformTo... method you call on your XsltExecutable ... |
71,380,239 | 71,380,283 | warning: 'totalTemp' may be used uninitialized in this function and cout not printing to console | Trying to write a program displaying the average temperature in 24 hours, by the user typing in the temperature each hour. However, I'm just getting this error in code blocks:
warning: 'totalTemp' may be used uninitialized in this function [-Wmaybe-uninitialized]|.
and the console is just black when ran and not display... |
How do I initialize it?
int totalTemp = 0;
and what is making my code not appear in the console when I'm trying to use cout?
while(i <= 24);
This is an infinite loop with an empty body. Infinite loops without observable side effects are undefined behavior. The compiler is allowed to produce the same output for yo... |
71,381,407 | 71,382,654 | ROS-server client srv not printing uint8 | So I am learning ROS and I am having an issue in writing a simple service client code.
The srv_server.cpp is:
#include<iostream>
#include<string>
#include<ros/ros.h>
#include<std_msgs/String.h>
#include "msg_srv_basics/addInts.h"
bool callback_function(msg_srv_basics::addInts::Request &req, msg_srv_basics::addInts::Re... | Since it is a uint8 on the ROS side, it's actually being saved as a char when it hits c++ code. This means you're trying to print out the ASCII value of of your age field. Instead you should convert the value directly to an int when printing like:
ROS_INFO_STREAM("Actual age is: " << int(req.age));
ROS_INFO_STREAM("Dou... |
71,382,216 | 71,428,586 | Qt 5 Disabling Click-and-Hold | I'm trying to solve an issue in a Qt5 application that's caused by a touchscreen driver I wrote a couple years ago. The problem being that my touchscreen driver generates mouse press events to simulate touch behavior. This was because at the time I wrote it, my team was using an outdated Linux OS that didn't have a nat... | A minimal example to generate mouse press/release events that are correctly handled by QSlider is:
#include <QApplication>
#include <QMainWindow>
#include <QMouseEvent>
#include <QSlider>
#include <QTimer>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QMainWindow m;
QSlider *slider = new ... |
71,382,976 | 71,383,628 | static assertion failed with unordered map when using non-type template and empty lambda | The following class will trigger a static assert error within std::map due to differing value_types of the allocator, despite the allocator being defaulted:
template < bool store>
class MyClass {
public:
using hashmap_type = std::unordered_map<
int,
decltype([](){})
>;
private:
std::map... | Seems to be a bug with how gcc substitutes default arguments to template parameters involving unevaluated lambda types.
A similar example:
#include <type_traits>
template<typename T, typename U = T>
struct assert_is_same {
static_assert(std::is_same_v<T, U>);
};
template<bool B>
struct X {
assert_is_same<decl... |
71,383,519 | 71,383,648 | Largest value representable by a floating-point type smaller than 1 | Is there a way to obtain the greatest value representable by the floating-point type float which is smaller than 1.
I've seen the following definition:
static const double DoubleOneMinusEpsilon = 0x1.fffffffffffffp-1;
static const float FloatOneMinusEpsilon = 0x1.fffffep-1;
But is this really how we should define thes... | You can use the std::nextafter function, which, despite its name, can retrieve the next representable value that is arithmetically before a given starting point, by using an appropriate to argument. (Often -Infinity, 0, or +Infinity).
This works portably by definition of nextafter, regardless of what floating-point fo... |
71,383,989 | 71,384,100 | Why I can't take address of the std::addressof function | Why I can't take the address of the std::addressof when I explicitly specify the type?
To make it more weird, when I c/p the implementation from cppreference I can take address of that function.
#include <memory>
template<typename T>
void templ_fn();
template<class T>
typename std::enable_if<std::is_object<T>::value... | As you already hinted yourself, taking the address of std::addressof has unspecified behavior, and so may or may not work, because it is not designated as an addressable function in the standard.
More practically speaking though, the issue is that there are at least two overloads for std::addressof, both being template... |
71,384,102 | 71,384,402 | gdb asking to continue/quit? | I am new to GDB, using to debug an issue with my program(C++). I used gdb to find the backtrace and then print frames information. During one of the print, let's say the command is something like:
1) frame 2
2) print *this
In between the output of the print call, I am getting the following line:
---Type <return> to co... | When there is too much to print to fit inside the current buffer, gdb will pause after it's hit the limit. If you press enter, it'll continue printing.
I assume this points to an object that has a lot of "stuff" in it, so it's perfectly normal that you get this message. Just keep pressing return until you see the infor... |
71,384,120 | 71,384,200 | std::is_pointer of dereferenced double pointer | I have some code where i want to check for (accidental) double pointers in static_assert
#include<type_traits>
int main()
{
using namespace std;
float* arr[10];
float ** pp;
static_assert(!is_pointer<decltype(*arr)>::value, "double pointer detected");
static_assert(!is_pointer<decltype(*pp)>::val... | Both of those decltypes resolve to reference types, and therefore neither are pointers, and hence the static assertions pass. These would also pass:
static_assert(std::is_pointer<std::remove_reference_t<decltype(*arr)>>::value);
static_assert(std::is_pointer<std::remove_reference_t<decltype(*pp)>>::value);
|
71,384,146 | 71,396,548 | Rotation using Transformation Matrix | Can someone please explain to me what does this function do :
void QMatrix4x4::rotate ( const QQuaternion & quaternion )
In the documentation, it's written that it multiples this matrix by another that rotates coordinates according to a specified quaternion.
The question is which matrix is " this matrix" ? d... |
The question is which matrix is "this matrix" ?
"This matrix" refers to the matrix that this member function is called on.
does it calculate a rotation matrix ?
According to this source code, yes. The current matrix is multiplied by a rotation matrix that corresponds to the quaternion.
|
71,384,247 | 71,385,094 | C++ require function without implicit conversion | I'm using boost::variant to imitate inheritance with value semantics.
There is one class that may be printed:
struct Printable { /* ... */ };
void print(const Printable &) { /* ... */ }
And class that may not:
struct NotPrintable { /* ... */ };
Finally, there is "Base" class with implicit cast:
struct Base : boost::... | I found a perfect solution that is based on Inline friend definition.
According to standard:
Such a function is implicitly an inline function (10.1.6). A friend function defined in a class is in the (lexical)
scope of the class in which it is defined. A friend function defined outside the class is not (6.4.1).
Some ... |
71,384,296 | 71,384,655 | Wrap type of "this" parameter | Rust's equivalent of C++'s this is self. In Rust you can do this:
struct C;
impl C {
fn some_fn(self: &Rc<Self>) {}
}
Does such feature exist in C++? The following is syntactically invalid:
class c_t {
void some_fn(std::shared_ptr<c_t> this) {
std::cout << "calling from shared_ptr";
}
};
So that ... | You cannot have
shared_ptr<C> c = std::make_shared<C>();
c->foo(); // OK
c.get()->foo(); // Should not be OK.
The nearest you can do would be something like:
class C {
public:
friend void some_fn(std::shared_ptr<C> self) {
// ...
}
};
and so
shared_ptr<C> c = std::make_shared<C>();
some_fn(c); // OK
s... |
71,384,416 | 71,384,594 | multiset count method not working with class comparator | I have this struct
struct C {
int ID;
int age;
C(int ID, int age) : ID{ID}, age{age} {}
};
I use a comparator function for a multiset
bool fncomp (const C& lhs, const C& rhs) {
return lhs.age < rhs.age;
}
multiset<C, decltype(fncomp)*> ms{fncomp};
ms.emplace(1, 15);
...
// this works fine
ms.count(C(... | Elaborating on my comment above:
multiset::count is a const member function, which means that it operates on a const multiset. This includes the member variables of the multiset. The comparator is a member variable of the multiset.
Since your classcomp::operator() is not marked const, it can't be called on a const obje... |
71,384,673 | 71,386,616 | Crash while creating IBM ImqQueueManager class object | I am creating an object of ImqQueueManager class like this
ImqQueueManager mqManager;
Default constructor is getting called which is default initializing an object of ImqObject class.
Which is further leading to the crash. Here is the call stack
(gdb) bt full
#0 0x00007fb41179c336 in xcsCheckPointer () from /apps/mqm/... |
IBM MQ version 7.5 is installed on this 64 bit Linux machine.
You are using a release of IBM MQ that is long out of support. See here for a list of IBM MQ End of Service Dates.
Secondly, you should be showing us your code (update your post) because otherwise we will just be guessing.
Here's a fully functioning C++ t... |
71,384,930 | 71,385,141 | CMake- what is the difference between 'target_link_options(.. -lgcov)' and 'target_link_libraries(...gcov)'? | I'm trying to build a library with code coverage enabled like so:
add_library(my_library my_lib.cpp)
target_compile_options(my_library PRIVATE --coverage)
target_link_options(my_library PRIVATE -lgcov)
and then later I have some tests for the library:
add_executable(my_test my_test.cpp)
target_link... | The answer is right there, in the docs:
Note This command cannot be used to add options for static library
targets, since they do not use a linker. To add archiver or MSVC
librarian flags, see the STATIC_LIBRARY_OPTIONS target property.
|
71,385,661 | 71,385,806 | unsigned long long to std::chrono::time_point and back | I am very confused about something. Given:
std::time_t tt = std::time(0);
std::chrono::system_clock::time_point tp{seconds{tt} + millseconds{298}};
std::cout << tp.time_since_epoch().count();
prints something like: 16466745672980000 (for example)
How do I rehydrate that number back into a time_point object? I find mys... | system_clock::time_point tp{system_clock::duration{16466745672980000}};
The units of system_clock::duration vary from platform to platform. On your platform I'm guessing it is 1/10 of a microsecond.
For serialization purposes you could document that this is a count of 1/10 microseconds. This could be portably read b... |
71,386,628 | 71,390,979 | Getting hundreds of import errors when running boilerplate code in Visual Studio | Recently I tried opening up Visual Studio 2019 because I wanted to try I new IDE when I was met with hundreds of errors upon running standard boilerplate c++ code. More specifically import errors. I have tried installing the newest version of Visual Studio, have tried adding the path manually to the "Additional Include... | 1.Check the C++ windows sdk version in VS Installer.
2.Make sure that the installed windows sdk is selected in your project properties.
|
71,386,842 | 71,386,971 | Best way to reset all struct elements to 0 C++ | I'm trying to create some variables within certain structs, and I need to create a function that would reset all the values in the namespace to 0. I'm aware I can just tediously reset them all to 0 one by one, but I'm certain that's not the best way to do it. Another question I want to ask is that is it alright to init... | I see you're getting some suggestions to use memset. I think that's a mistake. It might be perfectly fine with the data you have, but as soon as someone down the road adds a string to your class, suddenly that's bad.
I would give each of them a default value of zero and then use the assignment operator to a newly-const... |
71,387,150 | 71,387,271 | Why isn't the derived class destructor being called? | I was doing some practicing with pointers to derived classes and when I ran the code provided underneath,the output I get is
Constructor A
Constructor B
Destructor A
Could someone tell me why is B::~B() not getting invoked here?
class A {
public:
A() { std::cout << "Constructor A\n"; }
~A() { std::cout << "Destru... | The static type of the pointer a is A *.
A* a = new B;
So all called member functions using this pointer are searched in the class A.
To call the destructor of the dynamic type of the pointer, that is of the class B, you need to declare the destructor as virtual in class A. For example:
#include <iostream>
class A {
... |
71,387,366 | 71,387,394 | (C++) My CopyFile() function doesn't work, but my paths and parameter types seem to be ok | I'm trying to write a function which copies the current running program's .exe file to the Windows's Startup folder. I'm completely new to this, so don't be mad at me :D
I have this piece of code:
void startup()
{
std::string str = GetClipboardText();
wchar_t buffer[MAX_PATH];
GetModuleFileName(NULL, buffer... | CopyFile() copies from one file to another file. So both lpExistingFileName and lpNewFileName parameters must be given file paths, but you are passing in a folder path for the lpNewFileName parameter. That will not work.
Had you followed what the documentation says:
If the function fails, the return value is zero. To... |
71,387,590 | 71,388,093 | error: ‘async_read_until’ is not a member of ‘boost::asio’ | Code:
https://coliru.stacked-crooked.com/a/d39bdc13f47785e5
Reference:
https://www.boost.org/doc/libs/1_72_0/libs/beast/doc/html/beast/using_io/timeouts.html
https://www.boost.org/doc/libs/1_72_0/doc/html/boost_asio/reference/async_read_until.html
/** This function echoes back received lines from a peer, with a timeout... | You are missing the correct header file. Include
#include <boost/asio/read_until.hpp>
or
#include <boost/asio.hpp>
|
71,387,979 | 71,387,990 | can't modify static set declared within a static method | I would like to store the value that is passed to the constructor in a static set returned by a static function.
It seems that the insertion is successful, but when it reach the end of the scope of the constructor it disappear.
I have reproduced it in a simple example:
// container.hh
#pragma once
#include <vector>
#i... | auto set = object_set_instance();
If you use your debugger to inspect what set is, you will discover that it's a std::set and not a std::set& reference. Effectively, a copy of the original std::set is made (object_set_instance() returns a reference, only to copy-construct a new object that has nothing to do with th... |
71,388,142 | 71,388,223 | Segmentation Fault at runtime in a simple C++ CUDA code | I got a cuda Segmentation fault after running this code.
The reason for this code:
I wanted to know the maximum size ian array can declare in register memory, maximum array for each thread per block:
#include "common.h"
#include <cuda_runtime.h>
#include "stdio.h"
#define N 10
#define Nblock 10
__global__ void add(in... | The seg fault is happening at this line:
free(dev_c);
You don't free a device pointer (allocated with cudaMalloc) that way.
The correct thing would be:
cudaFree(dev_c);
|
71,389,045 | 71,389,283 | in this C++ transform to vector<string>, how do I write this lambda function to count max words in any sentence? | http://cpp.sh/6qn6jh : Working solution by creating additional vector.
I am looking for a 1 liner solution using C++ STL transform on vector
Find most words in any sentence. Expecting answer as 6.
How do i structure this lambda without creating additional vector as a back_inserter in transform function?
#include <iostr... | You can do this as a one liner using C++20's ranges library:
#include <iostream>
#include <vector>
#include <string>
#include <ranges>
#include <algorithm>
int mostWordsFoundInASentence(const std::vector<std::string>& sentences) {
return std::ranges::max(
sentences |
std::ranges::views::transform(
... |
71,389,346 | 71,389,360 | C++ Template Syntax for Mixed Class and Method Templates | I am having trouble getting an inline method implementation to reference a generic template instance method [ check nomenclature ] because I don't know how to refer to it (or can't). I can make it work inline, but want to know if/how to do defer the definition.
I've found similar questions with the same setup (class/st... | You need to declare typename T for Vec first, and then typename R for fmap2, like this
template <typename T>
template <typename R>
Vec<R> Vec<T>::fmap2(std::function<R(T)> apply) const {
return Vec<R>();
}
|
71,389,630 | 71,389,655 | Possible race condition when invoking std::packaged_task::get_future() | Seen at this document, there is a demo snippet:
std::packaged_task<int()> task([]{ return 7; }); // wrap the function
std::future<int> f1 = task.get_future(); // get a future
std::thread t(std::move(task)); // launch on a thread
My question is that whether there is any potential problems(race condition) or not if I r... | Yes, there's a problem. You moved the task. Your thread doesn't have it anymore; the task variable at that point is in a valid-but-unspecified state. You can't ask for its future, because it doesn't represent the task in question... because you moved it.
This isn't a race condition; it is functionally no different from... |
71,389,690 | 71,389,715 | Error while printing 2 arrays with sort selection method | Ive been working with this project for school to leanr about the sorting and searching methos like quicksort, bubblesort, etc.
I started working one cpp file per method. Everythind almost works fine, but when the program is printing the info, the first column (words) prints 0x70fc90 instead the words.
#include<iostream... | You forgot to append [i] on busquedasFrecuentes
Instead of this:
cout << " " << busquedasFrecuentes << " " <<frecuencia[i]<< sizeof(20) << endl;
This:
cout << " " << busquedasFrecuentes[i] << " " <<frecuencia[i]<< sizeof(20) << endl;
Also, I'm not sure why you want to print sizeof(20) at the end of ea... |
71,390,316 | 71,390,432 | How to override output operator (<<) as a function template outside a class template | I am reading Section 2.4 of the book "C++ tempalte, a complete guide".
I tried to override output operator (<<) as a function template outside the class template Stack<>.
Below is my code, but it doesn't work.
#include <iostream>
#include <string>
#include <vector>
template<class T>
class Stack
{
private:
std:... | You are just omitting the &, which makes the operator<< inside and outside the class have different function signatures, they are both valid for std::cout << s1, hence the ambiguity
template<typename T>
std::ostream& operator<< (std::ostream& out, const Stack<T> & s)
// ^
{ ... |
71,390,564 | 71,390,694 | About the parameters passed to the ctor of `std::thread` | As this code snippet does not compile, I understand that the std::thread need callable&& other than callable&.
#include <iostream>
#include <cmath>
#include <thread>
#include <future>
#include <functional>
// unique function to avoid disambiguating the std::pow overload set
int f(int x... | std::thread takes all of the objects it is given (the function to be called and its parameters) by "decay copy". This effectively means that a new object will be created for each parameter given. These objects will be stored by std::thread and used when calling your function on the new thread. The new objects will be c... |
71,390,586 | 71,390,733 | question about C++ single linked list implementation | I am studying the following code but get confused on the building of the single linked list in function read_file(), I have marked the question at the function next to the code below:
here is the full code: https://github.com/mickyjm/c.cpp.address.book.project/tree/master/CPP
list header file list.h
#ifndef LLIST_H
#de... | In order of comments asked.
What's the purpose of this loop?
while (index != NULL) {
previous = index;
index = index->next;
} // end while index != NULL
Answer: this loop is used to position previous on the last node in the list, so long as there is at least one node. There are multipl... |
71,390,905 | 71,391,030 | Why can't I use a set as the output collection of transform operation on a vector? | When I use transform on a set and use a vector to store the output, it works fine. But it doesn't seem to work the other way around.
This is the code that doesn't work:
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
int multiply(int a) {
return a * 2;
}
void print(i... | As @molbdnilo pointed out:
The elements of a set are immutable.
Thus, existing elements cannot be overwritten.
However, it can be done with e.g. a std::insert_iterator:
#include <algorithm>
#include <iostream>
#include <set>
#include <vector>
int main()
{
std::vector<int> v = { 1, 2, 3, 4, 5 };
std::set<int> ... |
71,391,558 | 71,393,102 | Print all the substrings with equal number of zeros and ones, But am not able to | I want to print all the substrings to be printed and everysubstring should have equal number of zeros and ones.I have strated the loop where i points to the index and initially number of zeros and one is equal to 0 and loop runs till both of them becomes equal and i push that in the vector. But My code is not running g... | There are a number of little mistakes in your code. You should learn to use a debugger to step through it, the errors would become evident.
In the loop over i it is useless to set the value of j just before setting in again in the loop over j.Then, the loop should be limited by j<n to prevent an access past end of stri... |
71,391,597 | 71,391,643 | Why do I keep getting a zsh: segmentation fault error when I use a.out for this file? | New to file io in c++. I'm initially writing a basic program to simply remove comments from a file. If the first two characters are //, then I basically need to skip and print the following line in the text file. My output file and input file are both in the same folder as my CPP file, so I'm not sure why I keep gettin... | Your variable int i is not initialized, so in_stream>>result[i] yields undefined behaviour.
Use int i=0 instead (and check if i < 100 before writing to your buffer).
|
71,391,863 | 71,392,686 | QTextEdit placeholder color | here's my problem:
I'm using Qt, I've got two QLineEdits (name, author) and one QTextEdit (description) in my form.
I need to set placeholders for each of them, so i wrote this code:
name->setPlaceholderText("Name");
author->setPlaceholderText("Author");
description->setPlaceholderText("Descript... | There is preety easy way of doing this programatically.
You can change the QPalette of your QLineEdit and QTextEdit and modify the QPalette::Text with setColor.
Another way of doing the same is catching signal if it is empty or not and setting stylesheet.
https://doc.qt.io/qt-5/stylesheet-examples.html
There is no refe... |
71,392,318 | 71,392,388 | scoped_lock inside lock_guard, is it redundant? | I'm new in multi-thread programming.
I'm now doing a serial port communication project, and search related codes for reference.
I found a code that someone used scoped_lock inside lock_guard as below:
void B(){
boost::mutex::scoped_lock b_lock(b_mutex);
/* do something */
}
void A(){
const std::lock_gua... | They lock different mutexes. Whether this makes sense depends on what is do something. For example it could be:
void B(){
boost::mutex::scoped_lock b_lock(b_mutex);
/* do something that needs b_mutex locked */
}
void A(){
const std::lock_guard<std::mutex> a_lock(a_mutex);
/* do something that needs... |
71,392,674 | 71,393,254 | How to return an std::optional lambda? | How can I declare a function that returns an std::optional lambda? e.g.
<what_do_i_put_here?> foo(bool b) {
if(b) return std::nullopt;
return [](int) { ... };
}
| How about using the ternary operator? It will automatically deduce the correct optional type
#include <optional>
auto foo(bool b) {
return b ? std::nullopt : std::optional{[](int){}};
}
|
71,392,856 | 71,393,472 | Boost : serialize long unsigned int | I have compilation error from boost because of a long unsigned int serialization and I cannot find out where does it come from..
Here is my class to serialize:
#ifndef JUCECMAKEREPO_PERFAUDITRESPONSE_H
#define JUCECMAKEREPO_PERFAUDITRESPONSE_H
#include <string>
#include <utility>
#include <vector>
#include "boost/seri... |
If I only keep message and httpCode serialization the compilation works
I don't see how. You explicitly deleted the default constructor. Boost Serialization requires default construction (or you MUST implement save_construct_data/load_construct_data.
Here's my simple tester, you can compare notes and see what you mis... |
71,392,994 | 71,401,364 | Huffman Coding using min priority queue | In this Question, I need to print the huffman code for all the data. But for the given test case below, I'm getting different output.
Input
8
i j k l m n o p
5 9 12 13 16 45 55 70
Where
First line enters the number of letters
Second line enters the letters
Third line enters the frequencies of the letters
Expected Outpu... | Just to add to 500's correct answer, depending on the choice made, you can get either of these trees, both of which are valid and optimal:
By the way, since you also show bit assignments, for each of those two trees there are 128 ways to assign codes to the symbols. You can make each branch individually 0 on the left ... |
71,393,622 | 71,393,896 | accessing std::tuple element by constexpr in type | I would like to access to a tuple element at compile time by a value constexpr in the type
#include <iostream>
#include <tuple>
#include <utility>
struct A {
static constexpr int id = 1;
void work() {
std::cout << "A" << std::endl;
}
};
struct B {
static constexpr int id = 2;
void work... | You can create constrexpr function to get index:
template <typename... Ts>
constexpr std::size_t get_index(int id)
{
constexpr int ids[] = {Ts::id...};
const auto it = std::find(std::begin(ids), std::end(ids), id);
// Handle absent id.
if (it == std::end(ids)) {
throw std::runtime("Invalid id"... |
71,394,001 | 71,394,049 | Why does abstract base class need explicit default constructor? | For below code,
#include <iostream>
class virtualBase {
public:
virtual void printName() = 0;
// virtualBase() = default;
private:
virtualBase(const virtualBase &) = delete; // Disable Copy Constructor
virtualBase &
operator=(const virtualBase &) = delete; // Disable Assignment Operator
};
class derivedCl... | Declaring any constructor explicitly prevents declaration of the implicit default constructor.
You do declare the copy constructor explicitly (even if you then define it as deleted).
|
71,394,420 | 71,394,717 | objects as class data members using default constructor with and without initializer list | for the following program
#include <iostream>
using namespace std;
class university{
private:
string uni;
public:
university(){
cout<<"default constructor of university is invoked"<<endl;
}
university(string u){
uni =u;
cout<<"parametrized constructor of university is invoked: "... | "Allocating memory" and "assigning memory location" has nothing to do with anything here. You are asking about how objects that are members of another class get constructed. Trying to pull in the subject of memory allocation here only confuses things. Advanced C++ techniques allow objects to be repeatedly constructed a... |
71,394,678 | 71,394,788 | How to propagate changes from one class to another in C++? | Having this code:
#include <iostream>
#include <vector>
#include <string>
class A{
public:
A(std::string const& name) : name(name) {}
std::string const& getName() const {
return name;
}
private:
std::string name;
};
class B{
public:
void add(A const& a){
//vec.emplace_back(a) does ... | C's members are not reference types. Both c1 and c2 are storing copies of the constructor arguments.
So
d.add(c1);
d.add(c2);
doesn't affect b in main, only the members of c1 and c2, which are copies of the original b, a1 and a2 in main.
|
71,395,416 | 71,395,681 | While incrementing a pointer which points to an array, why does my array feels be reversed? | When I'm dereferencing and printing the output of a given array pointer, I'm getting my array in reverse.
Here's the code
using namespace std;
int main()
{
int arr[5] = {1,2,3,4};
int* ptr = arr;
cout<<ptr<<endl;
cout<<*ptr++<<endl;
cout<<*ptr<<" "<<*ptr++<<" "<<*ptr++<<" "<<*ptr++;
return 0... | The first thing to note is that the size of the array is 5 and the number of initialization elements is 4, which means that the last element will be initialized to 0.
The reason for unordered output is that C++ compiler does not guarantee the order in which the parameters of << are evaluated. It means that, in your las... |
71,395,595 | 71,395,634 | Trying to pass 2D array to function and getting a compiler error | I'm a C/C++ beginner and trying to build a simple script. I'm running this on an Arduino.
#include <Arduino.h>
int pin_locations[3][3] = {
{8, 5, 4},
{9, 6, 3},
{10, 7, 2}
};
void setup() {
for (int i=0; i<3; ++i) {
for (int j=0; j<3; ++j) {
pinMode(pin_locations[i][j], OUTPUT);
}
}
}
void ... | You've declared convert_drawing_to_LEDS to take an int [] which is not a 2D array. This causes a mismatch between the parameter and how its being used in the function, and also a mismatch between the actual parameter being passed in and what the function is expecting.
You instead want:
void convert_drawing_to_LEDS(int... |
71,395,734 | 71,395,903 | Memory leak caused by array of pointers? | I'm making chess in c++, by making an array of pointers to class Piece.
Piece* chessboard[8][8];
Piece pieces[32];
Each chessboard field that has a piece points to an element of array pieces[] and those that don't have a piece, point to NULL. Here's a fragment of chessboard initialization function:
for (int i = 0;... |
Piece pieces[32];
chessboard[i][j]=&pieces[tmp];
chessboard[7-(y2-'1')][x2-'a'] = chessboard[7-(y1-'1')][x1-'a'];
chessboard[7-(y1-'1')][x1-'a'] = NULL;
Does this cause a memory leak?
No. This does not cause a memory leak.
Memory leaks when you allocate dynamic memory, and lose the pointer to that dynamic memory s... |
71,396,698 | 71,396,973 | Does PIMPL idiom actually work using std::unique_ptr? | I've been trying to implement the PIMPL idiom by using a unique_ptr.
I inspired myself from several articles that always highlight the same important point : ONLY DECLARE the destructor in the header of the class implementing PIMPL and then define it in your .cpp file. Otherwise, you'll get compilation error like "Inco... | I don't (yet) fully understand the issue, but the cause is the default member initializer of the m_ptr member. It compiles wihout errors if you use the member initializer list instead:
// A.hpp:
class A
{
public:
A();
~A();
private:
class B;
std::unique_ptr<B> m_b; // no initializer here
};
// A.cpp:
A::A() : ... |
71,397,071 | 74,062,637 | Drawing Circle In SDL2 Broken | So I found some code to draw a circle, added it to my project then I tried using it annndddd.. well my program never stops, uses almost all free ram, and does nothing (that I can see) here's my whole c++ app there is no other scripts or anything:
#include <SDL.h>
#include <stdio.h>
#undef main
//Draw A Circle
void Dr... | I ended up using what HolyBlackCat said, the SDL_RenderGeometry and that seemed to work for what I needed it for.
|
71,397,333 | 71,398,651 | Why doesn't my SDL2 code display images with SDL_Texture* | I have a C++ project where I'm initially trying to display a PNG image to the screen.
This is my code.
RenderWindow.hpp
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
class RenderWindow
{
public:
RenderWindow(const char *p_title, int p_width, int p_height);
void render();
void cleanUp();
private:
... | I think that the call to SDL_CreateTextureFromSurface fails because it is called before SDL_CreateWindow and SDL_CreateRenderer, thereby initializing texture to NULL.
Please move the initizalization of texture (and image) to after window and renderer are initialized.
To further help with such issues, please check if th... |
71,397,564 | 71,398,193 | Variable with same name with a struct type compiling only if it's not a template | Why is it allowed to have a variable with same name with a struct type only if it's not a template?
Why is this considered okay:
struct Foo {
int func(int) const;
};
struct Foo Foo;
but not this:
template<bool x = true>
struct Foo {
int func(int) const;
};
struct Foo<> Foo;
// gcc 11.2
<source>:6:14: error... | According to the C++ Standard (C++ 20, 13 Templates) class template name shall be unique in its declarative region.
7 A class template shall not have the same name as any other template,
class, function, variable, enumeration, enumerator, namespace, or type
in the same scope (6.4), except as specified in 13.7.6. Excep... |
71,398,145 | 71,398,289 | Vector 4 not representing the colors of all the verticii | I'm trying to have 4 integers represent the colors of all the verticii in a VBO by having the stride on the color vertex attribute pointer, however, It seems to only take the value once for the color, and, as a result, assigns the rest of the verticii as black as in the picture: picture. The expected result is that all... | From the documentation of glVertexAttribPointer:
stride
Specifies the byte offset between consecutive generic vertex attributes. If stride is 0, the generic vertex attributes are understood to be tightly packed in the array.
Setting the stride to 0 does not mean that the same data is read for each vertex. It means th... |
71,398,406 | 71,606,734 | Generate the vertices of a circle in SDL2 (C++) | Is there a way to automagically generate the vertices of a circle? I know how to render it and all that I just need a way to input a set amount of vertices and then generate the circle's vertices (the number of them) based on that number.
| One way you can generate the vertices to approximate a circle is as follows:
void GenerateCircle(std::vector<SDL_Vertex> &outCircleVertices, size_t vertexCount, int radius, std::vector<int> &outIndices)
{
// Size our vector so it can hold all the requested vertices plus our center one
outCircleVertices.resize(v... |
71,399,281 | 71,446,110 | Error with C++ module fragments and namespaces? | I want to build a single module with several implementation files. One file with structs is used by two implementation files.
When I compile I get the following error in gcc trunk (12) and also 11:
$HOME/bin/bin/g++ -std=c++20 -fmodules-ts -g -o test_optimization test_optimization.cpp optimization.cpp opt_structs.cpp g... | I'm trying to figure out modules with gcc as well, I can't comment so I'll post here.
The gcc documentation says:
Standard Library Header Units:
The Standard Library is not provided as importable header units. If you want to import such units, you must explicitly build them first. If you do not do this with care, you... |
71,399,392 | 71,399,462 | Concept for "this object looks like a 3D vector" | I have a project which is using a few libraries where each one of the libraries define some sort of 3D vector, as an example I use SFML's 3D vector in some parts of the code, reactphysics3d's Vector3 on others, and yet another 3D vector from another library.
Now I need to code the cross product and the std::ostream &op... | This
template <typename vector_t>
concept vector3_c = requires(vector_t v) { // error: expected unqualified-id
{ std::is_scalar_v<decltype(v.x)> } -> true;
};
will only check the validity of the expression std::is_scalar_v<decltype(v.x)>. In addition, the return-type-requirement constrains the type not the val... |
71,399,722 | 71,400,018 | Convert main args to span<std::string_view> without ranges | This question has been answered before by using ranges, but I'm using C++17 with a backport of std::span - so I have spans but not ranges.
Consider this simple function:
std::span<std::string_view> cmdline_args_to_span(int argc, const char* argv[])
{
return std::span<const char*>(argv, argc);
}
I thought the conve... |
Convert main args to `spanstd::string_view without ranges
This question has been answered before
You'll notice that the "answered before" solution doesn't create a std::span<std::string_view> at all.
std::span is not an adapter range whose iterators would generate objects upon indirection such as std::views::transfor... |
71,399,773 | 71,399,822 | Why did this assignment of a shared pointer have no effect after returning from nested function? | Consider this mwe:
#include<iostream>
#include<memory>
#include<vector>
using namespace std;
struct A {
shared_ptr<vector<int>> b;
};
void foo(vector<A> &vec)
{
auto c = shared_ptr<vector<int>>(new vector<int>{42});
vec.back().b = c;
cout << "Foo size " << vec.back().b->size() << endl;
}
void bar(A ... | In main(), a.b doesn't point at a valid vector, so accessing a.b->size() is undefined behavior.
bar() creates a new vector that holds a copy of the A object that was passed in to it. foo() is then acting on that copied A object, not the original A object in main().
If you want foo() to act on the original A object in m... |
71,399,898 | 71,400,491 | c++ Multithreaded output freezes on join() | This is a mock up of code I have for output drivers which output to files, database, etc.
In the array in main, if I have two objects of the same child type, the code stalls out on the second call to ShutDown(). However, If I have two objects of different child types it does not stall out, exiting the program correctly... | You never notify the thread about the shutdown and the predicate doesn't even consider, whether mProgramRunning has been set to false. You need to notify the condition variable after writing mProgramRunning you need to change the predicate accordingly.
E.g. something like this should work, but I consider the separation... |
71,400,077 | 71,401,349 | Xcode c++ project build fails for Profile mode (Release configuration) | I have a C++ CLI project in Xcode that compiles and runs fine for "Run" and "Analyze" mode (Debug configuration), but the build fails for "Profile" mode (Release configuration) with so many errors like the following:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/13.0.0/inc... | Figured it out.
The issue seems to be Apple Silicon architecture (I have Intel). So I changed the option for "Build Active Architecture Only" for Release to "Yes" from "No" and it solved the issue.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.