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 initialization order problem involved with STL components (or non-primitives). Using C++14. // MyClass.h #include <string> class MyClass{ public: static const std::string test; MyClass(); }; // MyClass.cpp #include <iostream> #include "MyClass.h" const std::string MyClass::test = "Yooooooo"; MyClass::MyClass(){ std::cout << test << std::endl; } // main.cpp #include <iostream> #include "MyClass.h" const MyClass c; int main(){ //MyClass c; // Would work std::cout << "There should be something above this line." << std::endl; }
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 initialization of a variable defined in a different translation unit. You have two variables with static storage duration in different compilation units const std::string MyClass::test = "Yooooooo"; and const MyClass c; You could avoid the problem by declaring the variable with the inline specifier. class MyClass { public: inline static const std::string test = "Yooooooo"; MyClass(); };
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 pre-allocated object obj = GetPointerFromOtherList(i); i++; } But when I access to this objects, it seems like it's empty. for(Object* obj : ObjectList) { // Access violation because obj is null. obj->doSomething(); } I tried other way too. for(int i = 0; auto& obj : ObjectList) { // store pointer of pre-allocated object. obj = GetPointerFromOtherList(i); i++; } and this work. The auto& keyword is same as Object*&. and I don't really understand why the first method didn't worked and second one worked otherwise. Can someone explain this to me?
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 ObjectList. When you assign to it with obj = GetPointerFromOtherList(i);, you are assigning to the pointer element inside ObjectList.
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 v_it, v_end(mesh.faces_end()); uint count = 0; for (v_it=mesh.faces_begin(); v_it!=v_end; ++v_it) { mesh.delete_face(*v_it, true); } This is segfaulting on the first call to delete_face. However, writing this mesh (without trying to delete faces): if (!OpenMesh::IO::write_mesh(mesh, std::string("open_mesh.obj"))) { std::cerr << "write error\n"; exit(1); } Works perfectly fine and blender can open the obj. So the issue very much seems to be with how I am trying to delete the faces. The docs don;t seem to provide any explanation as to why this is not valid: https://www.graphics.rwth-aachen.de/media/openmesh_static/Documentations/OpenMesh-Doc-Latest/a02618.html#ae20c4e746b52c34ace6a7b805fbd61ac
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 before to the graph. Code example: Node* a = new Node; Node* b = new Node; // from now on multiple threads at the same time a->next = b; Can a->next be invalid considering that pointer assignment is not atomic? Edit 1: I am checking next pointers after all threads stop running.
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 contains a data race if it contains two potentially concurrent conflicting actions, at least one of which is not atomic, and neither happens before the other ... Any such data race results in undefined behavior. Your specific scenario sounds like it might work in practice, but I wouldn't do it, unless you already tried atomics and benchmarking shows them to cause performance problems. If you're going to use atomics, you can try writing to them using std::memory_order_relaxed. From your description, it looks like it would be safe.
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 establish a baseline around a known time. //lol....lol is an exe which calls usleep() #include <unistd.h> using namespace std; int main(){ usleep(100); return 0; } then to measure execution time, I wrote this: #include <chrono> #include <stdlib.h> #include <iostream> using namespace std::chrono; using namespace std; int main(int argc, char **argv){ //returns runtime in nanoseconds //useage: runtime <program> //caveates: I put the exe in /home/$USER/bin //start timing auto start = high_resolution_clock::now(); //executable being timed: system(argv[1]); // After function call auto stop = high_resolution_clock::now(); auto duration = duration_cast<nanoseconds>(stop - start); cout << argv[1] << " " << duration.count() << endl; return 0; } my issue is that the run time seems to be wildly variant. Is this because I'm running in userspace and my system is also doing other things? why am I not getting more consistent run times? $ ./run_time lol lol 13497886 $ ./run_time lol lol 11175649 $ ./run_time lol lol 3340143 ./run_time lol lol 3364727 $ ./run_time lol lol 3372376 $ ./run_time lol lol 1981566 $ ./run_time lol lol 3385961
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 sleep_for: https://en.cppreference.com/w/cpp/thread/sleep_for The merits of this contest is not how you micro-optimize to save 1ns. It`s about choosing the right algorithm to calculate pi.
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.f, 0.f}; // right bottom glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA4, image.width, image.height, 0, GL_BGRA, GL_UNSIGNED_SHORT_4_4_4_4_REV, image.pixels.data());
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 image is loaded to a texture object and 2*image.width is not divisible by 4, GL_UNPACK_ALIGNMENT has to be set to 2, before specifying the texture image with glTexImage2D: glPixelStorei(GL_UNPACK_ALIGNMENT, 2); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA4, image.width, image.height, 0, GL_BGRA, GL_UNSIGNED_SHORT_4_4_4_4_REV, image.pixels.data());
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_; InternalType height_; std::vector<InternalType> vectorRepr() { return std::vector<InternalType>{width_, height_}; }; Vector2 vectorRepr() { return Vector2{width_, height_}; }; // maybe some other overloadings of vectorRepr() } Above example is NOT working, as vectorRepr is overloaded badly. What I want to achive is to have in Resolution struct encapsulated methods to return me internal state in different data types. Template specialization might come in handy for this, but I'am having a hard time joining the idea of both Resolution templating and vectorRepr templating. For me it looks similar as partial template specialization. Close up to std::vector return type: template<> // <- this is a specialization for vectorRepr std::vector<InternalType> vectorRepr<std::vector>() { // but here, vector should know the InternalType, to embed it. // so the InternalType is not specialized. return std::vector<InternalType>{width_, height_}; } Here I've found interesting example (but it is lacking a member attributes to return): How to specialize template function with template types I am aware it can be done easy in different way, but at this point I'm just to curious. Is it achivable ? Playground: https://godbolt.org/z/bE49vv3Ms
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 infinite loop for some reason. #include <iostream> using namespace std; struct node { int data; struct node *p; } *first = NULL; void createLinkedList(int a[], int n) { int i; struct node *last, *t; first = (struct node *)malloc(sizeof(struct node)); first->data = a[0]; first->p = NULL; cout << first->p << endl; last = first; for (i = 1; i <= n; i++) { t = (struct node *)malloc(sizeof(struct node)); t->data = a[i]; t->p = NULL; last->p = t; last = t; } } void displayLinkedList(struct node *p) { while (p->p != 0) { cout << "the element is " << p->data << endl; p = p->p; } } int sizeOfLinkedList(struct node *pointer) { int n{ 0 }; while (pointer->p != NULL) { n++; } return n; } int displayLinkedListRe(struct node *pointer) { while (pointer->p != NULL) { cout << pointer->data << endl; displayLinkedListRe(pointer->p); } return 0; } int main() { int array[] = { 1, 2, 3, 4, 5, 6, 7 }; createLinkedList(array, 7); displayLinkedList(first); displayLinkedListRe(first); cout << "the size of linked list is " << sizeOfLinkedList(first); }
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; p = p->p; } } in function sizeOfLinkedList(), you do not update p in the loop body, so the loop runs forever. displayLinkedListRe recurses inside the loop and you do not update p either! either use a loop or recursion but not both. Furthermore, allocating objects with malloc() in C++ is not recommended, especially without including <stdlib.h>. Here is a modified version: #include <iostream> using namespace std; struct node { int data; struct node *p; } *first = NULL; void createLinkedList(const int a[], int n) { if (n <= 0) return; node *first = new node; first->data = a[0]; first->p = NULL; node *last = first; for (int i = 1; i < n; i++) { node *t = new node; t->data = a[i]; t->p = NULL; last->p = t; last = t; } } void displayLinkedList(const struct node *p) { while (p != NULL) { cout << "the element is " << p->data << endl; p = p->p; } } int sizeOfLinkedList(const struct node *p) { int n = 0; while (p != NULL) { n++; p = p->p; } return n; } void displayLinkedListRe(const struct node *p) { if (p != NULL) { cout << p->data << endl; displayLinkedListRe(p->p); } } int main() { int array[] = { 1, 2, 3, 4, 5, 6, 7 }; createLinkedList(array, 7); displayLinkedList(first); displayLinkedListRe(first); cout << "the size of linked list is " << sizeOfLinkedList(first); }
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: template <typename T> struct maybe_void { maybe_void() requires(std::is_void_v<T>) = default; maybe_void(const T& v) requires(!std::is_void_v<T>) {} explicit maybe_void(int) {}; }; auto test() -> void { auto v = maybe_void<void>(42); // error -- sees 'const void&' constructor, even though it's disabled } All major compilers agree that this is an error: gcc-trunk: <source>:12:33: required from here <source>:7:5: error: forming reference to void 7 | maybe_void(const T& v) requires(!std::is_void_v<T>) {} | ^~~~~~~~~~ clang-trunk: <source>:7:23: error: cannot form a reference to 'void' maybe_void(const T& v) requires(!std::is_void_v<T>) {} ^ <source>:12:14: note: in instantiation of template class 'maybe_void<void>' requested here auto v = maybe_void<void>(42); ^ msvc-v19-latest: <source>(7): error C2182: 'v': illegal use of type 'void' <source>(12): note: see reference to class template instantiation 'maybe_void<void>' being compiled Live Example It was my understanding that requires was meant to work in cases like the above, but the various compilers seem to suggest otherwise. Why doesn't this work? Note: One possible workaround is to change the constructor to a constrained template instead: template <typename U> explicit maybe_void(const U& v) requires(!std::is_void_v<U> && std::same_as<T,U>); Live Example Although this works as a workaround, it doesn't explain why the requires clause doesn't prevent the otherwise disabled function from triggering the ill-formed issue in the first place.
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. The way this is generally dealt with is that you cull out void in the type. So you would need a separate specialization that allows void. Note that in most cases where a constructor would want to take a T const&, you'd have to do this anyway, because that function would almost certainly want to copy that T into a member variable or something. And you can't have a member variable of type void. So you'd still need a separate specialization. If you do not otherwise need a specialization of your type to handle void, then you can create a type which, when given a T that is void results in an innocuous non-void type. struct dont_use {}; template<typename T> struct non_void { using type = T; }; template<> struct non_void<void> { using type = dont_use; }; ... maybe_void(non_void_t<T> const& v) requires(!std::is_void_v<T>) {} As seen here.
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: fread(r,sizeof(uint8_t),1,f); break; case 16: fread(r,sizeof(uint16_t),1,f); break; case 32: fread(r,sizeof(uint32_t),1,f); break; case 64: fread(r,sizeof(uint64_t),1,f); break; default: break; } fclose(f); } So the first issue is I'm passing uint64_t if I might not even need a variable of that size , if I only need 1 byte then I should pass in uint8, or 2 bytes then uint16. The other is I'm passing in the number of bits needed to be read. Can this be automated? Can I for example pass in the type(uint8_t) as an argument itself so the function knows which type its dealing with and the size its dealing with? I can't do sizeof(r) because r is a pointer. Maybe function overloading could be a solution where I have a different type for each argument? void URand::getrandom(uint8_t* r); void URand::getrandom(uint16_t* r); void URand::getrandom(uint32_t* r); void URand::getrandom(uin64_t* r); I get that's a more pleasant solution than what I have; however I think with modern C++ it could be done even nicer and cleaner.
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 Unsigned> void dev_urandom(Unsigned& u) { std::ifstream("/dev/urandom", std::ios::binary).read((char*)&u, sizeof(u)); } int main() { unsigned u; dev_urandom(u); std::cout << u << '\n'; }
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_COUNT; ++i) { delete[] charArray[i]; } delete[] charArray; } int main(){ char ** test = createCharArray(); char *asd = new char[MAXSIZE]; cin >> asd; for (int i = 0; i < PARAM_COUNT; ++i) { strcpy_s(test[i], asd); } for (int i = 0; i < PARAM_COUNT; ++i) { cout << i << " " << test[i] << endl; } deleteCharArray(test); return 0; } How do I copy that string into the char array, where am I mistaking? Edit: As answered by Igor Tandetnik and user17732522 in the comments and Joseph Larson in the reply below, this was solved by adding the buffer argument to the strcpy_s function, making it a total of 3 arguments.
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 = createCharArray(); // array of pointers to char arrays char *asd = new char[MAXSIZE]; cin >> asd; for (int i = 0; i < PARAM_COUNT; ++i) { strcpy_s(test[i], asd); } for (int i = 0; i < PARAM_COUNT; ++i) { cout << i << " " << test[i] << endl; } deleteCharArray(test); return 0; Let's start with this. We don't know what createCharArray() does. Is it doing everything it should? Not only should it create an array of char pointers, but the way you're using it, it also needs to create the buffers they each point to. So it might look something like this: char ** createCharArray() { char ** array = new char *[PARAM_COUNT]; for (int index = 0; index < PARAM_COUNT; ++index) { array[index] = new char[MAXSIZE]; } return array; } If yours looks remarkably different, you may have issues. After that, let's look at this: for (int i = 0; i < PARAM_COUNT; ++i) { strcpy_s(test[i], asd); } As others have said, this version of strcpy_s takes three arguments: strcpy_s(test[i], asd, MAXSIZE); Note that you're copying the same string into place multiple times. I wonder if your code should really do this: for (int i = 0; i < PARAM_COUNT; ++i) { cin >> asd; strcpy_s(test[i], asd, MAXSIZE); } And finally, the delete method needs to delete the individual pointers and then the array of pointers.
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 meaningless if statement as below, the destructor is called twice. V f() { if(false) return V(3); V x(2); return x; } Destructor Function End Destructor Why can this happen? Is there some points to avoid calling destructor twice?
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 the copy because x is returned in all paths that leads to return. V f() { V x(2); if (false) x = V(3); return x; }
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 guaranteed. To be honest, I would probably never asked this question, if the name of destructor was simply destructor() in every class. However, the call basePtr->~Base(); looks a bit similar to basePtr->Base::virtual_fcn(); which is not a virtual call. By contrast, usual way of invoking a dtor of the most derived object, through delete basePtr; does not provide a hint to a compiler that (maybe) we are requesting the base class version. BTW, this is not a purely academic question. I want to have a container that can store a single object of a class derived from a given base with virtual dtor, up to some maximal size. If basePtr->~Base() is a virtual call, implementation of such a container is pretty easy and, only for completeness, shown below (sort of modeled after std::optional). #include<cstddef> #include<type_traits> #include<new> #include<utility> template <typename PolyBaseT, std::size_t MaxSize> class SubClassContainer{ static_assert ( std::is_class_v<PolyBaseT> ); static_assert ( std::has_virtual_destructor_v<PolyBaseT> ); static_assert ( sizeof(PolyBaseT) <= MaxSize ); public: SubClassContainer() noexcept :m_basePtr(nullptr) {} void reset() noexcept { if(m_basePtr) {m_basePtr->~PolyBaseT(); m_basePtr=nullptr;} } ~SubClassContainer() noexcept { reset(); } template<typename DerivedT, typename ...ArgsT> DerivedT* emplace(ArgsT&& ...args) { static_assert ( std::is_convertible_v<DerivedT*,PolyBaseT*> ); static_assert ( std::is_constructible_v<DerivedT,decltype(std::forward<ArgsT>(args))...> ); static_assert ( sizeof (DerivedT) <= MaxSize ); static_assert ( alignof(DerivedT) <= alignof (std::max_align_t) ); reset(); auto result = ::new (static_cast<void*>(&m_storage[0]) ) DerivedT(std::forward<ArgsT>(args)... ); m_basePtr=result; return result; } explicit operator bool () const noexcept {return m_basePtr;} const PolyBaseT * operator->() const noexcept {return m_basePtr;} PolyBaseT * operator->() noexcept {return m_basePtr;} SubClassContainer(const SubClassContainer&) = delete; SubClassContainer(SubClassContainer&&) = delete; SubClassContainer& operator=(const SubClassContainer&) = delete; SubClassContainer& operator=(SubClassContainer&&) = delete; private: alignas(std::max_align_t) unsigned char m_storage[MaxSize]; PolyBaseT *m_basePtr ; }; #include <iostream> struct B { virtual void id(){} virtual ~B() noexcept = default;}; struct D1:B{ virtual ~D1() {std::cout << __func__ <<std::endl;} }; struct D2:B{ virtual ~D2() {std::cout << __func__ <<std::endl;} }; struct D3:B{ D3(int) {} D3(double&&) {} virtual ~D3() {std::cout << __func__ <<std::endl;} }; int main() { SubClassContainer<B,128> der; der.emplace<D1>(); std::cout << "about to reset: " << std::endl; der.emplace<D2>(); std::cout << "about to reset:" << std::endl; der.emplace<D3>(7); std::cout << "about to reset [implicitely]" << std::endl; }
[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 { ~D() { } }; D D_object; B* B_ptr = &D_object; void f() { D_object.B::~B(); // calls B’s destructor B_ptr->~B(); // calls D’s destructor } —end example ]
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 type. I wish to know, how may I print the elements within this deck[1], i.e {1,1,1}. #include <iostream> using namespace std; struct card { int face; int shape; int color; }; int main() { struct card deck[52]; deck[1].face=1; deck[1].shape=1; deck[1].color=1; cout<< sizeof(deck)<<endl; for(int x:deck[1]) { cout<<x<<endl } return 0; }
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; int shape; int color; //overload operator<< friend std::ostream& operator<<(std::ostream &os, const card& obj); }; std::ostream& operator<<(std::ostream &os, const card& obj) { os << obj.face << " " << obj.shape << " " << obj.color; return os; } int main() { card deck[52] = {}; deck[1].face = 1; deck[1].shape = 1; deck[1].color = 1; std::cout << deck[1].face << " " << deck[1].shape << " " << deck[1].color << std::endl; //use overloaded operator<< std::cout << deck[1] << std::endl;\ } The output of the above program can be seen here: 1 1 1 1 1 1
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)SetWindowLongPtrA(getGameWindow, GWLP_WNDPROC, 0); } LRESULT CALLBACK ModuleManager::WndProc(const HWND hwnd, unsigned int message, uintptr_t wParam, long lparam) { if (message == WM_CHAR) { for (Module* m : modules) { if (m->getKeybinding() == wParam) { m->isActive = !m->isActive; // toggle } } } return CallWindowProcA(wndProc, hwnd, message, wParam, lparam); } Here is my current code. I want to set a callback on WndProc function.
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::WndProc); } LRESULT CALLBACK ModuleManager::WndProc(const HWND hwnd, unsigned int message, uintptr_t wParam, long lparam) { if (message == WM_CHAR) { for (Module* m : modules) { if (m->getKeybinding() == wParam) { m->isActive = !m->isActive; // toggle } } } return CallWindowProcA(wndProc, hwnd, message, wParam, lparam); }
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 explanation will be usefull for my learning process // comparison function object bool compareContourAreas ( std::vector<cv::Point> contour1, std::vector<cv::Point> contour2 ) { double i = fabs( contourArea(cv::Mat(contour1)) ); double j = fabs( contourArea(cv::Mat(contour2)) ); return ( i < j ); } [...] // find contours std::vector<std::vector<cv::Point> > contours; std::vector<cv::Vec4i> hierarchy; cv::findContours( binary_image, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) ); // sort contours std::sort(contours.begin(), contours.end(), compareContourAreas); // grab contours std::vector<cv::Point> biggestContour = contours[contours.size()-1]; std::vector<cv::Point> smallestContour = contours[0];
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, you will get a 2D array of points, this basically is a one-channel cv::Mat. In 'compareContourAreas' you take two contours out of your vector 'contours' and compare the absolute sum of all of the points in the contour. To add all the points you use contourArea, which needs a cv::Mat as input, so you first need to convert your contour-vector of points to a cv::Mat. Then with the sort function you sort all the contours from small to big.
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 it and checking each char i see the output is 3 0 ffffffffd ffffffffd instead of 3 0 0, here is the full code: int32_t i_lengthOfCommand = 3; char *s_lengthOfCommand = toBytes(&i_lengthOfCommand); printf("%x %x %x %x", s_lengthOfCommand[0], s_lengthOfCommand[1], s_lengthOfCommand[2], s_lengthOfCommand[3]); stdout: 3 0 ffffffffd ffffffffd PS: i know there is no support for big/little endian
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(const T& src) { return {reinterpret_cast<const char*>(&src), sizeof src}; } You can then use either with send() etc: auto res = toBytes(i_lengthOfCommand); send(sockfd, res.data(), res.size(), flags);
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 treated as one object: I tried to use HoughCircles, but found that this only works well with actual circles, not distorted ones. So how would I go about finding a solution? Is there any algorithm that fits better for this problem, or can I somehow work out the individual circles in each contour?
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 is to find the lowest common ancestor of these two values. For example: if strArr is ["[10, 5, 1, 7, 40, 50]", "1", "7"] then this tree looks like the following: 10 / \ 5 40 / \ \ 1 7 50 For the input above, your program should return 5 because that is the value of the node that is the LCA of the two nodes with values 1 and 7. You can assume the two nodes you are searching for in the tree will exist somewhere in the tree. When submitting my code for this challenge the website calculates my time complexity to be O(n^2) when the most efficient is O(n). I believe that the problem lies within the "build tree" function because the for loop calls a recursive "build tree". Please help me identify what is causing my time complexity to be quadratic and the concept to achieve a linear time complexity #include <iostream> #include <string> #include <cstring> #include <vector> #include <algorithm> using namespace std; struct Node { int value; Node *parent = nullptr; Node *leftChild = nullptr; Node *rightChild = nullptr; }; Node* findClosestParentOf(Node* n1, Node* n2) { vector<int> ancestVals; for (n1 = n1; n1 != nullptr; n1 = n1->parent) { ancestVals.push_back(n1->value); } for (n2 = n2; n2 != nullptr; n2 = n2->parent) { if (find(ancestVals.begin(), ancestVals.end(), n2->value) != ancestVals.end()) return n2; } return nullptr; } Node* searchNodeOf(Node* tree, int val) { if(tree->value == val) { return tree; } else { if (val < tree->value) return searchNodeOf(tree->leftChild, val); else return (searchNodeOf(tree->rightChild, val)); } return nullptr; } Node* createNode (Node *_parent, int _value) { Node *node = new Node; node->parent = _parent; node->value = _value; return node; } Node* buildTree(Node *&parent, int val) { if (val < parent->value) { if (parent->leftChild == nullptr) parent->leftChild = createNode(parent, val); else buildTree(parent->leftChild, val); } else { if (parent->rightChild == nullptr) parent->rightChild = createNode(parent, val); else buildTree(parent->rightChild, val); } return parent; } Node* buildTree(vector<int> values) { Node *base = createNode(nullptr, values[0]); for (int i = 1; i < values.size(); i++) { buildTree(base, values[i]); } return base; } vector<int> stringToInt(string str) { vector<int> vec; for (char* pch = strtok((char*)str.c_str(), "[ ,]"); pch != NULL; pch = strtok(NULL, "[ ,]")) { vec.push_back(stoi(pch)); } return vec; } int BinarySearchTreeLCA(string strArr[], int length) { vector<int> values = stringToInt(strArr[0]); //O(n) Node *tree = buildTree(values); //O(n^2) Node* n1 = searchNodeOf(tree, stoi(strArr[1])); //O(n) Node* n2 = searchNodeOf(tree, stoi(strArr[2])); //O(n) return findClosestParentOf(n1, n2)->value; //O(n) } int main(void) { string A[] = {"[3, 2, 1, 12, 4, 5, 13]", "5", "13"}; int arrLength = sizeof(A) / sizeof(*A); cout << BinarySearchTreeLCA(A, arrLength); return 0; }
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 common ancestor then it must have a value that lies between the two target values. Not all values that are between the two target values are common ancestors. Not all common ancestors are values between the two target values There is actually only one value that lies between the two target values that is also a common ancestor. And this is the LCA. All other values that are between the two target values are necessarily part of the subtree rooted in that LCA node. As the nodes are given in preorder, the first value we find that lies between the two target values must be the LCA (for all of the above reasons) The last point describes the linear algorithm you can implement, which is also a lot simpler than what you had done.
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 vector accordingly The following code outlines the idea: int main(){ auto required_size = get_required_buffer_size(); auto buffer = std::vector<char>{}; buffer.resize(required_size); auto read_size = read_data(std::data(buffer), buffer.capacity()); buffer.resize(read_size); } Is this a correct usage of std::vector, or am I shooting myself in the foot somewhere? Edit: Change reserve to resize since the last resize will overwrite data written by read_data
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_size(); std::vector<char> buffer(required_size); auto read_size = read_data(buffer.data(), buffer.size()); buffer.resize(read_size); } That being said, in cases where char[] buffers are needed, I prefer to use std::string instead: int main(){ auto required_size = get_required_buffer_size(); std::string buffer(required_size, '\0'); auto read_size = read_data(buffer.data()/*or: &buffer[0]*/, buffer.size()); buffer.resize(read_size); }
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) { for(auto param : params) { func(param); } } This works and compiles, but I want to improve this to use C++20 concepts. First I created an iterable concept like this: template<typename Container, typename ElementType> concept iterable = std::ranges::range<Container> && std::same_as<typename std::iterator_traits<Container>::value_type, ElementType>; and used it to check if the value_type of the iterator is the same as the parameter type of the provided container like this: template<typename Func, typename ParamType, typename Params> requires std::invocable<Func, ParamType> && iterable<Params, ParamType> void bar(Func func, Params params) { for(auto param : params) { func(param); } } But this doesn't compile for this simple example std::vector<int> payload(10, 5); bar(&foo, payload); with the following error message error C2672: 'bar': no matching overloaded function found error C2783: 'void bar(Func,Params)': could not deduce template argument for 'ParamType' Which somewhat makes sense as Func and Params are arguments of the function and ParamType is not, but I want to solve this without having to manually specify the type of parameter. I also tried changing the signature to void bar(Func func, Params<ParamType> params) or change to template to ... typename ParamType, typename Params<ParamType>> both of which didn't compile. How can I solve this without explicitly specifying the parameter type to bar?
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_reference_t<Rng>> void bar(Func func, Rng params) { for(auto &&param : params) { std::invoke(func, param); } }
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 the function when it finishes executing. And here comes my questions: Will this problem happened to all the functions which their return type is a pointer but they are running on stack?(Since they just return an address and stack delete every thing when the function finished running)? Is there any other things that pointer can do besides connecting stack to heap(Like Pointing to an address on heap)? From my understanding, the difference between stack and heap is that for stack, instead of manually allocating memory by programmer, stack allocating memory automatically by system continuously. So I am wondering if I have a function like this int ReturnInt() {const int a = 5;return a;} what actually this function returns, if it returns an address, won't stack deleted the 5 as before? If this function returns an integer 5, how to explain this integer in memory since it just add 4 bytes in RAM and changes still happens in memory address? Thank you so much for help :)
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 dereference.) Pointers can point to anything: globals, statics, and they can be passed from a caller (who could allocate their target on the stack for example). int ReturnInt(){const int a = 5;return a;} returns through a register on most platforms. If that's not possible, the compiler will have made sure the caller has stack-allocated space for the return value.
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.cbClsExtra = 0; Wcc.cbWndExtra = 0; Wcc.hInstance = (HINSTANCE)GetWindowLong(hParent, GWL_HINSTANCE); hInst_ = (HINSTANCE)GetWindowLong(hParent, GWL_HINSTANCE); Wcc.hIcon = LoadIcon(NULL, IDI_APPLICATION); Wcc.hCursor = LoadCursor(NULL, IDC_ARROW); Wcc.hbrBackground = reinterpret_cast<HBRUSH> (CreateSolidBrush(RGB( 255, 255, 255))); Wcc.lpszMenuName = NULL; Wcc.lpszClassName = className; this->className = className; this->hParent = hWnd; this->text = text; this->title = title; //this->title = title; windowW = 450; windowH = 300; hChild = CreateWindowExW(0, Wcc.lpszClassName, 0, WS_POPUP | WS_MINIMIZEBOX, x, y, windowW, windowH, hWnd, NULL, (HINSTANCE)GetWindowLong(hParent, GWL_HINSTANCE), NULL); loadResources(hChild); SetWindowLongPtrW(hChild, GWLP_USERDATA, (LONG)this); //SetTransparency(hChild, 0x0f); //ShowWindow(hChild, SW_SHOW); AnimateWindow(hChild, 1000, AW_ACTIVATE | AW_BLEND); PAINT: case WM_PAINT: { Paint(hDlg); break; } case WM_PRINTCLIENT: { PaintA(hDlg); break; } Paint(HWND hwnd) { PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &ps); Graphics graphics(hdc); Image image(L"g:\\_project\\image viewer\\ipcamera.jpg"); graphics.DrawImage(&image, 0, 0); EndPaint(hwnd, &ps); } PaintA(HWND hwnd) { HDC hdc = GetDC(hwnd); Graphics graphics(hdc); Image image(L"g:\\_project\\image viewer\\ipcamera.jpg"); graphics.DrawImage(&image, 0, 0); } enter image description here
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 = ChildWndProc; Wcc.cbClsExtra = 0; Wcc.cbWndExtra = 0; Wcc.hInstance = hInst; Wcc.hIcon = LoadIcon(NULL, IDI_APPLICATION); Wcc.hCursor = LoadCursor(NULL, IDC_ARROW); Wcc.hbrBackground = CreateSolidBrush(RGB(255, 0, 255)); Wcc.lpszMenuName = NULL; Wcc.lpszClassName = className; RegisterClassW(&Wcc); HWND hChild = CreateWindowW(className, nullptr, WS_POPUP | WS_MINIMIZEBOX, 100, 200, 300, 400, nullptr, nullptr, hInst, nullptr); AnimateWindow(hChild, 2000, AW_ACTIVATE | AW_BLEND); } And here is the window proc I used: LRESULT CALLBACK ChildWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_PAINT: { ::OutputDebugString(L"WM_PAINT\n"); PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); } case WM_PRINTCLIENT: { ::OutputDebugString(L"WM_PRINTCLIENT\n"); HDC hdc = (HDC)wParam; ::MoveToEx(hdc, 10, 10, nullptr); ::LineTo(hdc, 100, 100); } case WM_ERASEBKGND: { ::OutputDebugString(L"WM_ERASEBKGND\n"); return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } NOTE: For details, please see WM_PRINTCLIENT message A window can process this message in much the same manner as WM_PAINT, except that BeginPaint and EndPaint need not be called (a device context is provided), and the window should draw its entire client area rather than just the invalid region.
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 = SomeFunction(someobject); where someobject is of type N and SomeFunction is overloaded, returning different types based on the type of someobject — but, importantly, no overload of SomeFunction returns an N. Now, instead of a plain variable, I want to have a container (specifically, std::unordered_set) whose elements are of the type returned by SomeFunction, but I'm having trouble figuring out how to write the necessary class template parameter. I've tried std::unordered_set<auto> hoping the compiler can deduce the type from what elements it is initialized with, but that didn't work. I tried std::unordered_set<SomeFunction(someobject)>, std::unordered_set<SomeFunction(someobject)::type>, and std::unordered_set<typeof(SomeFunction(someobject))>, but those didn't work either. It seems the C++ standard lacks a way to express this directly.
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 of the C++ standard and so isn't supported by non-GCC compilers. For this reason you should always use decltype instead of typeof.
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 { Data data; Node *left, *right, *previous; }; InsertionStatus insertNode(Node* newNode, std::function<InsertionStatus(Data&, Data&)> insertion_method = NULL); } } // in another cpp using namespace A; template<class Data> typename Tree<Data>::InsertionStatus Tree<Data>::insertNode(Node* newNode, std::function<InsertionStatus(Data&, Data&)> insertion_method) { if (HasNoRoot()) { return InsertionStatus::INSERTION_COMPLETE; } return InsertionStatus::NO_INSERTION; } The compiler returns outer link not interpretable.
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 function in the header, the compiler knows everythin it needs to generate the body of the function instantiated with the concrete class. Then the linker would find this code in the module and link. If you don't define the template functon in the header, and the compiler doesn't see the code the defines the template function, it cannot generate the assembler code for it. Now consider another module where you define the template function. It knows how to generate the assembler code for any type... but it doesn't know which types it should generate this function for. There are multiple solutions how to solve the issue. First: define the template function body in the header where the template class is being defined. In this case the compiler sees all the code it needs to define the assembler code. Another solution: explicitly instantiate the class in the module where the function is defined for each type you plan to use.
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 b; a.A_lookup(b); In this case, I have two classes both of which would visit each other members. When compiling such a .cpp file, there are two piece of information: sample2.cpp:8:25: error: 'b' has incomplete type void A_lookup(B b){ sample2.cpp:4:7: note: forward declaration of 'class B' class B; Why could class A still not visit the member b_i of class B after class B has been declared ahead of class A. How should I fix such a error?
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 have only declared class B and not defined it, you get the mentioned error. Moreover, the expression b.b_i needs B to be a complete type as well. Solution You can solve this by declaring the member function A_lookup inside the class A and then defining it later when B is a complete type as shown below: #include <iostream> class B; class A{ public: int a_i=10; //only a declaration here void A_lookup(B b); }; class B{ public: int b_i=20; void B_lookup(A a){ std::cout << a.a_i <<std::endl; } }; //this is a definition. At this point B is a complete type void A::A_lookup(B b) { std::cout << b.b_i <<std::endl; } int main(void){ A a; B b; a.A_lookup(b); } Demo Solution 2 Note that you can also make the parameters a and b to be a reference to const A or reference to const B respectively as shown below. Doing so has some advantages like now the parameter a and b need not be complete type. But still expression a.a_i and b.b_i will need A and B respectively to be complete type. Also, now the argument will not be copied since now they will be passed by reference instead of by value. #include <iostream> class B; class A{ public: int a_i=10; void A_lookup(const B& b); //HERE ALSO void A_lookup(const B& b){ std::cout << b.b_i <<std::endl;} WILL NOT WORK }; class B{ public: int b_i=20; void B_lookup(const A& a){ std::cout << a.a_i <<std::endl; } }; void A::A_lookup(const B& b) { std::cout << b.b_i <<std::endl; } int main(void){ A a; B b; a.A_lookup(b); } Demo Also refer to Why should I not #include <bits/stdc++.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( ) { const std::string_view sv { " @a hgs -- " }; const size_t expectedTokenCount { 4 }; std::stringstream ss; ss << sv; std::vector< std::string > foundTokens; foundTokens.reserve( expectedTokenCount + 1 ); std::ranges::for_each( std::ranges::take_view { ss, expectedTokenCount + 1 }, [ &foundTokens ]( const std::string& token ) { std::back_inserter( foundTokens ); } ); if ( foundTokens.size( ) == expectedTokenCount ) { // do something } for ( const auto& elem : foundTokens ) { std::cout << std::quoted( elem ) << '\n'; } } How should I fix it? Also, how should I use back_inserter to push_back the extracted strings into foundTokens?
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 glaring issue here is that ss is not a view or range. You need to create a proper view of it: auto tokens = views::istream<std::string>(ss) | views::take(expectedTokenCount + 1); Now for the other issue: std::back_inserter( foundTokens ); This is a no-op. It creates a back-inserter for the container, which is an iterator whose iteration causes push_back to be called, but doesn't then use it. While the situation is poor in C++20 for creating a vector from a range or view, here's one way to do it: rng::copy(tokens, std::back_inserter(foundTokens)); Putting this all together, you can see a live example, but note that it might not be 100% correct—it currently compiles with GCC, but not with Clang. As noted below, you can also make use of views::split to split the source string directly if there's a consistent delimiter between the tokens: std::string_view delim = " "; auto tokens = views::split(sv, delim); However, you might run into trouble if your standard library hasn't implemented this defect report.
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 furthest I could get to before the it calls JNI methods is line 36 of Xslt30Processor.cpp : Xslt30Processor::Xslt30Processor(SaxonProcessor * p, std::string curr) { proc = p; jitCompilation = false; exception = nullptr; /* * Look for class. */ cppClass = lookForClass(SaxonProcessor::sxn_environ->env, \\ It fails here "net/sf/saxon/option/cpp/Xslt30Processor"); jobject tempcppXT = createSaxonProcessor2(SaxonProcessor::sxn_environ->env, cppClass, "(Lnet/sf/saxon/s9api/Processor;)V", proc->proc); if(tempcppXT) { cppXT = SaxonProcessor::sxn_environ->env->NewGlobalRef(tempcppXT); SaxonProcessor::sxn_environ->env->DeleteLocalRef(tempcppXT); } else { createException("Error: Failed to create the Xslt30Processor internal object"); } #ifdef DEBUG jmethodID debugMID = SaxonProcessor::sxn_environ->env->GetStaticMethodID(cppClass, "setDebugMode", "(Z)V"); SaxonProcessor::sxn_environ->env->CallStaticVoidMethod(cppClass, debugMID, (jboolean)true); #endif if(cppXT == nullptr) { createException(); } if(!(proc->cwd.empty()) && curr.empty()){ cwdXT = proc->cwd; } else if(!curr.empty()){ cwdXT = curr; } }
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 with the crash dump, here is the log 0000004f`ad1ff4e0 : ucrtbase!abort+0x4e 00000000`6ed19790 : Qt5Core!qt_logging_to_console+0x15a 000001b7`79015508 : Qt5Core!QMessageLogger::fatal+0x6d 0000004f`ad1ff0f0 : Qt5Core!QEventDispatcherWin32::installMessageHook+0xc0 00000000`00000000 : Qt5Core!QEventDispatcherWin32::createInternalHwnd+0xf3 000001b7`785b0000 : Qt5Core!QEventDispatcherWin32::registerSocketNotifier+0x13e 000001b7`7ad57580 : Qt5Core!QSocketNotifier::QSocketNotifier+0xf9 00000000`00000001 : Qt5Network!QLocalSocket::socketDescriptor+0x4cf7 00000000`00000000 : Qt5Network!QAbstractSocket::setSocketDescriptor+0x256 In the stderr log, I see those logs CreateWindow() for QEventDispatcherWin32 internal window failed (Not enough storage is available to process this command.) Qt: INTERNAL ERROR: failed to install GetMessage hook: 8, Not enough storage is available to process this command. Here is the function, where the code was stopped on the Qt codebase void QEventDispatcherWin32::installMessageHook() { Q_D(QEventDispatcherWin32); if (d->getMessageHook) return; // setup GetMessage hook needed to drive our posted events d->getMessageHook = SetWindowsHookEx(WH_GETMESSAGE, (HOOKPROC) qt_GetMessageHook, NULL, GetCurrentThreadId()); if (Q_UNLIKELY(!d->getMessageHook)) { int errorCode = GetLastError(); qFatal("Qt: INTERNAL ERROR: failed to install GetMessage hook: %d, %s", errorCode, qPrintable(qt_error_string(errorCode))); } } I did research and the error Not enough storage is available to process this command. maybe the OS (Windows) does not have enough resources to process this function (SetWindowsHookEx) and failed to create a hook, and then Qt fire a fatal signal, finally my app is killed. I tested this on Windows Server 2019, the app is working fine, no crashes appear. I just want to know more about the meaning of the error message (stderr) cause I don't really know what is "Not enough storage"? I think it is maybe the limit or bug of the Windows Server 2016? If yes, is there any way to overcome this issue on Windows Server 2016?
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-memory (The funny thing is the error message is Not enough storage is available to process this command but the real problem came to desktop heap limitation. ) So for the solution, flowing the steps in this link: https://learn.microsoft.com/en-us/troubleshoot/system-center/orchestrator/increase-maximum-number-concurrent-policy-instances I increased the 3rd parameter of SharedSection to 2048 and it fix the issue. Summary steps: Desktop Heap for the non-interactive desktops is identified by the third parameter of the SharedSection= segment of the following registry value: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\SubSystems\Windows The default data for this registry value will look something like the following: %SystemRoot%\system32\csrss.exe ObjectDirectory=\Windows SharedSection=1024,3072,512 Windows=On SubSystemType=Windows ServerDll=basesrv,1 ServerDll=winsrv:UserServerDllInitialization,3 ServerDll=winsrv:ConServerDllInitialization,2 ProfileControl=Off MaxRequestThreads=16 The value to be entered into the Third Parameter of the SharedSection= segment should be based on the calculation of: (number of desired concurrent policies) * 10 = (third parameter value) Example: If it's desired to have 200 concurrent policy instances, then 200 * 10 = 2000, rounding up to a nice memory number gives you 2048as the third parameter resulting in the following update to be made to the registry value: SharedSection=1024,3072,2048
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 a std::string in the first place, then you cannot move it into a std::string. In that case, you must copy the array instead. Or alternatively, if you cannot create the original buffer with std::string, then you could consider not attempting to create a std::string at all.
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 struggling with the implementation. How do i pass the allocator and deallocator to the shared object?
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{}; return {ptr, nng_msg_free}; }
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 : public BaseClass { public: Derived() {} void init(const int object) { cout<<"Derived::init"<<endl; } }; int main() { BaseClass b; b.init('c'); b.run('c'); Derived d; d.init(5); // Calls Derived::init d.run(5); // Calls Base::init. **I expected it to call Derived::init** } And here is generated output BaseClass::init BaseClass::run calls =>BaseClass::init Derived::init BaseClass::run calls =>BaseClass::init With call d.run(5), Why "BaseClass::init" is being called instead of "Derived::init" ? I though we need virtual functions only when calling through a pointer. What is the rationale behind keeping such behavior ?
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 object) { cout<<"BaseClass::init"<<endl; } //other member function here as before }; Demo I though we need virtual functions only when calling through a pointer. Note that the statement init(object); is equivalent to writing this->init(object); //here `this` is a pointer When you wrote: d.run(5); In the above statement, first the address of object d is implicitly passed as the first argument to the implicit this parameter of member function run. The type of this implicit this parameter is BaseClass* and this happens due to derived to base conversion. Now, the call init(object); is equivalent to this->init(object);. But since init is a non-virtual member function, the call is resolved at compile time meaning the base class init will be called. Basically when a member function is called with a derived class object, the compiler first looks to see if that member exists in the derived class. If not, it begins walking up the inheritance chain and checking whether the member has been defined in any of the parent classes. It uses the first one it finds. This means for the call d.run(5) the search for a member function named run starts inside the derived class. But since there is no function named run inside derived class, the compiler looks into the direct base class BaseClass and finds the member function named run. So it stops its search and uses this found run member function. And as i said, in your example, init is non-virtual and so the call is resolved at compile time to the base class run. On the other hand, if we make init to be a virtual member function, then this call will be resolved at run-time meaning the derived class init will be called.
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 touching the circle, and it shrinks the circle by the right amount (I put an std::cout line underneath mass -= shrinkAmount to test it) but the value of mass is never actually applied to the object. My guess is that I'm somehow changing the value of a copy of my circle object and not the actual referenced one but I have no idea how that'd be happening. Here's the entire object class if needed (I am using functions from Raylib): class Blib { private: Color color; Blib* address{ this }; public: float x; float y; float mass; /* Constructor */ Blib(float x, float y, float mass = 32.0f, Color color = Color{ 255, 255, 255, 200 }) { this->x = x; this->y = y; this->mass = mass; this->color = color; } /* Methods */ void check_collisions(std::vector<Blib> blibs) { // for (Blib blib : blibs) { if (CheckCollisionCircles(Vector2{ x, y }, mass, Vector2{ blib.x, blib.y }, blib.mass)) { if (mass > blib.mass && address != blib.address) { grow(blib.shrink(mass)); } } } } void draw() { DrawCircle(x, y, mass, color); } void grow(float amount) { mass += amount; } void move_with_keyboard() { float speed = 5.0f * mass * GetFrameTime(); if (IsKeyDown(KEY_W)) { y -= speed; } if (IsKeyDown(KEY_A)) { x -= speed; } if (IsKeyDown(KEY_S)) { y += speed; } if (IsKeyDown(KEY_D)) { x += speed; } } float shrink(float attackerMass) { float shrinkAmount = attackerMass * GetFrameTime(); mass -= shrinkAmount; return shrinkAmount; } };
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 check_collisions(std::vector<Blib> &blibs)
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; function tick(delta){ //this gets called every frame time += delta; print("pop"); } I've tried looking though this compiled documentation https://v8docs.nodesource.com/node-16.13/df/d69/classv8_1_1_context.html for a function in v8::Local<v8::Context>->Global that Get functions by name, from the compiled JS, but could not wrap my head around the keys system. I've tried reading through Calling a v8 javascript function from c++ with an argument but the examples seem outdated for the latest version of v8 in 2022.
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> #include <stdio.h> #include <stdlib.h> #include <string.h> const char jsCode[] = "var foo = function(arg) {" "if (Math.random() > 0.5) throw new Error('er');" "return arg + ' with foo from JS';" "}"; int main(int argc, char *argv[]) { // Initialize V8. v8::V8::InitializeICUDefaultLocation(argv[0]); v8::V8::InitializeExternalStartupData(argv[0]); std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform(); v8::V8::InitializePlatform(platform.get()); v8::V8::Initialize(); // Create a new Isolate and make it the current one. v8::Isolate::CreateParams create_params; create_params.array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator(); v8::Isolate *isolate = v8::Isolate::New(create_params); { v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handle_scope(isolate); // Create a context and load the JS code into V8 v8::Local<v8::Context> context = v8::Context::New(isolate); v8::Context::Scope context_scope(context); v8::Local<v8::String> source = v8::String::NewFromUtf8(isolate, jsCode, v8::NewStringType::kNormal).ToLocalChecked(); v8::Local<v8::Script> script = v8::Script::Compile(context, source).ToLocalChecked(); v8::Local<v8::Value> result = script->Run(context).ToLocalChecked(); v8::String::Utf8Value utf8(isolate, result); // This is the result of the evaluation of the code (probably undefined) printf("%s\n", *utf8); // Take a reference to the created JS function and call it with a single string argument v8::Local<v8::Value> foo_value = context->Global()->Get(context, v8::String::NewFromUtf8(isolate, "foo").ToLocalChecked()).ToLocalChecked(); if (foo_value->IsFunction()) { // argument (string) v8::Local<v8::Value> foo_arg = v8::String::NewFromUtf8(isolate, "arg from C++").ToLocalChecked(); { // Method 1 v8::TryCatch trycatch(isolate); v8::MaybeLocal<v8::Value> foo_ret = foo_value.As<v8::Object>()->CallAsFunction(context, context->Global(), 1, &foo_arg); if (!foo_ret.IsEmpty()) { v8::String::Utf8Value utf8Value(isolate, foo_ret.ToLocalChecked()); std::cout << "CallAsFunction result: " << *utf8Value << std::endl; } else { v8::String::Utf8Value utf8Value(isolate, trycatch.Message()->Get()); std::cout << "CallAsFunction didn't return a value, exception: " << *utf8Value << std::endl; } } { // Method 2 v8::TryCatch trycatch(isolate); v8::Local<v8::Object> foo_object = foo_value.As<v8::Object>(); v8::MaybeLocal<v8::Value> foo_result = v8::Function::Cast(*foo_object)->Call(context, context->Global(), 1, &foo_arg); if (!foo_result.IsEmpty()) { std::cout << "Call result: " << *(v8::String::Utf8Value(isolate, foo_result.ToLocalChecked())) << std::endl; } else { v8::String::Utf8Value utf8Value(isolate, trycatch.Message()->Get()); std::cout << "CallAsFunction didn't return a value, exception: " << *utf8Value << std::endl; } } } else { std::cerr << "foo is not a function" << std::endl; } } // Dispose the isolate and tear down V8. isolate->Dispose(); v8::V8::Dispose(); v8::V8::ShutdownPlatform(); delete create_params.array_buffer_allocator; return 0; }
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 file("bigfile.txt", ios::binary | ios::ate); cout << file.tellg() << " Bytes" << '\n'; ifstream bigFile("bigfile.txt"); constexpr size_t bufferSize = 4; unique_ptr<char[]> buffer(new char[bufferSize]); while (bigFile) { bigFile.read(buffer.get(), bufferSize); // print the buffer data cout << buffer.get() << endl; } } This gives me the following result: 26 Bytes ABCD EFGH IJKL MNOP QRST UVWX YZWX Notice how in the last line after 'Z' the character 'WX' is repeated again? How do I get rid of it so that it stops after reaching the end?
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 file read: #include <iostream> #include <fstream> #include <array> int main() { std::ifstream bigFile("bigfile.txt", std::ios::binary | std::ios::ate); int fileSize = bigFile.tellg(); std::cout << bigFile.tellg() << " Bytes" << '\n'; bigFile.seekg(0); constexpr size_t bufferSize = 4; std::array<char, bufferSize> buffer; while (bigFile) { for (int i(0); i < bufferSize; ++i) buffer[i] = '\0'; bigFile.read(buffer.data(), bufferSize); // Print the buffer data std::cout.write(buffer.data(), bufferSize) << '\n'; } } I also changed: The std::unique_ptr<char[]> to a std::array since we don't need dynamic allocation here and std::arrays's are safer that C-style arrays The printing instruction to std::cout.write because it caused undefined behavior (see @paddy's comment). std::cout << prints a null-terminated string (a sequence of characters terminated by a '\0' character) whereas std::cout.write prints a fixed amount of characters The second file opening to a call to the std::istream::seekg method (see @rustyx's answer). Another (and most likely more efficient) way of doing this is to read the file character by character, put them in the buffer, and printing the buffer when it's full. We then print the buffer if it hasn't been already in the main for loop. #include <iostream> #include <fstream> #include <array> int main() { std::ifstream bigFile("bigfile.txt", std::ios::binary | std::ios::ate); int fileSize = bigFile.tellg(); std::cout << bigFile.tellg() << " Bytes" << '\n'; bigFile.seekg(0); constexpr size_t bufferSize = 4; std::array<char, bufferSize> buffer; int bufferIndex; for (int i(0); i < fileSize; ++i) { // Add one character to the buffer bufferIndex = i % bufferSize; buffer[bufferIndex] = bigFile.get(); // Print the buffer data if (bufferIndex == bufferSize - 1) std::cout.write(buffer.data(), bufferSize) << '\n'; } // Override the characters which haven't been already (in this case 'W' and 'X') for (++bufferIndex; bufferIndex < bufferSize; ++bufferIndex) buffer[bufferIndex] = '\0'; // Print the buffer for the last time if it hasn't been already if (fileSize % bufferSize /* != 0 */) std::cout.write(buffer.data(), bufferSize) << '\n'; }
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; test.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::cout << Int; }; void CTest::Test() { pFuncton = &CTest::Function; (this->*pFuncton)(1); }; int main() { CTest test; test.Test(); }
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 set the path to the header file in "C/C ++ Build->Settings->Includes", and the header file is also visible in my project. I can include the "function_api.h" and access/use its pre-defined MACROs. However when I add e.g a new typedef to the "function_api.h", the new added typedef is not visible in my project. And then I created a new file (new->file), which is linked to the "function_api.h". After this step, the new added typedef is also visible in the project. So what I do not understand are: Why the new added typedef is not visible before linking the "function_api.h" (via new->file) while other pre-defined MACROs are visible ? What was changed after linking the "function_api.h", which make the new added typedef becoming visible? Thanks BL_
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. These projects are a play ground for me to understand more about c++. I decided I want a c# like functionalty between the exe and dll, so I exported a class from the dll class MyHttpClient. My first atempt was to export this class as a whole, but that resulted in the exe having dependancy on some of the libs the dll depends on due to the class having member fields whose types come from these libs, even though the build was successfull the exe would crash.. 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, I decorated this abstract class with __declspec(dllexport) using a predefined macro to __decspec(dllexport/import) the class based on the project it is in, and imported this headerfile into my exe main file. p.s. please note that the full class is also decorated with __declspec(dllexport). //inteface.h #include "def.h" //This is the abstract(interface) class class EXPORT_API MyHttpClient { public: MyHttpClient(); std::string Get(); }; main.cpp in exe includes the interface.h file. //MyHttpClient.h //Multiple #include "def.h" ... class EXPORT_API MyHttpClient { public: MyHttpClient(); std::string Get(); private: // some member fields }; //MyHttpClient.cpp provides implementation for the MyHttpClient class Now here is what happens: #include "inteface.h" int main() { // if I declare the class's object on the stack everything works as intended. MyHttpClient client; auto result = client.Get(); //if I set it on the heap the program crashes with Access violation // on the private members as if they were not there!! HttpClient* cli = new HttpClient; auto result = cli->Get(); // crash ... } Q1: Why do I see such behavior? I suspect that the new operator calls size of the abstract class and thus all the fields have no memory allocated, while the stack calls the construtor (where these members are initialized) and expands as these members are initialzed (that is my speculation but I really dont know!). Q2:How to remdy this issue? Thank you.
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 same class in different translation units must be formed by identical token sequences (plus some additional requirements). If you want an abstract class as interface, use inheritance and (pure) virtual functions.
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 stream shall be passed to the reader with a function like: class CHexFile { public: bool Open(std::istream& stream); uint16_t GetChunk(); // Return two bytes of the stream. private: void Validate(std::istream& stream); }; The parameter type is std::istream because this allows to prepare a std::strstream in a unit tester and pass the stream to the function. It's possible to detect the stream format and validate the entire stream. But how can I rewind the stream after validation (or format detection) and actually retrieve the data? Note: I have to use a rather old C++ compiler from 2006 (Paradigm). Therefore I can't use fancy features from C++1x or C++2x.
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: LancElem(){next = nullptr;} LancElem(int keyy, LancElem* nextt){key = keyy;next = nextt;} LancElem* getNext(){return next;} int getKey(){return key;} void setNext(LancElem* nextt){next = nextt; } void setKey(int keyy){key = keyy;} }; The remove fucntion: void removeByKey(LancElem& head, int key){ LancElem* n = head.getNext(); while(n->getNext()!=nullptr){ if(n->getNext()->getKey()==key){ n->setNext(n->getNext()->getNext()); delete n->getNext(); break; } n=n->getNext(); } } When I try to remove the biggest element: The original linked list: 4 1 9 8 2 7 3 6 3 Expected output: 4 1 8 2 7 3 6 3 The real output: 4 1 0 The problem is probably where I connect the current element to the next->next element but I can't figure out why my implementation isn't good.
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()); delete to_be_deleted;
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 or run any applyTemplates.. method after setting that XdmNode as the initial match selection with the method setInitialMatchSelection.
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 displaying anything. #include <iostream> using namespace std; int main(void) { int i = 0; while(i <= 24); int newTemp; int totalTemp; { cout << "Input temperature for the hour " << i << ":"; cin >> newTemp; totalTemp = totalTemp + newTemp; i++; cout << "The average temperature for the day is " << totalTemp/24 << " degrees"; } return (0); } How do I initialize it? and what is making my code not appear in the console when I'm trying to use cout?
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 your code as it would for int main() {}. You probably want while( i<=24) { .... Or rather use a for loop when the number of iterations is fixed. Moreover, totalTemp/24 is using integer arithmetics. Maybe thats what you want, but more likely you want totalTemp/24.0. And also very likely you want to print the average outside of the loop instead of printing it in every iteration.
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::Response &res){ res.complete_name = req.first_name + " " + req.last_name; res.double_age = 2 * req.age; ROS_INFO_STREAM("Secret number is: " << res.secret_num); ROS_INFO_STREAM("Requested score is: " << req.score); ROS_INFO_STREAM("Actual age is: " << req.age); ROS_INFO_STREAM("Double age is: " << res.double_age); ROS_INFO_STREAM("Complete name is: " << res.complete_name); return true; } int main(int argc, char** argv){ ros::init(argc, argv, "srv_server"); ros::NodeHandle nodehandle; ros::ServiceServer service = nodehandle.advertiseService("server_client", callback_function); ROS_INFO_STREAM("Service publishing"); ros::spin(); return 0; } The srv_client.cpp is: #include<iostream> #include<ros/ros.h> #include<std_msgs/String.h> #include<msg_srv_basics/addInts.h> int main(int argc, char** argv){ ros::init(argc, argv, "srv_client"); ros::NodeHandle nodehandle; ros::ServiceClient client = nodehandle.serviceClient<msg_srv_basics::addInts>("server_client"); msg_srv_basics::addInts service_node; service_node.request.age = 23; service_node.request.first_name = "Madyln"; service_node.request.last_name = "Monroe"; client.call(service_node); return 0; } The srv directory contains the addInts.srv (please ignore the files naming quality) string last_name string first_name uint8 age uint32 score=10 #request a constant --- uint8 double_age string complete_name uint32 secret_num=1234 #response constants The issue is, when I rosrun the code, I don't see any value printed for the actual age and double age. rosrun msg_srv_basics msg_srv_basics_server [ INFO] [1646657193.346883143]: Service publishing [ INFO] [1646657197.717564001]: Secret number is: 1234 [ INFO] [1646657197.717584344]: Requested score is: 10 [ INFO] [1646657197.717593796]: Actual age is: [ INFO] [1646657197.717599339]: Double age is: . [ INFO] [1646657197.717632206]: Complete name is: Madyln Monroe I can't see why the age is not printed, give the name is printed correctly. Please help!
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("Double age is: " << int(res.double_age));
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 native touch driver. The problem is that when I touch the +/- buttons (the scroll buttons that increase/decrease the slider by a single tick, or cause it to rapidly scroll if held), the slider rapidly slides up/down as if I had clicked and held the button. This is because my driver uses QApplication::postEvent() to dispatch the mouse event from a separate thread, and the delay in between touch and release is just long enough for it to register a click-and-hold type event, though the release event doesn't stop the sliding. I would rewrite the application to use the now available native touch driver, but it doesn't offer enough control to be able to do what my driver does (my driver can generate left, right, or middle mouse events, whereas the native driver only provides left). I tried rewriting the driver to use QApplication::sendEvent() instead, but that was causing a segmentation fault that I couldn't figure out the cause of. So is there a way I can disable the "click-and-hold" type behavior on the QSlider itself? So that I can still tap the buttons, but they'll only increase/decrease by a single tick at a time? EDIT: Here's an example of how I'm generating the "touch" events via my driver. void InputHandler::touchPress(TouchPoint * tp, QWidget * widget) { QPoint screenPos(tp->cx(), tp->cy()); QWidget * target = widget; if(target == NULL) target = QApplication::widgetAt(screenPos); if(target != NULL) { QPoint local = target->mapFromGlobal(screenPos); QMouseEvent * press = new QMouseEvent(QEvent::MouseButtonPress, local, screenPos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); QApplication::postEvent(target, press); DBG(" -- touch press on: " << typeid(*widget).name()); // Check to see if the target is a QLineEdit or QComboBox, and if so, set focus on it. QLineEdit * lineEdit = dynamic_cast<QLineEdit*>(target); QComboBox * comboBox = dynamic_cast<QComboBox*>(target); if(lineEdit) lineEdit->setFocus(Qt::MouseFocusReason); if(comboBox) comboBox->setFocus(Qt::MouseFocusReason); } } EDIT 2: So a coworker played around with the slider and pointed out that he pressed the +/- buttons, causing it to slide, and then he clicks the "reset" button we have to reset all controls on the form, the slider would reset and then continue sliding, indicating that the touch press was never released. He then would click the +/- buttons normally with the mouse and reset again and it would stop. So even though the logs indicate that the mousePressEvent and mouseReleaseEvent methods are being triggered by my events, they don't seem to have the same behavior as using the mouse. Any ideas? EDIT 3: If it helps, I added an eventFilter and printed out every event type that the QSlider receives, from when I first touch the screen to when I release. The events received are: Mouse Press (2) Tooltip Change (184) Paint (12) Mouse Move (5) Mouse Move (5) Mouse Release (3) But then after the release event, I get spammed in the logs with QEvent::Timer events, which does not happen when I simply click with the mouse, as opposed to touching the slider with the touchscreen. If I then tap somewhere else, drag the slider, or click the slider with the actual mouse, these timer events stop. Why is my generated QMouseEvent causing these QEvent::Timer events to be generated when I tap the slider with the touchscreen, but not with the mouse?
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 QSlider(); m.setCentralWidget(slider); m.resize(100, 100); m.show(); QTimer::singleShot(1000, [&](){ a.postEvent(slider, new QMouseEvent(QEvent::MouseButtonPress, QPoint(50,50), m.mapToGlobal(QPoint(50,50)), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier)); a.postEvent(slider, new QMouseEvent(QEvent::MouseButtonRelease, QPoint(50,50), m.mapToGlobal(QPoint(50,50)), Qt::LeftButton, Qt::NoButton, Qt::NoModifier)); }); return a.exec(); } This example decreases the slider value with 1 tick after 1 second. Note that it is important to pass Qt::NoButton as buttons parameters to the QEvent::MouseButtonRelease event, otherwise the slider will continue moving to the current mouse position (see QAbstractSlider::setRepeatAction), as QSlider thinks the button is still pressed. I assume this behaviour is what you call 'press-and-hold'.
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< int, hashmap_type > m_mapofmaps; }; using it via Myclass<false> v{}; triggers /opt/compiler-explorer/gcc-11.1.0/include/c++/11.1.0/bits/hashtable.h:191:21: error: static assertion failed: unordered container must have the same value_type as its allocator 191 | static_assert(is_same<typename _Alloc::value_type, _Value>{}, as can be seen here (GCC 11.1): But if the non-type template store is removed the compiler is suddenly having no issues anymore. The same holds for exchanging the lambda [](){} with another type, see here and here. What is this odd interplay between the boolean non-type template, the lambda, and allocators?
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<decltype([](){})> x; }; int main() { X<false> a; } Without the template<bool B>, decltype([](){}) is not a dependent expression, so is evaluated more eagerly (and you end up with something like assert_is_same<_ZN1XILb0EEUlvE0_E, _ZN1XILb0EEUlvE0_E>) Inside the template, [](){}'s type is now dependent on B, so can't be replaced with a type immediately. It seems like gcc expands it to assert_is_same<decltype([](){}), decltype([](){})>, where those two lambdas are now different. (the default argument in your map example is std::allocator<std::pair<const Key, T>>, or std::allocator<std::pair<const int, decltype([](){})>>) A workaround is to give the lambda something named it can hide behind: private: static constexpr auto lambda = [](){}; public: using hashmap_type = std::unordered_map< int, decltype(lambda) >; // allocator is now `std::pair<const int, decltype(lambda)>`, and // the two `decltype(lambda)`'s have the same type
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 these values? According to the Standard, std::numeric_limits<T>::epsilon is the machine epsilon, that is, the difference between 1.0 and the next value representable by the floating-point type T. But that doesn't necessarily mean that defining T(1) - std::numeric_limits<T>::epsilon would be better.
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 format your C++ implementation uses. (Binary vs. decimal, or width of mantissa aka significand, or anything else.) Example: Retrieving the closest value less than 1 for the double type (on Windows, using the clang-cl compiler in Visual Studio 2019), the answer is different from the result of the 1 - ε calculation (which as discussed in comments, is incorrect for IEEE754 numbers; below any power of 2, representable numbers are twice as close together as above it): #include <iostream> #include <iomanip> #include <cmath> #include <limits> int main() { double naft = std::nextafter(1.0, 0.0); std::cout << std::fixed << std::setprecision(20); std::cout << naft << '\n'; double neps = 1.0 - std::numeric_limits<double>::epsilon(); std::cout << neps << '\n'; return 0; } Output: 0.99999999999999988898 0.99999999999999977796 With different output formatting, this could print as 0x1.fffffffffffffp-1 and 0x1.ffffffffffffep-1 (1 - ε) Note that, when using analogous techniques to determine the closest value that is greater than 1, then the nextafter(1.0, 10000.) call gives the same value as the 1 + ε calculation (1.00000000000000022204), as would be expected from the definition of ε. Performance C++23 requires std::nextafter to be constexpr, but currently only some compilers support that. GCC does do constant-propagation through it, but clang can't (Godbolt). If you want this to be as fast (with optimization enabled) as a literal constant like 0x1.fffffffffffffp-1; for systems where double is IEEE754 binary64, on some compilers you'll have to wait for that part of C++23 support. (It's likely that once compilers are able to do this, like GCC they'll optimize even without actually using -std=c++23.) const double DoubleBelowOne = std::nextafter(1.0, 0.); at global scope will at worst run the function once at startup, defeating constant propagation where it's used, but otherwise performing about the same as FP literal constants when used with other runtime variables.
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, T*>::type xaddressof(T& arg) noexcept { return reinterpret_cast<T*>( &const_cast<char&>( reinterpret_cast<const volatile char&>(arg))); } template<class T> typename std::enable_if<!std::is_object<T>::value, T*>::type xaddressof(T& arg) noexcept { return &arg; } int main() { auto fn_1 = xaddressof<int>; // works (void) fn_1; auto fn_a = std::addressof<int>; // does not work (void) fn_a; } note: I know it may be illegal to do this, since function is in std::, but I care about language/implementation limitations, not UB since I am doing something evil.
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 templates with one template parameter. One taking T& as a function parameter and the other taking const T&& as a function parameter (where T is the template parameter). The latter is defined as delete'd. std::addressof<int> is not sufficient to decide which of these to choose. The library implementation could also choose to implement these specified overloads in different ways, or add additional overloads, which is why taking the address is unspecified.
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 continue, or q <return> to quit--- Is this expected from the gdb? We should just continue on that message or it means something? Note: I didn't set any breakpoint or anything, so didn't expect any message.
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 information you're looking for or until there is nothing more to print! (In other words, there is no breakpoint or anything of the sort getting triggered here and nothing happens to the control flow of the debugged program.)
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)>::value, "double pointer detected"); } I am curious why this compiles, as i was expecting the static_asserts to give an error.
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" ? does it calculate a rotation matrix ?
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::variant<Printable, NotPrintable> { Base(const Printable &) {} // constructor for implicit cast Base(const NotPrintable &) {} // constructor for implicit cast }; // Print, if printable, throw exception, if not void print(const Base &base) { Printer printer{}; base.apply_visitor(printer); } The problem is how to check for printable inside of visitor: struct Printer { using result_type = void; // If printable template<typename PrintableType> requires requires(const PrintableType &v) { {print(v)}; } // (1) void operator()(const PrintableType &v) { print(v); } // If not printable void operator()(const auto &v) { throw /*...*/; } }; Requirement (1) is always true due-to implicit conversion to const Base &. How to avoid conversion only in that exact place?
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 other things that may work: Deleted template function void print(auto) = delete; cons: Boilerplate for every function Forbids all implicit conversions struct Boolean; struct String; struct Integer { Integer(Boolean); friend Integer operator+(Integer, Integer); } template<class T, class U> requires (!std::convertible_to<U, T>) void operator+(T, U) = delete; Integer + Integer // OK Integer + String // ERROR (as expected) Integer + Boolean // OK Change interface struct Base : /* ... */ { /* ... */ static void print(Base); } cons: No operators support (Base + Base -> Base::add(Base, Base)) Interface a little bit worse Add traits template<typename T> struct Traits { static constexpr bool is_printable = true; } cons: Boilerplate for every class and method How to handle implicit conversion (Boolean + Integer)? Closed for extension
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 I can do: auto c = std::make_shared<c_t>(); c->some_fn(); // "calling from shared_ptr" And yes, c->some_fn() would work (C++ dereferences), but I want to know the pointer that is passed to some_fn() though — that is, I want to know what pointer is this.
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 some_fn(c.get()); // KO.
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(1, 15)); However if I use a class comparator, this is no longer working. struct classcomp { bool operator() (const C& lhs, const C& rhs) { return lhs.age < rhs.age; } }; multiset<C, classcomp> ms; ms.emplace(1, 15); ... // error // ms.count(C(1, 15)); Anything makes the two different?
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 object, and so it fails to compile. This works for the function pointer example, because it's the pointer that is const in that case.
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/lib64/libmqe_r.so No symbol table info available. #1 0x00007fb412101ccd in ImqTrc::checkWritePointer(void const*, unsigned long) () from /apps/mqm/lib64/libimqb23gl_r.so No symbol table info available. #2 0x00007fb412100264 in ImqStr::copy(char*, unsigned long, char const*, char) () from /apps/mqm/lib64/libimqb23gl_r.so No symbol table info available. #3 0x00007fb411fdd007 in ImqObj::setName(char const*) () from /apps/mqm/lib64/libimqc23gl_r.so No symbol table info available. #4 0x00007fb411fda4ee in ImqMgr::ImqMgr() () from /apps/mqm/lib64/libimqc23gl_r.so IBM MQ version 7.5 is installed on this 64 bit Linux machine. Same code is working fine on another machine having the same IBM MQ version installed on that. Can someone please help me to figure out what could be the reason behind this?
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++ that will connect to a remote queue manager and put a message to a queue. /* * Program Name * MQTest31.cpp * * Description * Test program to connect to a queue manager using MQCONNX and MQCSP * and then put a message from a queue. * * Sample Command Line Parameters * QMgrName ChlName hostname(port) QName * * Where * QMgrName is the queue manager name * ChlName is the name of the channel to be used * hostname(port) is the hostname and port number * QName is the queue name * i.e. * MQTest31.exe MQWT1 TEST.CHL 127.0.0.1(1415) TEST.Q1 * * @author Roger Lacroix, Capitalware Inc. */ /* * Standard Include files */ #include <iostream.h> #include <stdio.h> #include <string.h> #include <imqi.hpp> /* MQI */ /* * mainline */ int main ( int argc, char * * argv ) { /* -------------------------------------------- * Variable declarations. * -------------------------------------------- */ ImqQueueManager mgr; ImqChannel *pchannel = 0 ; ImqQueue queue; ImqMessage msg; /* */ char buffer[10240]; char myUserId[33] = "roger"; char myPassword[33] = "mypwd"; char testMsg[] = "This is a simple test message."; /* -------------------------------------------- * Code section * -------------------------------------------- */ if (argc != 5) { cout << "Usage: MQTest31 QMgrName ChlName hostname(port) QName" <<endl; return( 1 ); } cout << "MQTest31 Starting." <<endl; // Create object descriptor for subject queue mgr.setName( argv[ 1 ] ); pchannel = new ImqChannel ; pchannel -> setHeartBeatInterval( 1 ); pchannel -> setTransportType( MQXPT_TCP ); pchannel -> setChannelName( argv[ 2 ] ); pchannel -> setConnectionName( argv[ 3 ] ); mgr.setChannelReference( pchannel ); queue.setName( argv[ 4 ] ); /* * Specify UserId and Password via MQCSP */ mgr.setAuthenticationType(MQCSP_AUTH_USER_ID_AND_PWD); mgr.setUserId( myUserId ); mgr.setPassword( myPassword ); /* * Connect to queue manager */ if ( ! mgr.connect( ) ) { cout << "MQTest31: connect CC=" << mgr.completionCode()<< " : RC=" << mgr.reasonCode() <<endl; return( 1 ); } /* setup queue info */ queue.setConnectionReference( mgr ); queue.setOpenOptions(MQOO_OUTPUT + MQOO_FAIL_IF_QUIESCING); queue.open( ); cout << "MQTest31: open CC=" << queue.completionCode()<< " : RC=" << queue.reasonCode() <<endl; if ( queue.completionCode( ) == MQCC_OK ) { msg.useEmptyBuffer( buffer, sizeof( buffer ) ); msg.setMessageId( ); msg.setCorrelationId( ); msg.setFormat( MQFMT_STRING ); /* character string format */ strcpy(buffer, testMsg); msg.setMessageLength( (int)strlen( buffer ) ); queue.put(msg); cout << "MQTest31: put CC=" << queue.completionCode()<< " : RC=" << queue.reasonCode() <<endl; } /* Close the queue */ queue.close( ); cout << "MQTest31: close CC=" << queue.completionCode()<< " : RC=" << queue.reasonCode() <<endl; /* Disconnect from the queue manager */ mgr.disconnect( ); cout << "MQTest31: disconnect CC=" << mgr.completionCode()<< " : RC=" << mgr.reasonCode() <<endl; /* clean up */ if ( pchannel ) { mgr.setChannelReference( ); delete pchannel ; } cout << "MQTest31 Ending." <<endl; return( 0 ); }
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_libraries(my_test my_library) However I get link errors when building the tests- libmy_library.a(my_lib.cpp.o): In function `_GLOBAL__sub_I_00100_0__ZN7myClass10returnTrueEv': my_lib.cpp:(.text+0x2f): undefined reference to `__gcov_init' libmy_library.a(my_lib.cpp.o): In function `_GLOBAL__sub_D_00100_1__ZN7myClass10returnTrueEv': my_lib.cpp:(.text+0x3a): undefined reference to `__gcov_exit' libmy_library.a(my_lib.cpp.o):(.data.rel+0x20): undefined reference to `__gcov_merge_add' If instead of using target_link_options I use target_link_libraries - target_link_libraries(my_library PRIVATE gcov) then I don't get the errors. What's the reason for the difference in behaviour? I thought that target_link_libraries(my_library PRIVATE gcov) would be equivalent to target_link_options(my_library PRIVATE -lgcov).
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 myself doing kooky things (that I'd rather not show here) and I'd like to ask what the correct way to do the rehydration is.
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 back in with: long long i; in >> i; using D = std::chrono::duration<long long, std::ratio<1, 10'000'000>>; std::chrono::time_point<std::chrono::system_clock, D> tp{D{i}}; If the native system_clock::time_point has precision as fine as D or finer, you can implicitly convert to it: system_clock::time_point tp2 = tp; Otherwise you can opt to truncate to it with a choice of rounding up, down, to nearest, or towards zero. For example: system_clock::time_point tp2 = round<system_clock::duration>(tp);
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 Directories and modifying my installation but nothings worked. Update: In the build errors I got the following error fatal error C1083: Cannot open include file: 'crtdbg.h': No such file or directory and when I checked the directory where I would expect the header file to be it wasn't there.
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 initialise all the variables as undefined/NULL? Would that cause any bottlenecks in my code at compile time? namespace REGISTER { struct GPR { // 64-bit struct R64 { uint64_t RAX; // accumulator uint64_t RBX; // base uint64_t RCX; // counter uint64_t RDX; // data uint64_t RSP; // stack pointer uint64_t RBP; // stack base pointer uint64_t RSI; // source index uint64_t RDI; // destination index } R64; // 32-bit struct R32 { uint32_t EAX; uint32_t EBX; uint32_t ECX; uint32_t EDX; uint32_t ESP; uint32_t EBP; uint32_t ESI; uint32_t EDI; } R32; // 16-bit struct R16 { uint16_t AX; uint16_t BX; uint16_t CX; uint16_t DX; uint16_t SP; uint16_t BP; uint16_t SI; uint16_t DI; } R16; // 8-bit struct R8 { uint8_t AH; uint8_t BH; uint8_t CH; uint8_t DH; uint8_t AL; uint8_t BL; uint8_t CL; uint8_t DL; uint8_t SPL; uint8_t BPL; uint8_t SIL; uint8_t DIL; } R8; } GPR; // Segment registers struct SREG { uint16_t SS; // stack uint16_t CS; // code uint16_t DS; // data uint16_t ES; // extra data uint16_t FS; // more extra data uint16_t GS; // still more extra data } SREG; // Pointer registers struct PREG { uint64_t RIP; uint32_t EIP; uint16_t IP; } PREG; };
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-constructed version. It's good practice to automatically initialize all your values, anyway -- to 0 or nullptr or whatever makes sense. Leaving them undefined the way you have is a big opportunity for bugs. So: GPR blank; *this = blank; And you would be good to go.
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 << "Destructor A\n"; } }; class B : public A { public: B() { std::cout << "Constructor B\n"; } ~B() { std::cout << "Destructor B\n"; } }; int main() { A* a = new B; delete a; }
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 { public: A() { std::cout << "Constructor A\n"; } virtual ~A() { std::cout << "Destructor A\n"; } }; class B : public A { public: B() { std::cout << "Constructor B\n"; } ~B() override { std::cout << "Destructor B\n"; } }; int main() { A* a = new B; delete 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, MAX_PATH); std::wstring stemp = std::wstring(str.begin(), str.end()); LPCWSTR sw = stemp.c_str(); int a; if (CopyFile(buffer, sw, true)) a = 1; else a = 0; } Here I get the paths and save them in buffer (like D:\source\Project2\Debug\Project2.exe, I checked if that's the right path, if I paste what buffer contains in File Explorer, it runs the right .exe file) and sw (like C:\Users\user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup). But it doesn't copy, and the simple if check shows a=0. I thought it might not has the permission to copy files into the Startup folder, but it doesn't work with other "test" folders as well.
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 get extended error information, call GetLastError. GetLastError() would have told you that your inputs where unacceptable. So, to fix this, you will have to extract and concatenate the source filename onto your destination folder path, eg: std::wstring GetClipboardUnicodeText() { // get clipboard text using CF_UNICODETEXT, return as std::wstring... } void startup() { std::wstring str = GetClipboardUnicodeText(); WCHAR src[MAX_PATH] = {}; GetModuleFileNameW(NULL, src, MAX_PATH); WCHAR dest[MAX_PATH] = {}; PathCombineW(dest, str.c_str(), PathFindFileNameW(src)); int a = CopyFileW(src, dest, TRUE); } Otherwise, to copy a file into a folder without specifying a target filename, use SHFileOperation() instead, eg: void startup() { // note the extra null terminator! std::wstring dest = GetClipboardUnicodeText() + L'\0'; // note +1 for the extra null terminator! WCHAR src[MAX_PATH+1] = {}; GetModuleFileNameW(NULL, src, MAX_PATH); SHFILEOPSTRUCTW op = {}; op.wFunc = FO_COPY; op.pFrom = src; op.pTo = dest.c_str(); op.fFlags = FOF_FILESONLY; int a = SHFileOperationW(&op); }
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. The algorithm terminates upon any error (including timeout). */ template <class Protocol, class Executor> void do_async_echo (basic_stream<Protocol, Executor>& stream) { // This object will hold our state when reading the line. struct echo_line { basic_stream<Protocol, Executor>& stream; // The shared pointer is used to extend the lifetime of the // string until the last asynchronous operation completes. std::shared_ptr<std::string> s; // This starts a new operation to read and echo a line void operator()() { // If a line is not sent and received within 30 seconds, then // the connection will be closed and this algorithm will terminate. stream.expires_after(std::chrono::seconds(30)); // Read a line from the stream into our dynamic buffer, with a timeout net::async_read_until(stream, net::dynamic_buffer(*s), '\n', std::move(*this)); } // This function is called when the read completes void operator()(error_code ec, std::size_t bytes_transferred) { if(ec) return; net::async_write(stream, buffers_prefix(bytes_transferred, net::buffer(*s)), [this](error_code ec, std::size_t bytes_transferred) { s->erase(s->begin(), s->begin() + bytes_transferred); if(! ec) { // Run this algorithm again echo_line{stream, std::move(s)}(); } else { std::cerr << "Error: " << ec.message() << "\n"; } }); } }; // Create the operation and run it echo_line{stream, std::make_shared<std::string>()}(); } $ g++ -std=gnu++17 -I ./boost/boost_1_72_0. timeout_example.cpp -o ./build/timeout_example timeout_example.cpp: In member function ‘void do_async_echo(boost::beast::basic_stream<Protocol, Executor>&)::echo_line::operator()()’: timeout_example.cpp:43:18: error: ‘async_read_until’ is not a member of ‘boost::asio’; did you mean ‘async_result’? 43 | net::async_read_until(stream, net::dynamic_buffer(*s), '\n', std::move(*this)); | ^~~~~~~~~~~~~~~~ | async_result Question> Why does the compiler(g++ (GCC) 10.2.1) cannot find the boost::asio::async_read_until? Thank you
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> #include <set> class container { public: container(const int& s); static std::set<int, std::less<int>>& object_set_instance(); }; #include "container.hxx" // container.hxx #pragma once #include "container.hh" #include <iostream> container::container(const int& s) { auto set = object_set_instance(); set.insert(s); std::cout << "Size " << set.size() << "\n"; } std::set<int, std::less<int>>& container::object_set_instance() { static std::set<int, std::less<int>> s; return s; } #include "container.hh" #include <iostream> int main() { auto a = container(42); auto b = container(21); auto b1 = container(51); auto b2 = container(65); auto b3 = container(99); } Output : Size 1 Size 1 Size 1 // Size never change Size 1 Size 1 Why doesn't the set's size change ?
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 the referenced one), and the next line of code modifies the copy, and it gets thrown away immediately afterwards. This should be: auto &set = object_set_instance(); A debugger is a very useful tool for solving these kinds of Scooby-Doo mysteries, and it would clearly reveal what's going on here. If you haven't yet had the opportunity to learn how to use one, hopefully this will inspire you to take a look, and join Mystery, Inc. as a member in good standing.
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(int *c) { int X[N]; int tID = blockIdx.x * blockDim.x + threadIdx.x; for(int o = 0; o < N;o++) { X[o]=1; c[tID] +=X[o]; } } int main(int argc, char **argv) { // set up device int dev = 0; cudaDeviceProp deviceProp; CHECK(cudaGetDeviceProperties(&deviceProp, dev)); printf("%s test struct of array at ", argv[0]); printf("device %d: %s \n", dev, deviceProp.name); CHECK(cudaSetDevice(dev)); int c[N*Nblock]; int *dev_c; cudaMalloc((void **) &dev_c, N*Nblock*sizeof(int)); add<<<Nblock,N>>>(dev_c); cudaMemcpy(c, dev_c, N*Nblock*sizeof(int), cudaMemcpyDeviceToHost); int sum = 0 ; for (int i = 0; i < N*Nblock; i++) { sum +=c[i]; } printf("sum= %d\n", sum); free(dev_c); // reset device CHECK(cudaDeviceReset()); return EXIT_SUCCESS; } Got this message after running the code: line 4: 18244 Segmentation error (memory stack flushed to disk)
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 <iostream> using namespace std; int mostWordsFoundInASentence(vector<string>& sentences) { int longest = 0; transform(sentences.begin(), sentences.end(), sentences.begin(), [](string& line){ int c = count(line.begin(), line.end(), ' '); // count spaces in each sentence longest = c>longest ? c : longest; }); return longest+1; } int main() { vector<string> sentences = { {"alice and bob love leetcode"}, {"i think so too"}, {"this is great thanks very much"} }; cout << mostWordsFoundInASentence(sentences) << endl; return 0; } Error: Line 9: Char 13: error: variable 'longest' cannot be implicitly captured in a lambda with no capture-default specified
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( [](const auto& sentence) -> int { return std::count(sentence.begin(), sentence.end(), ' ') + 1; } ) ); } int main() { std::vector<std::string> sentences = { "alice and bob love leetcode", "i think so too", "this is great thanks very much" }; std::cout << mostWordsFoundInASentence(sentences) << "\n"; return 0; }
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/struct template parameter and a method instance parameter), but they are always solving a different problem (I think). #include <functional> template <typename T> struct Vec { T elem; Vec(T t) : elem(t) { } // this works, but I want to defer the definition to later template <typename R> Vec<R> fmap(std::function<R(T)> apply) const { return Vec<R>(apply(elem)); } // but I want to defer the definition to later in the file // template <typename R> // Vec<R> fmap2(std::function<R(T)> apply) const; }; // This FAILS: how do I refer to this? // template <typename T,typename R> // inline Vec<R> Vec<T>::fmap2(std::function<R(T)> apply) const { // return Vec<R>(); // } Uncommenting fmap2 on GCC gives. no declaration matches ‘Vec<R> Vec<T>::fmap2(std::function<R(T)>) const’ Visual Studio 2019 gives unable to match function definition to an existing declaration The inline definition works, but I want to define that templated member later in the compilation unit if possible. Thanks in advance.
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 rewrite the code snippet like this: std::packaged_task<int()> task([]{ return 7; }); // wrap the function std::thread t(std::move(task)); // firstly launch on a thread, and then gets a future std::future<int> f1 = task.get_future(); // get a future UPDATED1: I understand Nicol Bolas's answer, is there any potential problem(race condition) if I rewrite the code snippet like this: std::packaged_task<int()> task([]{ return 7;}); thread_callablefunc_queue.push_back(task); //task may be popped and run by another thread at once, queue is protected by mutex. std::future<int> f1 = task.get_future(); // get a future What worries me is that the task may be invoked by another thread at once while the current thread is calling task.get_future().
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 this: std::packaged_task<int()> task([]{ return 7; }); auto t(std::move(task)); std::future<int> f1 = task.get_future(); task has been moved from, because that's what you asked to do.
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> using namespace std; int buscarpeq (int[],int); int main () { string busquedasFrecuentes[20] ={"2d arrays","matrices","algoritmos", "arrays c++", "C++ Multidimensional", "initialize 2d array", "center elements","2d array as element", "matriz bidimensional","too many initializers","0x6ffdf0 error c++","c++ beginners","error initializers char","combining 2d array","random number list generator","multidimensional arrays","c++ matriz 2 arrays","llenar matriz letras","multidimensional char array","c++ matrix bidimensional"}; int frecuencia [] = {152,5,5,842,476,438,65,152,148,4,16,5,634,634,120,16,729,148,83,645,83,570,148,842,706,788,842,716,395,707,707,152,500,560,614,463,847,152,83,707}; int pos,temp,pass=0; cout<<"\n\n\n Elementos a ordenar\n"; for(int i=0;i<20;i++) { cout<<busquedasFrecuentes[i]<<"\t"; } cout<<"\n\n\n Elementos a ordenar\n"; for(int i=0;i<20;i++) { cout<<frecuencia[i]<<"\t"; } for(int i=0;i<20;i++) { pos = buscarpeq (frecuencia,i); temp = frecuencia[i]; frecuencia[i]=frecuencia[pos]; frecuencia[pos] = temp; pass++; } cout<<"\n\n\n Lista ordenada...\n"; for(int i=0;i<20;i++) { cout << " " << busquedasFrecuentes << " " <<frecuencia[i]<< sizeof(20) << endl; } cout<<"\n\nNumero de ciclos usados para ordenar la lista: "<<pass<<endl; return 0; } int buscarpeq(int frecuencia[],int i) { int ele_small,position,j; //declaramos variables elementos menores y posiciones ele_small = frecuencia[i]; position = i; for(j=i+1;j<20;j++) { if(frecuencia[j]<ele_small) { ele_small = frecuencia[j]; position=j; } } return position; } Any suggestion?
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 each string. That will always resolve to the number 4(or more precisely, the size of an integer on your platform) getting printed on the end of each line.
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::vector<T> v; public: void push(T a); void printOn(std::ostream & os) const; template <typename U> friend std::ostream& operator<< (std::ostream& out, const Stack<U> & s); }; template<typename T> std::ostream& operator<< (std::ostream out, const Stack<T> & s) { s.printOn(out); return out; } template<class T> void Stack<T>::push(T a) { v.push_back(a); } template<class T> void Stack<T>::printOn(std::ostream & out) const { for(T const & vi : v) {out << vi << " ";} } int main() { Stack<int> s1; s1.push(12); s1.push(34); std::cout << s1; }
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) // ^ { s.printOn(out); return out; }
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, int y) { return std::pow(x,y); } void task_thread() { std::packaged_task<int(int,int)> task(f); std::future<int> result = task.get_future(); std::thread task_td(task, 2, 10); //std::move(task) works task_td.join(); std::cout << "task_thread:\t" << result.get() << '\n'; } int main() { task_thread(); } As std::thread need callable&&, why this code snippet below works? In this code snippet, f1 is a normal function, I think it's a callable& other than callable&&. #include <iostream> #include <utility> #include <thread> #include <chrono> void f1(int n) { for (int i = 0; i < 5; ++i) { std::cout << "Thread 1 executing\n"; ++n; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } void f2(int& n) { for (int i = 0; i < 5; ++i) { std::cout << "Thread 2 executing\n"; ++n; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } class foo { public: void bar() { for (int i = 0; i < 5; ++i) { std::cout << "Thread 3 executing\n"; ++n; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } int n = 0; }; class baz { public: void operator()() { for (int i = 0; i < 5; ++i) { std::cout << "Thread 4 executing\n"; ++n; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } int n = 0; }; int main() { int n = 0; foo f; baz b; std::thread t1; // t1 is not a thread std::thread t2(f1, n + 1); // pass by value std::thread t3(f2, std::ref(n)); // pass by reference std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread std::thread t5(&foo::bar, &f); // t5 runs foo::bar() on object f std::thread t6(b); // t6 runs baz::operator() on a copy of object b t2.join(); t4.join(); t5.join(); t6.join(); std::cout << "Final value of n is " << n << '\n'; std::cout << "Final value of f.n (foo::n) is " << f.n << '\n'; std::cout << "Final value of b.n (baz::n) is " << b.n << '\n'; }
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 created via copy if you provide lvalues, or by move if you provide xvalues or prvalues. This means that, by default, std::thread will not reference variables outside of the constructor call itself. This also means that it requires explicit effort (std::ref or similar) to access an object through a parameter which is not owned by the thread being invoked. packaged_task is a move-only type. The compilation failed because you did not invoke std::move on it, so decay-copy attempted to copy the type. Since it's move-only, compilation failed. But that is a property of packaged_task, not of std::thread.
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 #define LLIST_H #include <string> class llist { private: record *start; std::string file_name; int read_file(); int write_file(); record* reverse_llist(record *); void delete_all_records(); public: llist(); llist(std::string); ~llist(); int add_record(std::string, std::string, int, std::string); int print_record(std::string); int modify_record(std::string, std::string, std::string); void print_all_records(); int delete_record(std::string); void reverse_llist(); }; #endif record header file record.h #include <string> #ifndef RECORD_H #define RECORD_H struct record { std::string name; std::string address; int birth_year; std::string phone_number; struct record* next; }; #endif list.cpp read_file function int llist::read_file() { // read_file variables std::ifstream read_file(file_name.c_str()); struct record *temp = NULL; struct record *index = NULL; struct record *previous = NULL; int file_char_length = 0; int record_count = 0; std::string dummy = ""; if (!read_file.is_open()) { read_file.close(); return -1; } // end if !read_file.is_open() read_file.seekg(0, read_file.end); // move read pointer to end of file file_char_length = read_file.tellg(); // return file pointer position if (file_char_length == 0) { read_file.close(); return 0; } // end file_char_length == 0 read_file.seekg(0, read_file.beg); // reset file pointer to beginning do { // do while !read_file.eof() // do while temporary variables std::string address = ""; temp = new record; index = start; std::getline(read_file, temp->name); std::getline(read_file, temp->address, '$'); read_file >> temp->birth_year; std::getline(read_file, dummy); std::getline(read_file, temp->phone_number); std::getline(read_file, dummy); ++record_count; while (index != NULL) { <-- what's the purpose of this loop? previous = index; index = index->next; } // end while index != NULL if (previous == NULL) { <-- why would the start pointer of the temp->next = start; list not at the start but after temp? start = temp; } else { // else if previous != NULL previous->next = temp; <-- what is the purpose of this loop? temp->next = index; } // end if previous == NULL } while (!read_file.eof()); // end do while read_file.close(); return record_count; // read_file return - end of function }
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 multiple techniques to do this; this is one of the more common. As index races to the end of the loop previous stays one step behind. Why would the start pointer of the list not at the start but after temp? if (previous == NULL) { temp->next = start; start = temp; Answer: fighting the grammar of that question, the usage of start here as the right-side of this assignment is pointless. It must be NULL or the prior loop would have loaded previous with a non-NULL value and this if-condition would have failed. The code could just as easily read: temp->next = nullptr; start = temp; what is the purpose of this loop? } else { // else if previous != NULL previous->next = temp; temp->next = index; } // end if previous == NULL Answer: First, this isn't a loop. This is the else clause to the prior if, which means if this runs it is because previous was non-null. Similar to the odd usage of start in (2) above, the use of index here is pointless. If you look to the loop you asked about in (1) you clearly see that thing doesn't stop until index is NULL. Nothing between there and here changes that fact. Therefore, temp->next = nullptr; is equivalent to what is happening here. Not sugarcoating it; this implementation is weak, and that is on a good day. Whomever it came from, consider it a collection of how things can be done, but by no means how they should be done.
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(int i) { cout << i << " "; } int main() { int mynumbers[] = { 3,9,2,4,1 }; vector<int> v1(mynumbers, mynumbers + 5); set<int> s1(mynumbers, mynumbers + 5); transform(v1.begin(), v1.end(), s1.begin(), multiply); for_each(v1.begin(), v1.end(), print); cout << endl; for_each(s1.begin(), s1.end(), print); }
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> s; std::transform(v.begin(), v.end(), std::insert_iterator<std::set<int>>(s, s.begin()), [](int x) { return x * 2; }); for (int x : s) std::cout << ' ' << x; } Output: 2 4 6 8 10 Live demo on coliru
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 good . I am given enough time to figure out what could be the error but am not able to find. Output 0 1 0 0 1 1 0 1 0 1 Expected Output 01 0011 01 01 I am not able figure out the error , Please help me with this. #include <iostream> #include <vector> using namespace std; vector<string> maxSubStr(string s, int n) { vector<string> v; for (int i = 0; i < n; i++) { int ones = 0; int zeros = 0; int j = 0; for (j = i; zeros != ones && j<n; j++) { if (s[j] == '0') { zeros++; } else { ones++; } } if (zeros == ones) { int size = j - i; v.push_back(s.substr(i, size)); } if(j==n){ break; } i = j ; } return v; } int main() { string str = "0100110101"; int n = str.length(); vector<string> v; v = maxSubStr(str, n); vector<string>::iterator it; for (it = v.begin(); it != v.end(); it++) { cout << *it << " "; } return 0; }
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 string. Next, you do not want to test s[i] but s[j]. Finally, the test zeros == ones should be in the j loop and should set i to the next position, that is j + 1. Code could become: vector<string> maxSubStr(string s) { vector<string> v; int n = s.size(); for (int i = 0; i < n; i++) { int ones = 0; int zeros = 0; int j = 0; for (j = i; j < n; j++) { if (s[j] == '0') { zeros++; } else { ones++; } if (zeros == ones) { v.push_back(s.substr(i, j + 1 - i)); i = j; break; } } } return v; }
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 getting an error here. #include <iostream> #include <stream> using namespace std; int main() { ifstream in_stream("HW2Test.txt"); ofstream output_stream("HW2output.txt"); string result[100]; int i; while(!in_stream.eof()) { in_stream>>result[i]; i++; } for(int j = 0; j<i; j++) { if((result[j][0]=='/')&&(result[j][0]=='/')) { output_stream<<result[j+1]; } } output_stream.close(); in_stream.close(); return 0; }
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("Description"); Now I want to style it using QSS, thus i wrote this: QLineEdit[text=""], QTextEdit[text=""] { color: red; } But unfortunately this works only for QLineEdits and I cannot find a way to check if QTextEdit is empty in QSS. Do you have any idea? Thanks in advance.
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 reference of doing this in QT documentation. If you want to look about complex examples other than this: Change color of placeholder text in QLineEdit https://forum.qt.io/topic/90176/change-qlineedit-placeholder-text-color
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_guard<std::mutex> a_lock(a_mutex); /* do something */ B(); } According to this post, I think these two are just to lock mutex. And B() is called by A(), so maybe scoped_lock inside B() is not needed, and can be removed. Is it right?
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 a_mutex locked */ B(); } It seems like A could be changed to void A(){ { const std::lock_guard<std::mutex> a_lock(a_mutex); /* do something that needs a_mutex locked */ } B(); } But whether this is still correct depends on details that were left out from the posted code. Locking two different mutexes is not redundant, because other threads may lock only one of them.
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/serialization/nvp.hpp" #include <boost/serialization/array_wrapper.hpp> #include "CPUStructs.h" namespace API::Network { class PerfAuditResponse { public: PerfAuditResponse() = delete; explicit PerfAuditResponse(std::string msg, int code, const Performance::CPUData &CPUData, const std::vector<Performance::ProcessData> &processesData) : message(std::move(msg)), httpCode(code), CPUIdleTime(CPUData.GetIdleTime()), CPUActiveTime(CPUData.GetActiveTime()), _processesData(processesData) { }; private: friend class boost::serialization::access; template<typename Archive> void serialize(Archive &ar, unsigned) { ar & BOOST_SERIALIZATION_NVP(CPUIdleTime) & BOOST_SERIALIZATION_NVP(CPUActiveTime) & BOOST_SERIALIZATION_NVP(message) & BOOST_SERIALIZATION_NVP(httpCode); } std::string message; boost::int32_t httpCode; std::size_t CPUIdleTime; std::size_t CPUActiveTime; const std::vector<Performance::ProcessData> &_processesData; }; } #endif //JUCECMAKEREPO_PERFAUDITRESPONSE_H And here is the compiler output: [...]/boost-src/libs/serialization/include/boost/serialization/access.hpp:116:11 error: request for member ‘serialize’ in ‘t’, which is of non-class type ‘long unsigned int’ t.serialize(ar, file_version); Does someone have any clue about where does it come from?
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 missed: Live On Coliru #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/integer.hpp> //#include <boost/serialization/array_wrapper.hpp> #include <boost/serialization/nvp.hpp> #include <iostream> #include <sstream> #include <vector> namespace Performance { struct CPUData { std::size_t idle, active; std::size_t GetIdleTime() const { return 0; } std::size_t GetActiveTime() const { return 0; } }; struct ProcessData { }; } // namespace Performance namespace API::Network { class PerfAuditResponse { public: //PerfAuditResponse() = delete; explicit PerfAuditResponse(std::string msg, int code, const Performance::CPUData &CPUData, const std::vector<Performance::ProcessData> &processesData) : message(std::move(msg)), httpCode(code), CPUIdleTime(CPUData.GetIdleTime()), CPUActiveTime(CPUData.GetActiveTime()), _processesData(processesData) { }; private: friend class boost::serialization::access; template<typename Archive> void serialize(Archive &ar, unsigned) { ar& BOOST_SERIALIZATION_NVP(CPUIdleTime) & BOOST_SERIALIZATION_NVP(CPUActiveTime) & BOOST_SERIALIZATION_NVP(message) & BOOST_SERIALIZATION_NVP(httpCode); } std::string message; boost::int32_t httpCode; std::size_t CPUIdleTime; std::size_t CPUActiveTime; const std::vector<Performance::ProcessData>& _processesData; }; } int main() { std::stringstream ss; std::vector<Performance::ProcessData> const pdata(13, Performance::ProcessData{}); { boost::archive::text_oarchive oa(ss); API::Network::PerfAuditResponse par("Yo", 42, {99, 320}, pdata); oa << par; } std::cout << ss.str() << "\n"; { API::Network::PerfAuditResponse par("default", -1, {}, pdata); { boost::archive::text_iarchive ia(ss); ia >> par; } ss.str(""); ss.clear(); { boost::archive::text_oarchive oa(ss); oa << par; } std::cout << " --- COMPARE --- \n" << ss.str() << "\n";; } } Prints e.g. 22 serialization::archive 19 0 0 0 0 2 Yo 42 --- COMPARE --- 22 serialization::archive 19 0 0 0 0 2 Yo 42
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 Output n: 00 k: 0100 l: 0101 i: 01100 j: 01101 m: 0111 o: 10 p: 11 My Output n: 00 o: 01 k: 1000 l: 1001 i: 10100 j: 10101 m: 1011 p: 11 My code #include<bits/stdc++.h> using namespace std; struct Node { char data; int freq; Node *left, *right; Node(char x, int y): data(x), freq(y), left(NULL), right(NULL) {} }; struct compare { bool operator()(Node *l, Node*r) { return l->freq > r->freq; } }; void display(Node *p, string str) { if(p) { if(p->data != '$') cout << p->data << ": " << str << "\n"; display(p->left, str + "0"); display(p->right, str + "1"); } } void huffmanCodes(char data[], int fr[], int n) { priority_queue<Node*, vector<Node*>, compare > pq; for(int i=0;i<n;i++) pq.push(new Node(data[i], fr[i])); while(pq.size() != 1) { Node *l = pq.top(); pq.pop(); Node *r = pq.top(); pq.pop(); Node *t = new Node('$', l->freq + r->freq); t->left = l; t->right = r; pq.push(t); } display(pq.top(), ""); } int main() { int n; cin >> n; char data[n]; int freq[n]; for(auto &x: data) cin >> x; for(auto &x: freq) cin >> x; huffmanCodes(data, freq, n); }
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 and 1 on the right, or 1 on the left and 0 on the right. So there are actually 256 different ways to make valid Huffman codes for those frequencies.
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() { std::cout << "B" << std::endl; } }; int main() { A a; B b; std::tuple<A,B> t = std::make_tuple(a,b); static constexpr int search_id = 2; auto& item = std::get< ? ( T::id == search_id ) ? >(t); item.work(); return 0; } I guess using std::apply and test would be a runtime search... I'm using c++20
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"); } // You can also possibly handle duplicate ids. return std::distance(std::begin(ids), it); } template <int id, typename... Ts> constexpr auto& get_item(std::tuple<Ts...>& t) { return std::get<get_index<Ts...>(id)>(t); } template <int id, typename... Ts> constexpr const auto& get_item(const std::tuple<Ts...>& t) { return std::get<get_index<Ts...>(id)>(t); } and then auto& item = get_item<search_id>(t);
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 derivedClass : public virtualBase { public: void printName() { std::cout << "Derived name" << std::endl; }; derivedClass() {}; ~derivedClass() = default; }; int main() { derivedClass d; d.printName(); return 0; } I need to uncomment the default constructor definition in base class for the compilation to succeed. I am seeing the following compilation error: test.cpp: In constructor ‘derivedClass::derivedClass()’: test.cpp:18:18: error: no matching function for call to ‘virtualBase::virtualBase()’ 18 | derivedClass() {}; | ^ test.cpp:10:3: note: candidate: ‘virtualBase::virtualBase(const virtualBase&)’ <deleted> 10 | virtualBase(const virtualBase &) = delete; // Disable Copy Constructor | ^~~~~~~~~~~ test.cpp:10:3: note: candidate expects 1 argument, 0 provided My understanding is that compiler provides it own default constructor esp in case like this where the class is really simple. What am I missing here? Thanks
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: "<<uni; } }; class student{ private: university u; public: student() { u = university("ABC"); } }; int main() { student s; return 0; } the output is: default constructor of university is invoked parametrized constructor of university is invoked: ABC but when changing the the constructor of student class to use initializer list like following: student(): u(university("ABC")){ } the output is: parametrized constructor of university is invoked: ABC My question is: for the second case, when the compiler runs the line university u in the private section of student class, does it create an object 'u' of class 'university' and allocate a memory address to it, or does the object get created in the initializer list? if the former, then why didn't it call the default constructor? for the first case, I have the same question where does the object get created and assigned a memory location.
"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 and destroyed "in the same place" (via placement new and explicit destructor invocations). Actual memory locations, and object constructions/destructions, are completely immaterial. They have nothing to do with each other, and it will be helpful if you simply forget everything about memory locations, and focus only on the topic of object construction and destruction. Having said all of that: An object constructor is responsible for constructing all members of the object. That's the rule. No exceptions. Full stop. student(): u(university("ABC")){ This will work, but this also does this in a confusing member. This spells out the following sequence of events: a temporary university object gets constructed, then copy-constructs the actual member of the student class, finally the temporary object gets destroyed. This is unnecessary and only serves to muddy the waters. Using a simpler, modern C++ syntax, this should be: student(): u{"ABC"}{ This shorter, direct syntax, describes exactly what's going on in a simple, concise manner: the object's constructor constructs all members of this object, namely just one, here. It's called u. u's constructor gets invoked passing to it a character string as a parameter. The university's "parametrized" constructor gets called. A constructor's member initialization section is nothing more than a simple list: here are my class members, and here are the parameters to their respective constructors. Abracadabra: they're constructed. student() { If a constructor does not have a member initialization section, or does not list the object's member in the initialization section, the corresponding class members' default constructors get called. That's it, that's all there is to it: your class *here the class is called student) has members, and the class's constructor explicitly initializes them, the corresponding constructor gets called, for the class members. If any class member is not listed in the initialization section its default constructor gets called, if the class member does not have a default constructor the resulting code is ill-formed and won't compile.
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 not help either vec.push_back(a); } std::vector<A> const& getVec() const { return vec; } private: std::vector<A> vec; }; class C{ public: C(B const& b, A const& a) : a(a), b(b) {} A const& getA() const { return a; } B& getB() { return b; } private: A a; B b; }; class D{ public: C& add(C& c){ A const& a = c.getA(); B& b = c.getB(); b.add(a); vec.push_back(c); return c; } private: std::vector<C> vec; }; int main(){ A a1{"first"}; A a2{"second"}; B b; C c1{b, a1}; C c2{b, a2}; D d; d.add(c1); d.add(c2); for(A const& a : b.getVec()){ std::cout << a.getName() << ' '; } } There is no output from the program, but I would expect output: first second Where the B class is holding the vector, and D is trying to modify it (c.getB().add()) via class C. It's just simple example (encountered in a school project), but I wanted to know by this example the flow of changes between classes.
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; } Output 0x61fee8 1 0 4 3 2 But since I filled the array in increasing order and incremented the pointer I was expecting the output to be as 1 2 3 4 and why there is a zero in 2nd line?
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 last cout, it is possible that the third ptr++ is evaluated before the first one. If you replace your last cout with multiple couts as follows, you will see that the code works as you expect. cout<< *ptr; cout<< *ptr++; cout<< *ptr++; cout<< *ptr++;
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 convert_drawing_to_LEDS(int drawing[]) { for (int i=0; i<3; ++i) { for (int j=0; j<3; ++j) { if (drawing[i][j] == 1) { digitalWrite(pin_locations[i][j], HIGH); } } } } void loop() { // drawing int my_drawing[3][3] = { {1, 1, 1}, {1, 0, 1}, {1, 1, 1} }; convert_drawing_to_LEDS(my_drawing); } But it gives me two errors: src/main.cpp: In function 'void convert_drawing_to_LEDS(int*)': src/main.cpp:31:23: error: invalid types 'int[int]' for array subscript if (drawing[i][j] == 1) { ^ src/main.cpp: In function 'void loop()': src/main.cpp:46:37: error: cannot convert 'int ()[3]' to 'int' for argument '1' to 'void convert_drawing_to_LEDS(int*)' convert_drawing_to_LEDS(my_drawing); ^ Compiling .pio/build/uno/FrameworkArduino/WInterrupts.c.o *** [.pio/build/uno/src/main.cpp.o] Error Can anyone help me? Thanks!
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 drawing[3][3]) {
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; i < 8; i++) { for (int j = 0; j < 8; j++) { chessboard[i][j]=NULL; if(i==6) isBlack=0; if(i==0 || i==7) { switch(j) { case 0: case 7: chessboard[i][j]=&pieces[tmp]; pieces[tmp++].setPiece(isBlack,rook); break; Class Piece has only an enumerator and fundamental type variables: enum Figure { king,queen,rook,bishop,knight,pawn }; class Piece { bool isBlack; Figure figure_type; public: Piece() {}; If a piece hits another piece, the pointer is simply overwritten like so: 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? I think not, because array pieces[] keeps track of all the pointers, but my paranoia gets better of me. Would it cause memory leaks if class Piece had some constructed classes, i.e. class Piece { bool isBlack; std::vector<std::string> figure_type; public: Piece() {}; ?
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 so that the dynamic memory cannot be freed anymore. The shown program doesn't allocate any dynamic memory (except through the vector member, but the vector class takes care to not leak the memory that it manages).
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 "Incomplete type bla bla". Alright, I did it on a little test which respects this, but I still have the "incomplete type" error. The code is just below, it's very short. A.hpp: #pragma once #include <memory> class A { public: A(); ~A(); private: class B; std::unique_ptr<B> m_b = nullptr; }; A.cpp: #include "A.hpp" class A::B { }; A::A() { } A::~A() // could be also '= default' { } main.cpp: #include "A.hpp" int main() { A a1; return 0; } I built in 2 (quick and dirty) ways and the result is very surprising from my point of view. First I built without linking A.cpp g++ -c A.cpp No error so far. Then, I compiled A.cpp and main.cpp to create an executable g++ A.cpp main.cpp -o test That's where I am into troubles. Here I got the famous error about the incomplete type: In file included from /usr/include/c++/9/memory:80, from A.hpp:2, from test.cpp:2: /usr/include/c++/9/bits/unique_ptr.h: In instantiation of ‘void std::default_delete<_Tp>::operator()(_Tp*) const [with _Tp = A::B]’: /usr/include/c++/9/bits/unique_ptr.h:292:17: required from ‘std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp = A::B; _Dp = std::default_delete<A::B>]’ A.hpp:11:28: required from here /usr/include/c++/9/bits/unique_ptr.h:79:16: error: invalid application of ‘sizeof’ to incomplete type ‘A::B’ 79 | static_assert(sizeof(_Tp)>0, | ^~~~~~~~~~~ I know what the constraints are when you intend to use unique_ptr as a part the PIMPL idiom and I tried to care about them. However, in this case, I have to admit that I'm out of idea (and hairs as it gets me on my nerves). Do I do something wrong, or are we just not censed to use unique_ptr in such a case ? Live demo
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() : m_b(nullptr) // initializer here { } https://wandbox.org/permlink/R6SXqov0nl7okAW0 Note that clangs error message is better at pointing at the line that causes the error: In file included from prog.cc:1: In file included from ./A.hpp:3: In file included from /opt/wandbox/clang-13.0.0/include/c++/v1/memory:682: In file included from /opt/wandbox/clang-13.0.0/include/c++/v1/__memory/shared_ptr.h:25: /opt/wandbox/clang-13.0.0/include/c++/v1/__memory/unique_ptr.h:53:19: error: invalid application of 'sizeof' to an incomplete type 'A::B' static_assert(sizeof(_Tp) > 0, ^~~~~~~~~~~ /opt/wandbox/clang-13.0.0/include/c++/v1/__memory/unique_ptr.h:318:7: note: in instantiation of member function 'std::default_delete<A::B>::operator()' requested here __ptr_.second()(__tmp); ^ /opt/wandbox/clang-13.0.0/include/c++/v1/__memory/unique_ptr.h:272:19: note: in instantiation of member function 'std::unique_ptr<A::B>::reset' requested here ~unique_ptr() { reset(); } ^ ./A.hpp:12:28: note: in instantiation of member function 'std::unique_ptr<A::B>::~unique_ptr' requested here std::unique_ptr<B> m_b = nullptr; ^ ./A.hpp:11:9: note: forward declaration of 'A::B' class B; ^ 1 error generated.
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 DrawCircle(SDL_Renderer* renderer, int x, int y, int radius) { int offsetx, offsety, d; offsetx = 0; offsety = radius; d = radius - 1; while (offsety >= offsetx) { SDL_RenderDrawPoint(renderer, x + offsetx, y + offsety); SDL_RenderDrawPoint(renderer, x + offsety, y + offsetx); SDL_RenderDrawPoint(renderer, x - offsetx, y + offsety); SDL_RenderDrawPoint(renderer, x - offsety, y + offsetx); SDL_RenderDrawPoint(renderer, x + offsetx, y - offsety); SDL_RenderDrawPoint(renderer, x + offsety, y - offsetx); SDL_RenderDrawPoint(renderer, x - offsetx, y - offsety); SDL_RenderDrawPoint(renderer, x - offsety, y - offsetx); if (d >= 2 * offsetx) { d -= 2 * offsetx + 1; offsetx += 1; } else if (d < 2 * (radius - offsety)) { d += 2 * offsety - 1; offsety -= 1; } else { d += 2 * (offsety - offsetx - 1); offsety -= 1; offsetx += 1; } } } //Main Loop int main(int argc, char** args) { //Initialize everything SDL_Init(SDL_INIT_EVERYTHING); //Setting up window and renderer SDL_Window* window = SDL_CreateWindow("Hmm", 200, 200, 800, 600, SDL_WINDOW_SHOWN); SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0); //Draw A Circle, Update the surface, and wait 10 seconds then close the program DrawCircle(renderer, 200, 200, 100); SDL_UpdateWindowSurface; SDL_Delay(10000); //Flushes memory and closes program/window SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 0; } (also feel free to give any recommendations or things that might speed it up)
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: SDL_Window *window; SDL_Renderer *renderer; SDL_Surface *image = IMG_Load("~/SDL2_Game/images/Green_Tile.png"); SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, image); }; RenderWindow.cpp #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <iostream> #include "RenderWindow.hpp" RenderWindow::RenderWindow(const char* p_title, int p_w, int p_h):window(NULL), renderer(NULL) { window = SDL_CreateWindow(p_title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, p_w, p_h, SDL_WINDOW_SHOWN); if (window == NULL) std::cout << "Window failed to init: " << SDL_GetError() << std::endl; renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED); } void RenderWindow::render(){ SDL_RenderClear(renderer); //SDL_Rect dstrect = { 5, 5, 320, 240 }; SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); } void RenderWindow::cleanUp(){ SDL_DestroyTexture(texture); SDL_FreeSurface(image); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); } main.cpp #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <iostream> #include "RenderWindow.hpp" int main(int argc, char** argv){ if (SDL_Init(SDL_INIT_VIDEO) != 0) { std::cout << "Problem with initialization. " << SDL_GetError() << std::endl; } else { std::cout << "Initialization success!" <<std::endl; } if (!IMG_Init(IMG_INIT_PNG)){ std::cout << "Problem with Image initialization " <<SDL_GetError() << std::endl; } RenderWindow win("RPG_Game_v_1.0", 800, 600); win.render(); bool gameRunning = true; SDL_Event event; while(gameRunning){ while(SDL_PollEvent(&event)){ if (event.type == SDL_QUIT) gameRunning = false; } } win.cleanUp(); IMG_Quit(); SDL_Quit(); return 0; } I'm on a Linux machine. I compile this with g++ -g -o game ./*.cpp -lSDL2main -lSDL2 -lSDL2_image Only a window is displaying. There is no image. I've tried refactoring my code with SDL_BlitSurface() and it does indeed display the PNG image. But why is this code not working? is it due to the fact that I'm using SDL_Texture* and my current system does not have a discrete graphics card?
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 the result of SDL functions != NULL and print SDL_GetError() to get more information about what went wrong.
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: 'Foo<> Foo' redeclared as different kind of entity 6 | struct Foo<> Foo; | ^~~ <source>:2:8: note: previous declaration 'template<bool x> struct Foo' 2 | struct Foo { | ^~~ Compiler returned: 1 // clang 13.0.1 <source>:6:14: error: redefinition of 'Foo' as different kind of symbol struct Foo<> Foo; ^ <source>:2:8: note: previous definition is here struct Foo { ^ 1 error generated. Compiler returned: 1 https://godbolt.org/z/s94n115fq
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. Except that a function template can be overloaded either by non-template functions (9.3.4.6) with the same name or by other function templates with the same name (13.10.4), a template name declared in namespace scope or in class scope shall be unique in that scope. So for example this declaration in main template<bool x = true> struct Foo { int func(int) const; }; int main() { struct Foo<> Foo; } will be correct. As for these declarations struct Foo { int func(int) const; }; struct Foo Foo; then the declaration of the variable Foo hides the name of the declared structure. In C structure tag names and variable names are in different name spaces. So to preserve the compatibility with C such declarations in C++ are allowed. To refer to the structure type after the variable declaration you need to use the elaborated name of the structure type.
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 the verticii will be white. Here is the relevant pieces of code: int triangleData[18] = { 2147483647,2147483647,2147483647,2147483647,//opaque white 0,100, //top 100,-100, //bottom right -100,-100 //bottom left }; unsigned int colorVAO, colorVBO; glGenVertexArrays(1, &colorVAO); glGenBuffers(1, &colorVBO); glBindVertexArray(colorVAO); glBindBuffer(GL_ARRAY_BUFFER, colorVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(triangleData), triangleData, GL_STATIC_DRAW); glVertexAttribPointer(0, 2, GL_INT, GL_FALSE, 2 * sizeof(int), (void*)(4*sizeof(int))); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 4, GL_INT, GL_TRUE, 0, (void*)0); glEnableVertexAttribArray(1); Vertex shader: #version 330 core layout (location = 0) in vec2 aPos; layout (location = 1) in vec4 aColor; out vec4 Color; uniform mat4 model; uniform mat4 view; uniform mat4 ortho; void main() { gl_Position = ortho * view * model * vec4(aPos, 1.0, 1.0); Color = aColor; } Fragment shader: #version 330 core out vec4 FragColor; in vec4 Color; void main() { FragColor = Color; }
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 that the data is packed one after the other in the buffer. If you want all the vertices to use the same data, you can either disable the attribute and use glVertexAttrib, or you can use the separate vertex format (available starting from OpenGL 4.3 or with ARB_vertex_attrib_binding) similar to: glBindVertexBuffer(index, buffer, offset, 0); where a stride of 0 really means no stride.
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(vertexCount + 1); // Calculate the angle we'll need to rotate by for each iteration (* (PI / 180) to convert it into radians) double segRotationAngle = (360.0 / vertexCount) * (3.14159265 / 180); // Here I set a center in the middle of the window as an example. The center point of the circle can be anywhere int centerX = WINDOW_WIDTH / 2; int centerY = WINDOW_HEIGHT / 2; // We need an initial vertex in the center as a point for all of the triangles we'll generate outCircleVertices[0].position.x = centerX; outCircleVertices[0].position.y = centerY; // Set the colour of the center point outCircleVertices[0].color.r = 255; outCircleVertices[0].color.g = 255; outCircleVertices[0].color.b = 255; outCircleVertices[0].color.a = 255; // Set the starting point for the initial generated vertex. We'll be rotating this point around the origin in the loop double startX = 0.0 - radius; double startY = 0.0; for (int i = 1; i < vertexCount + 1; i++) { // Calculate the angle to rotate the starting point around the origin double finalSegRotationAngle = (i * segRotationAngle); // Rotate the start point around the origin (0, 0) by the finalSegRotationAngle (see https://en.wikipedia.org/wiki/Rotation_(mathematics) section on two dimensional rotation) outCircleVertices[i].position.x = cos(finalSegRotationAngle) * startX - sin(finalSegRotationAngle) * startY; outCircleVertices[i].position.y = cos(finalSegRotationAngle) * startY + sin(finalSegRotationAngle) * startX; // Set the point relative to our defined center (in this case the center of the screen) outCircleVertices[i].position.x += centerX; outCircleVertices[i].position.y += centerY; // Set the colour for the vertex outCircleVertices[i].color.r = 255; outCircleVertices[i].color.g = 255; outCircleVertices[i].color.b = 255; outCircleVertices[i].color.a = 255; // Add centre point index outIndices.push_back(0); // Add generated point index outIndices.push_back(i); // Add next point index (with logic to wrap around when we reach the start) int index = (i + 1) % vertexCount; if (index == 0) { index = vertexCount; } outIndices.push_back(index); } } Each stage is commented up with an explanation to help with understanding. In my example here I have opted not to duplicate any vertices and instead use indices to describe to the drawing function how it should use each of the vertices to generate triangles. This is a common practice in graphics programming - you'd see this in OpenGL for example. To use this function simply add std::vector<SDL_Vertex> circleVertices; std::vector<int> indices; GenerateCircle(circleVertices, 20, 60, indices); in your initialisation and then add int rc = SDL_RenderGeometry(renderer, NULL, circleVertices.data(), circleVertices.size(), indices.data(), indices.size()); if (rc < 0) { std::cout << SDL_GetError(); } in your rendering loop between the SDL_RenderClear and SDL_RenderPresent calls. Note that you can change the vertexCount that you pass in to generate a circle with more or less triangles for a better or worse approximation. Please also note that if you use the function as is you'll be drawing a white circle, just in case you have a white background and wonder where it is!
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 golden.cpp brent.cpp test_optimization.cpp: In function ‘int main()’: test_optimization.cpp:13:3: error: ‘emsr’ has not been declared 13 | emsr::MinBracket<double> mb; | ^~~~ test_optimization.cpp:13:20: error: expected primary-expression before ‘double’ 13 | emsr::MinBracket<double> mb; | ^~~~~~ There could be several non-exclusive things going on from my not understanding modules at all to incomplete g++ implementation and on and on... Main tester (test_optimization.cpp): #include <cmath> import emsr.opt; int main() { emsr::MinBracket<double> mb; } Module interface (optimization.cpp): export module emsr.opt; export import :golden; export import :brent; One implementation module (golden.cpp): module; #include <cmath> #include <numbers> export module emsr.opt:golden; export import :structs; namespace emsr { template<typename Func, typename Real> void mean_bracket(Func func, MinBracket<Real>& mb) { } template<typename Func, typename Real> FuncPt<Real> golden(Func func, MinBracket<Real>& mb, Real tol) { return FuncPt<Real>(); } } // namespace emsr Another implementation module (brent.cpp): module; #include <cmath> #include <numbers> export module emsr.opt:brent; export import :structs; namespace emsr { template<typename Func, typename Real> FuncPt<Real> brent(Func func, Real ax, Real bx, Real cx, Real tol) { return FuncPt<Real>(); } template<typename Func, typename Deriv, typename Real> FuncPt<Real> brent_deriv(Func func, Deriv deriv, Real ax, Real bx, Real cx, Real tol) { return FuncPt<Real>(); } } // namespace emsr Structs module fragment (opt_structs.cpp): export module emsr.opt:structs; namespace emsr { template<typename Real> struct FuncPt { Real arg; Real val; FuncPt() = default; }; template<typename Real> struct MinBracket { FuncPt<Real> a; FuncPt<Real> b; FuncPt<Real> c; }; template<typename Real> struct DerivPt { Real arg; Real val; Real der; DerivPt() = default; }; }
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 may have multiple declarations, which the module machinery must merge—compiler resource usage can be affected by how you partition header files into header units. No new source file suffixes are required or supported. If you wish to use a non-standard suffix (see Overall Options), you also need to provide a -x c++ option too.2 According to this blog post, with gcc you need to compile headers separately from what I understand. They use iostream from the standard library as an example. While Clang comes with a mapping of standard headers to modules. Using GCC, we need to compile iostream manually. > g++ -std=c++20 -fmodules-ts -xc++-system-header iostream > g++ -std=c++20 -fmodules-ts hello_modular_world.cc It also looks like they use import <header>; syntax instead of include. > cat hello_modular_world.cc import <iostream>; int main() { std::cout << "Hello Modular World!\n"; } I'm not sure if this is acceptable but it works, this is what I did: I compiled the system headers: > g++-12 -std=c++20 -fmodules-ts -xc++-system-header cmath > g++-12 -std=c++20 -fmodules-ts -xc++-system-header numbers I changed the code like this: opt_structs.cpp export module emsr.opt:structs; export namespace emsr { template <typename Real> struct FuncPt { Real arg; Real val; FuncPt() = default; }; template <typename Real> struct MinBracket { FuncPt<Real> a; FuncPt<Real> b; FuncPt<Real> c; }; template <typename Real> struct DerivPt { Real arg; Real val; Real der; DerivPt() = default; }; } // namespace emsr golden.cpp module; import <cmath>; import <numbers>; export module emsr.opt:golden; export import :structs; export namespace emsr { template <typename Func, typename Real> void mean_bracket(Func func, MinBracket<Real> &mb) {} template <typename Func, typename Real> FuncPt<Real> golden(Func func, MinBracket<Real> &mb, Real tol) { return FuncPt<Real>(); } } // namespace emsr brent.cpp module; import <cmath>; import <numbers>; export module emsr.opt:brent; export import :structs; export namespace emsr { template <typename Func, typename Real> FuncPt<Real> brent(Func func, Real ax, Real bx, Real cx, Real tol) { return FuncPt<Real>(); } template <typename Func, typename Deriv, typename Real> FuncPt<Real> brent_deriv(Func func, Deriv deriv, Real ax, Real bx, Real cx, Real tol) { return FuncPt<Real>(); } } // namespace emsr optimization.cpp (the same) export module emsr.opt; export import :golden; export import :brent; test_optimization.cpp import <cmath>; import emsr.opt; int main() { emsr::MinBracket<double> mb; return 0; } All I did was change #includes to import <header>; and exported the namespace emsr. Then I compiled like this: > g++-12 -std=c++20 -fmodules-ts -g -c opt_structs.cpp > g++-12 -std=c++20 -fmodules-ts -g -c brent.cpp > g++-12 -std=c++20 -fmodules-ts -g -c golden.cpp > g++-12 -std=c++20 -fmodules-ts -g -c optimization.cpp > g++-12 -std=c++20 -fmodules-ts -g -c test_optimization.cpp > g++-12 -std=c++20 test_optimization.o opt_structs.o brent.o golden.o optimization.o -o test_optimization > ./test_optimization Note that I had to compile opt_structs.cpp first, then golden.cpp and brent.cpp, then optimization.cpp and then the main file. Again, I don't know if this is the best or right way, I'm still learning, but this is what I did trying to figure this out.
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 &operator << for each one of the vectors: constexpr sf::Vector3f cross(const sf::Vector3f &a, const sf::Vector3f &b) { return { a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; } std::ostream &operator <<(std::ostream &o, const sf::Vector3f &v) { return o << '{' << v.x << ", " << v.y << ", " << v.z << '}'; } // ... repeat for every 3D vector type Which implies lots of code repetition, so I changed the approach: template <typename vector3a_t, typename vector3b_t> constexpr vector3a_t cross(const vector3a_t &a, const vector3b_t &b) { return { a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; } Now the cross function two types which are expected to have members x, y and z but obvuiously this isn't aplicable to std::ostream &operator <<: template <typename vector3_t> std::ostream &operator <<(std::ostream &o, const vector3_t &v) { return o << '{' << v.x << ", " << v.y << ", " << v.z << '}'; } because the template type vector3_t shadows everything, so I was wondering if it is possible to constrain the function to accept any type that conforms the concept of "should look like a 3D vector": template <typename vector_t> concept vector3_c = requires(vector_t v) { // error: expected unqualified-id { std::is_scalar_v<decltype(v.x)> } -> true; { std::is_scalar_v<decltype(v.y)> } -> true; { std::is_scalar_v<decltype(v.z)> } -> true; }; template <vector3_c A, vector3_c B> constexpr decltype(A) cross(const A &a, const B &b) { return { a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; } template <vector3_c V> std::ostream &operator <<(std::ostream &o, const V &v) { return o << '{' << v.x << ", " << v.y << ", " << v.z << '}'; } But this doesn't even compile. It's my first time attempting concepts and I don't know if what I'm trying to do is even possible.
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 value, so -> true is not correct, it should be ->std::same_as<bool>. You should use nested requires to evaluate the value of the expression, for example template<typename vector_t> concept vector3_c = requires(vector_t v) { requires std::is_scalar_v<decltype(v.x)> && std::is_scalar_v<decltype(v.y)> && std::is_scalar_v<decltype(v.z)>; }; Demo If you just want to detect whether a struct has valid member variables, it is more intuitive to use a constraint expression of the form like {v.x} -> scalar template<typename T> concept scalar = std::is_scalar_v<T>; template<typename vector_t> concept vector3_c = requires(vector_t v) { { auto(v.x) } -> scalar; { auto(v.y) } -> scalar; { auto(v.z) } -> scalar; }; where auto(x) is the language supported decay-copy in C++23, which we can use to remove the reference of the member variable access. Demo
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 converting constructor of span would kick in due to the const char* constructor of std::string_view but it isn't. And neither is: std::span<std::string_view> cmdline_args_to_span(int argc, const char* argv[]) { auto c_args = std::span<const char*>(argv, argc); return std::span<std::string_view>(c_args); } Or: std::span<std::string_view> cmdline_args_to_span(int argc, const char* argv[]) { auto c_args = std::span<const char*>(argv, argc); return std::span<std::string_view>(c_args.begin(), c_args.end()); } All of these fail on both Clang and gcc (using the 'real' std::span but it's the same for my backported version). I must be doing something stupid, but I can't see what - can anyone help?
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::transform is and does. You cannot have a std::span<std::string_view> unless you have an array of std::string_view objects. And those objects won't be stored within the span. std::span<std::string_view> isn't very convenient for command line arguments. But, you could first create a std::vector<std::string_view> and then a span pointing to the vector. Since command line arguments are global, this is a rare case where a static storage doesn't suffer from significant problems - unless the caller mistakenly thinks that they can call it with varying arguments: std::span<std::string_view> cmdline_args_to_span(int argc, const char* argv[]) { static std::vector<std::string_view> args(argv, argv + argc); return args; } but I'm using C++17 with a backport of std::span - so I have spans but not ranges. Ranges can be had pre-C++20 even though the standard library doesn't have them. In fact, the standard ranges are based on a library that works in C++14. That said, in case you aren't interested in using any of the pre-existing range libraries, then implementing a transform view yourself involves quite a bit of boilerplate.
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 &a) { auto vec = vector<A>{a}; foo(vec); } int main() { A a; bar(a); cout << "Main size" << a.b->size() << endl; return 0; } This is the program's output: ~ ./a.out Foo size 1 [1] 107400 segmentation fault (core dumped) ./a.out Why does a.b->size() yield in a segfault, instead of asking the vector which contains 42 to report its size? Background: I have only very superficial knowledge of C++. Usually I program in Python but recently (some weeks ago) I started working on someone else's C++ code base and added some features to it.
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 main(), you will have to change bar() to pass a vector<A*> instead to foo(), eg: #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 &a) { auto vec = vector<A*>{&a}; foo(vec); } int main() { A a; bar(a); cout << "Main size" << a.b->size() << endl; return 0; }
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. I have no idea what is causing the problem. #include <iostream> #include <fstream> #include <list> #include <thread> #include <condition_variable> using namespace std; class Parent { public: Parent(); virtual ~Parent() = default; virtual void ShutDown() = 0; void Push(int aInt); virtual void Write(int aInt) = 0; bool IsEmpty() { return mList.empty(); } protected: std::list<int> Pop(); void WriteWithThread(); std::list<int> mList; std::thread mOutputThread; std::condition_variable mCV; std::mutex mMutex; std::atomic_bool mProgramRunning{ true }; std::atomic_bool mThreadRunning{ false }; }; Parent::Parent() { mOutputThread = std::move(std::thread(&Parent::WriteWithThread, this)); } void Parent::Push(int aInt) { std::unique_lock<std::mutex> lock(mMutex); mList.emplace_back(std::move(aInt)); lock.unlock(); mCV.notify_one(); } std::list<int> Parent::Pop() { std::unique_lock<std::mutex> lock(mMutex); mCV.wait(lock, [&] {return !mList.empty(); }); std::list<int> removed; removed.splice(removed.begin(), mList, mList.begin()); return removed; } void Parent::WriteWithThread() { mThreadRunning = true; while (mProgramRunning || !mList.empty()) { Write(Pop().front()); } mThreadRunning = false; } class ChildCout : public Parent { public: ChildCout() = default; void ShutDown() override; void Write(int aInt) override; }; void ChildCout::ShutDown() { mProgramRunning = false; if (mOutputThread.joinable()) { mOutputThread.join(); } std::cout << "Shutdown Complete"<< std::endl; } void ChildCout::Write(int aInt) { std::cout << "Inserting number: " << aInt << std::endl; } class ChildFile : public Parent { public: ChildFile(std::string aFile); void ShutDown() override; void Write(int aInt) override; private: std::fstream mFS; }; ChildFile::ChildFile(std::string aFile):Parent() { mFS.open(aFile); } void ChildFile::ShutDown() { mProgramRunning = false; if (mOutputThread.joinable()) { mOutputThread.join(); } mFS.close(); std::cout << "Shutdown Complete" << std::endl; } void ChildFile::Write(int aInt) { mFS<< "Inserting number: " << aInt << std::endl; } int main() { Parent *array[] = {new ChildFile("DriverOutput.txt"),new ChildFile("Output2.txt"), new ChildCout()}; for (int i = 0; i < 1000; i++) { for (auto& child : array) { child->Push(i); } } for (auto& child : array) { child->ShutDown(); } return 0; }
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 of the Pop and the WriteWithThread functions suboptimal, since the signatures force you to add unnecessary reads to mProgramRunning. ... std::list<int> Parent::Pop() { std::unique_lock<std::mutex> lock(mMutex); //mCV.wait(lock, [&] {return !mList.empty(); }); bool running = true; mCV.wait(lock, [this, &running] { // member variables accessed via this pointer -> capture this by value running = running = mProgramRunning.load(std::memory_order_acquire); return !running || !mList.empty(); // need to check for shutdown here too }); std::list<int> removed; if (running) { removed.splice(removed.begin(), mList, mList.begin()); } return removed; } void Parent::WriteWithThread() { mThreadRunning = true; while (mProgramRunning) { auto list = Pop(); if (list.empty()) { break; } Write(list.front()); } mThreadRunning = false; } ... void ChildCout::ShutDown() { mProgramRunning.store(false, std::memory_order_release); mCV.notify_all(); // tell consumer about termination if (mOutputThread.joinable()) { mOutputThread.join(); } std::cout << "Shutdown Complete" << std::endl; } ... void ChildFile::ShutDown() { mProgramRunning.store(false, std::memory_order_release); mCV.notify_all(); // tell consumer about termination if (mOutputThread.joinable()) { mOutputThread.join(); } mFS.close(); std::cout << "Shutdown Complete" << std::endl; } ... Note: I'm not 100% sure this does what exactly you expect it to do, but it should give you an idea what went wrong. A note on std::move: This is only useful to turn something not assignable to an rvalue reference into something that is assignable to an rvalue reference. In mOutputThread = std::move(std::thread(&Parent::WriteWithThread, this)); it's unnecessary to use std::move, since std::thread(&Parent::WriteWithThread, this) is an xvalue which is assignable to an rvalue reference, so mOutputThread = std::thread(&Parent::WriteWithThread, this); is sufficient. You'd need use std::move, if the thread object "had a name": std::thread tempThread(&Parent::WriteWithThread, this); mOutputThread = std::move(tempThread); Furthermore in mList.emplace_back(std::move(aInt)); it's not necessary to use std::move either, copy and move assignment for int have the same effect. Arithmetic types don't benefit from the use of std::move.
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/include/ia32intrin.h:288:10: Use of undeclared identifier '__builtin_ia32_crc32qi' /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/13.0.0/include/mmintrin.h:33:5: Use of undeclared identifier '__builtin_ia32_emms'; did you mean '__builtin_isless'? /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/13.0.0/include/hresetintrin.h:42:27: Invalid input constraint 'a' in asm Any help is much appreciated!
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.