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,740,385
71,741,933
why the jdk native refactor get class from heap
I am reading the jdk 19(support the m1 chip when compile) source code, in the refactor source code in reflection.cpp, the function look like this: oop Reflection::invoke_method(oop method_mirror, Handle receiver, objArrayHandle args, TRAPS) { oop mirror = java_lang_reflect_Method::clazz(method_mirror); int slot = java_lang_reflect_Method::slot(method_mirror); bool override = java_lang_reflect_Method::override(method_mirror) != 0; } when I tracing this clazz function java_lang_reflect_Method::clazz: oop java_lang_reflect_Method::clazz(oop reflect) { return reflect->obj_field(_clazz_offset); } the obj_field function get the oop data from heap. This makes me a little confusing, the heap store the all object instance, why the reflection get data from heap? I think it will get the metadata from Method Area because in there store the class metadata, using the metadata, could construct the class info. the obj_field look like this: inline oop oopDesc::obj_field(int offset) const { return HeapAccess<>::oop_load_at(as_oop(), offset); }
This reads the clazz field of a java.lang.reflect.Method object. java.lang.reflect.Method is a regular Java class (with some support from native helpers). Why do you expect it not to be stored on the heap? Note that java.lang.reflect.Method is not the same as a hotspot-internal C++ class Method. The class Method is an implementation detail of the hotspot JVM engine and instances of this internal C++ class are never stored on the heap.
71,740,495
71,740,796
Is implicitly deleted default constructor same as Compiler not synthesizing the default constructor
I am learning about class in C++. I came to know that in certain situations the default constructor can be implicitly deleted. Also, i read that when we have a user defined constructor then the compiler will not automatically synthesize the default constructor. To my current understanding, an implicitly deleted default constructor is quite different from the situation when the default constructor is not automatically synthesized. I mean in both cases we have the same effect, which is that we cannot create an object using default initialization. But still an implicitly deleted default constructor is not the same as compiler not synthesizing the default constructor. But then i came across this answer which says: when you explicitly declare any constructors, the default constructor is implicitly deleted. (end of quote) As i said, i don't think that when we have user defined constructors in our class then the default constructor is implicitly deleted. Instead the default constructor is not automatically synthesized by the compiler which is different(IMO) from being implicitly deleted. So the quoted answer seems technically wrong to me. And so the quoted answer should instead say that when we have user defined constructors then the compiler will not automatically synthesize the default ctor for us. But many people have upvoted(+marked it as correct) that answer so i may be missing something. Please correct me where i am wrong in my understanding of the topic and also tell me whether or not the quoted answer is technically correct. My point is that "having an implicitly deleted default ctor" and "the compiler not synthesizing a default ctor due to the presence of user defined constructor" are 2 different things.
This is covered in [class.default.ctor]: If there is no user-declared constructor for class X, a non-explicit constructor having no parameters is implicitly declared as defaulted ([dcl.fct.def]) So if there are user-declared constructors, there is no creation of an "implicitly declared" defaulted constructor. The broader question is this: why isn't an implicitly declared default constructor deleted instead of not added at all? Well, here's the definition of what a default constructor is: A default constructor for a class X is a constructor of class X for which each parameter that is not a function parameter pack has a default argument (including the case of a constructor with no parameters). Basically, a constructor is a default constructor if you can call it with no arguments. So it's not defined by a single signature; it's define by calling behavior. But a default constructor declaration is also a declaration of a user-declared constructor. So if you declare a default constructor, the compiler will not implicitly declare its own. Because otherwise you'd have two default constructors, which is... unhelpful when by definition they can both be called with no arguments (and therefore nothing to overload on) and one of them is deleted. So yes, it's incorrect to say that it is deleted if you provide a user-declared constructor.
71,740,678
71,741,078
CMake error in FindTerminfo with clang-15 on MacOS
I'm using llvm in my project and find it with cmake's find_package(LLVM REQUIRED CONFIG). Configuration fails with message: [cmake] CMake Error at /Applications/CMake.app/Contents/share/cmake-3.23/Modules/Internal/CheckSourceCompiles.cmake:44 (message): [cmake] check_source_compiles: C: needs to be enabled before use. [cmake] Call Stack (most recent call first): [cmake] /Applications/CMake.app/Contents/share/cmake-3.23/Modules/CheckCSourceCompiles.cmake:76 (cmake_check_source_compiles) [cmake] /usr/local/lib/cmake/llvm/FindTerminfo.cmake:21 (check_c_source_compiles) [cmake] /usr/local/lib/cmake/llvm/LLVMConfig.cmake:242 (find_package) [cmake] tools/driver/CMakeLists.txt:6 (find_package) [cmake] [cmake] [cmake] -- Could NOT find Terminfo (missing: Terminfo_LINKABLE) [cmake] -- Configuring incomplete, errors occurred! How to fix it?
It's actually a well-known issue in clang-14 and greater. Temporary solution is to use C language in your project. project(test LANGUAGES C CXX) # instead of project(test LANGUAGES CXX)
71,741,225
71,741,668
What is time complexity of the given code for sorting?
I thought about sorting using hash map, and the time complexity of insert operation is O(log(n)) so, I am wondering is it possible to sort using O(log(n)+n)? //sahil L. Totala #include <bits/stdc++.h> #include <iostream> using namespace std; int main () { cout << "how much no. do you want:"; int n; map < int, int > mp; cin >> n; for (int i = 0; i < n; i++) { int k = 0; cin >> k; mp.insert ({k, 1}); } for (auto itr = mp.begin (); itr != mp.end (); ++itr) { cout << itr->first << endl; } return 0; }
As it stands right now, the code is something like O(N log M), where N is the total number of input elements, and M is the number of unique elements. You're attempting to insert N elements into your map, but that attempt will only succeed for elements that weren't previously present. That means the map will only contain one node for each unique element in the input, so each insertion is the logarithm of the number of unique elements. That has a bit of a problem though: as it stands now, your code doesn't really work correctly. If the input contains duplicates, only unique numbers will be written out. For example, if you sort [1 1 1 1 2 2 1 2 1], the expected output would normally be [1 1 1 1 1 1 1 2 2 2], but your code will produce only [1 2]. It is possible to fix that while retaining approximately the current complexity. The obvious one would be to change mp.insert ({k, 1}); to ++mp[k]. Then you'd change your output loop to something like: for (auto itr = mp.begin (); itr != mp.end (); ++itr) { for (auto i = 0; i<itr->second; i++) cout << itr->first << '\n'; } Incrementing means we count the number of times each input value occurs. Then we write each of those values out as often as it occurred. At least in theory, this can save us a tiny bit on complexity if we expect the input to contain a lot of duplicates. As it stands right now, you're not really using the value you associate with each key, so you could use an std::set instead of an std::map. Another way to fix your code would be to use a std::multiset instead, but this would change the complexity from O(N log M) to O(N log N). As an aside, I'd advise avoiding std::endl. Just write out a new-line, as shown in the modified output loop. using namespace std; and #include <bits/stdc++.h> are best to avoid as well.
71,741,459
71,744,704
Can I create a c++ class instance and use it as an entity in Android JNI?
Let's say I create a class 'Car' in cpp. I want to creat an instance of that class with it's empty constructor in cpp. Can I do it and use it in java code on android? For instance: Java code Car myCar = new Car(); CPP class class Car{ std::string model; int creationYear; Car(){} } thanks for the help
Yes. You can easily have a native object that shadows a Java object - assuming you can call the C++ Car() constructor. You could use a public static method in the C++ Car class to do that. It's a bit of a hack, but a Java long is guaranteed to be 64 bits, so it's long enough to hold a native pointer value. In Java: public class Car { // A Java long is 64 bits, so it will // hold a native pointer private long nativeCar; private native long newNativeCar(); private native void deleteNativeCar( long car ); public Car() { this.nativeCar = newNativeCar(); } // allow for explicit native cleanup by caller public synchronized deleteCar() { if ( 0 != this.nativeCar ) { deleteNativeCar( nativeCar ); nativeCar = 0; } } // handle cases where the native cleanup code // was not called @Override protected void finalize() throws Throwable { deleteCar(); super.finalize(); } } Compile that, then use javah on the class file to create your C header file. (Note that JNI uses C, not C++. You can write C++ code to implement your logic, but the interface presented to the JVM must be a C interface.) You'll get a couple of functions in your native header, something like this (I've stripped off the annotation from javah - you will need to keep that...): jlong some_class_path_newNativeCar( JNIEnv *, jobject ); void some_class_path_deleteNativeCar( JNIEnv *, jobject, jlong ); You can implement your C++ code then: jlong some_class_path_newNativeCar( JNIEnv *env, jobject obj ) { Car *nativeCar = new Car(); // C cast - we're returning a C value return( ( jlong ) nativeCar ); } void some_class_path_deleteNativeCar( JNIEnv *env, jobject obj, jlong jNativeCar ) { Car *cppNativeCar = ( Car * ) jNativeCar; delete cppNativeCar; } I've deliberately kept the code simple - there's quite a bit I left out. javah can be a bit tricky to figure out how to use properly, for example. But if you can't figure out how to use javah properly you shouldn't be writing JNI code anyway. Because JNI code is fragile. You can't make any mistakes, or you will wind up getting seemingly random failures or having your JVM crash, and the crash will likely not be easily traced to the bad code that caused the problem. There are lots of rules for making JNI calls using the JNIEnv * pointer supplied to a native call. For example, in general you can't save the values passed to you by the JVM and use them outside of the context you received them in - using them in another thread, or after the function where they were passed to you returns is a great way to cause those JVM crashes I mentioned above. Nor can you make any JNI calls to Java if there are any exceptions pending from previous calls - again, you risk unpredictable errors and crashes if you do. So keep your native code simple. Keep all the logic and processing on only one side of the Java/native interface if you can. Pass only C or Java strings, primitives or primitive arrays across the Java/native interface if you can. Interacting with actual complex Java object from native code will take many, many lines of C or C++ code to safely replicate what can be done in Java with one or two lines of code. Even simple one-line get*()/set*() Java calls become 20 or 30 lines or more of C or C++ code if you replicate all the exception and failure checks you need in order to guarantee safe JVM execution after the native call no matter what data gets passed in. If you pass null to a Java method that can't handle a null value it will throw a NullPointerException that you can catch and your JVM runs happily or shuts down cleanly with an uncaught exception. Pass NULL to a JNI function that can't handle it, and if you don't properly check for any failure or any exception and then properly handle it, your JVM will exhibit seemingly unrelated failures or just crash.
71,741,517
71,741,645
How to grant friend class access to value of modified member
What is the proper method to grant class access to modified value of private member of different class. Using Friend Class is granting me access to value of private member if provided but won't let me access to modified value data of that member. For example when I am building vector in one Class and I would like to work on build up data of that vector in another class. How to grant access for bar_start.Print() have the same values as foo_start.PrintData() I believe its still in memory and it wasn't deleted class Foo { public: Foo(); ~Foo(); void ChangeData(); void PrintData(); private: int k = 0; std::vector<int> m_vector; friend class Bar; }; class Bar { public: Bar(); ~Bar(); void Print(); }; void Foo::ChangeData() { m_vector.push_back(1); int k = 5; } void Foo::PrintData() { std::cout << k << std::endl; std::cout << m_vector[0] << std::endl; } void Bar::Print() { Foo obj; std::cout << obj.k << std::endl; std::cout << obj.m_vector[0] << std::endl; } // printing in main() function Foo foo_start; Bar bar_start; foo_start.ChangeData(); foo_start.PrintData(); // k = 5, m_vector[0] = 1; bar_start.Print(); // k = 0, m_vector[0] empty and error due not existing element in vector
You may want to store a reference / pointer to a particular Foo inside each Bar instance. class Bar { public: Bar(Foo& f) : foo(&f) {} // take a Foo by reference and store a pointer to it void Print(); private: Foo* foo; }; void Bar::Print() { // use the pointer to the Foo in here: std::cout << foo->k << std::endl; std::cout << foo->m_vector[0] << std::endl; } You would then need to create each Bar supplying the Foo instance you'd like it to be connected to so to speak: int main() { Foo foo_start; Bar bar_start(foo_start); // this Bar now stores a pointer to foo_start foo_start.ChangeData(); bar_start.Print(); } Also note that the k you instantiate inside ChangeData is not the member variable k. You initialize a new variable named k with 5 and then that k is forgotten. void Foo::ChangeData() { m_vector.push_back(1); int k = 5; } If you want to make a change to the member variable k, remove the declaration part and just assign 5 to it: void Foo::ChangeData() { m_vector.push_back(1); k = 5; }
71,741,705
71,757,956
How to move the Gtk::Entry cursor?
I'm trying to make a custom Gtk::Entry widget (gtkmm4) that accepts only numbers and shows text as currency. Decimal and thousand separators are automatically added to the text. So I derived from Gtk::Entry and connected the signal_changed() with a member function that formats the input: class CurrencyEntry : public Gtk::Entry{ public: CurrencyEntry() { set_placeholder_text("0.00"); connectionChange = signal_changed().connect( sigc::mem_fun(*this, &CurrencyEntry::filterInput) ); } protected: sigc::connection connectionChange; Glib::ustring oldText; void filterInput(){ auto currentText = get_text(); /* format currentText */ connectionChange.block(); set_text(currentText); connectionChange.unblock(); /* move the cursor */ } }; The problem is: the user presses one key at time, but more than one symbol can be added to the text in specific cases. It seems that the default behavior of the cursor is to always move 1 place per key pressed, ignoring the extra symbols. This is the result (| is the cursor): Current Text Typed Key Result Desired Result | (empty) 1 0|.01 0.01| 123.45| 6 1,234.5|6 1,234.56| 98|0,123.45| 7 9,8|70,123.45 9,87|0,123.45 I need to move the cursor to the correct position. At first seemed trivial, but so far I have tried: Calling set_position(position) at the end of filterInput(). Calling gtk_editable_set_position( GTK_EDITABLE(this->gobj()), position) at the end of filterInput(). Overriding Entry::on_insert_text(const Glib::ustring& text, int* position) and change the value pointed by the position parameter. Calling Editable::on_insert_text(const Glib::ustring& text, int* position) directly at the end of filterInput(), passing a new position value. Nothing happens. All these commands seem to be ignored or ignore the position parameter. Am I doing something wrong or is this some kind of bug? How can I set the cursor position correctly in a Gtk::Entry widget?
The position seems not to be updated from the entry's handler. I tried other handlers (like insert_text) and the same issue arises. One way to solve this is to, from within you entry's handler, add a function to be executed in the idle loop. In that function, you can update the position. Here is the code: #include <algorithm> #include <iostream> #include <string> #include <gtkmm.h> class CurrencyEntry : public Gtk::Entry { public: CurrencyEntry() { m_connection = signal_changed().connect( [this]() { // Get the current edit box content: std::string str = get_text(); // Make it upper case: std::transform(str.begin(), str.end(), str.begin(), ::toupper); // Set the updated text. The connection is blocked to avoid // recursion: m_connection.block(); set_text(str); m_connection.unblock(); // Update the position in the idle loop: Glib::signal_idle().connect( [this]() { set_position(2); return false; }); }); } private: sigc::connection m_connection; }; class MainWindow : public Gtk::ApplicationWindow { public: MainWindow(); private: CurrencyEntry m_entry; }; MainWindow::MainWindow() { add(m_entry); } int main(int argc, char *argv[]) { auto app = Gtk::Application::create(argc, argv, "org.gtkmm.examples.base"); MainWindow window; window.show_all(); return app->run(window); } This is a simplified version of you case: all inserted text is transformed to upper case and, if possible, the cursor's position is set to 2. I think you can adapt to your use case from that.
71,741,742
71,746,258
Import C++ function in Python through ctypes: why segmentation fault?
I tried to call this C++ file (myfunc.cpp) from Python. I decided to use ctypes module, since it seems to work pretty well for both C and C++ code. I followed several tutorial (e.g., Modern/2020 way to call C++ code from Python), which suggests to add 'extern C' on the top of the C++ function to be called in Python. #include <iostream> #include <cmath> #include <vector> #include <cstdio> using namespace std; int from_xy(int x, int y, int nside) { return x + (nside * y); } std::vector<int> to_xy(int k, int nside) { int x = k%nside; int y = floor(k / nside); vector<int> res(x, y); return res; } int modNegOperator(int k, int n){ return ((k %= n) < 0) ? k+n : k; } extern "C" double** create2Darray(unsigned nside, double mx, double my) { int n_matrix = nside * nside; double **array2D = 0; array2D = new double *[n_matrix]; for (int h = 0; h < n_matrix; h++) { array2D[h] = new double[n_matrix]; for (int w = 0; w < n_matrix; w++) { // fill in some initial values // (filling in zeros would be more logic, but this is just for the example) array2D[h][w] = 0; } } for (int h = 0; h < n_matrix; h++){ std::vector<int> xy_vec = to_xy(h, nside); int modneg1 = modNegOperator(xy_vec[0] + 1,nside); int modneg2 = modNegOperator(xy_vec[0] - 1,nside); int modneg3 = modNegOperator(xy_vec[1] + 1,nside); int modneg4 = modNegOperator(xy_vec[1] - 1,nside); int pos1 = from_xy(modneg1, xy_vec[1], nside); int pos2 = from_xy(modneg2, xy_vec[1], nside); int pos3 = from_xy(xy_vec[0], modneg3, nside); int pos4 = from_xy(xy_vec[0], modneg4, nside); double half_mx = mx / 2; double half_my = my / 2; array2D[h][h] = 0; array2D[h][pos1] = half_mx; array2D[h][pos2] = half_mx; array2D[h][pos3] = half_my; array2D[h][pos4] = half_my; } return array2D; } I have then created a shared library: g++ -fPIC -shared -o libTest.so myfunc.cpp Created a myLib.py file including: import ctypes import sys import os dir_path = os.path.dirname(os.path.realpath(__file__)) handle = ctypes.CDLL(dir_path + "/libTest.so") handle.create2Darray.argtypes = [ctypes.c_int, ctypes.c_double, ctypes.c_double] def create2Darray(nside, mx, my): return handle.create2Darray(nside, mx, my) However, when I then try to run my function in python: from myLib import * create2Darray(4, 0.01,0.01) I get 'Segmentation fault'. Do you know what am I doing wrong? Do you have any suggestion? Or perhaps suggest another approach with which I can import my C++ function in python. The alternative ofcourse would be to re-write the code in C.
As mentioned in the chat we had, the code posted in the question segfaults because the following code returns a zero-length vector when first called: std::vector<int> to_xy(int k, int nside) { int x = k%nside; int y = floor(k / nside); vector<int> res(x, y); // if k==0, this is length 0 return res; } then this code faults here: for (int h = 0; h < n_matrix; h++){ std::vector<int> xy_vec = to_xy(h, nside); // length 0 int modneg1 = modNegOperator(xy_vec[0] + 1,nside); // xy_vec[0] faults. The code we discussed in chat didn't fail because: vector<int> res(x, y); // if k==0, this is length 0 had been changed to: vector<int> res{x, y}; // curly braces, length 2 After resolving that, the Python code just needed .restype defined, and technically c_uint for the first parameter: handle.create2Darray.argtypes = ctypes.c_uint, ctypes.c_double, ctypes.c_double handle.create2Darray.restype = ctypes.POINTER(ctypes.POINTER(ctypes.c_double)) Then the code would return the double** correctly.
71,741,978
71,742,253
Recursive iteration over type lists and concatenation into a result type list
Consider a scenario having various classes/structs, some having complex data members, which can contain more of them itself. In order to setup / initialize, a list of all dependencies is required before instantiantion. Because the types are known before instantiation, my approach is to define a type list containing involved/relevant types in each class/struct like this: template<typename...> struct type_list {}; struct a { using dependencies = type_list<>; }; struct b { using dependencies = type_list<>; }; struct c { using dependencies = type_list<b>; b b_; }; struct d { using dependencies = type_list<a>; a a_; }; struct e { using dependencies = type_list<c, a>; c c_; a a_; x x_; // excluded }; struct f { using dependencies = type_list<a,b>; a a_; b b_; y y_; // excluded }; For example I want to pre-initialize d, e, f. The next steps are: iterate through the dependencies of d,e,f and concat each item to a result list recursively iterate through each element of every dependencies[n]::dependencies and concat each item to a result list and do the same for each type until type list is empty The result may contain duplicates. These get reduced and sorted in a later step. I intend to do this using a constexpr hash map using hashes of __FUNCSIG__ / __PRETTY_FUNCTION__ (not part of this). How can this (iterating, accessing type list elements, concat into result list) be achieved using C++20 metaprogramming?
I'll just look at the metaprogramming part. As always, the solution is to use Boost.Mp11. In this case, it's one of the more involved algorithms: mp_iterate. This applies a function to a value until failure - that's how we can achieve recursion. We need several steps. First, a metafunction to get the dependencies for a single type template <typename T> using dependencies_of = typename T::dependencies; Then, we need a way to get all the dependencies for a list of types. Importantly, this needs to fail at some point (for mp_iterate's stopping condition), so we force a failure on an empty list: template <typename L> using list_dependencies_of = std::enable_if_t< not mp_empty<L>::value, mp_flatten<mp_transform<dependencies_of, L>>>; And then we can iterate using those pieces: template <typename L> using recursive_dependencies_of = mp_unique<mp_apply<mp_append, mp_iterate< L, mp_identity_t, list_dependencies_of >>>; The mp_append concatenates the list of lists that mp_iterate gives you, and then mp_unique on top of that since you don't want to have duplicates. This takes a list, so can be used like recursive_dependencies_of<mp_list<a>> (which is just mp_list<a>) or recursive_dependencies_of<mp_list<d, e, f>> (which is mp_list<d, e, f, a, c, b>). Demo.
71,742,203
71,760,027
Attempting to call Write() multiple times from separate thread(s) causes crash [gRPC] [C++]
I'm attempting to write an async streaming gRPC server (following this example) in C++ where multiple calls to Write are performed on a separate thread. Unfortunately, this causes a SIGSEGV on my system. The server is able to perform one write before it crashes. The below code provides a simple example of what I'm attempting to do. The overloaded call operator receives a message from a separate thread and executes the Write() call, writing MyMessage to the stream. void MyServer::HandleRpcs() { new CallData(&m_service, m_queue.get()); void* tag; bool ok; while (true) { GPR_ASSERT(m_queue->Next(&tag, &ok)); GPR_ASSERT(ok); static_cast<CallData*>(tag)->Proceed(); } } void MyServer::CallData::Proceed() { if (m_state == CREATE) { m_state = PROCESS; m_service->RequestRpc(&m_context, &m_request, &m_responder, m_queue, m_queue, this); } else if (m_state == PROCESS) { new CallData(m_service, m_queue); // Request the RPC here, which begins the message calls to the overloaded () operator } else { GPR_ASSERT(m_state == FINISH); delete this; } } void MyServer::CallData::operator()(Message message) { std::lock_guard<std::recursive_mutex> lock{m_serverMutex}; MyStream stream; stream.set_message(message.payload); m_responder.Write(stream, this); PushTaskToQueue(); } void MyServer::CallData::PushTaskToQueue() { // m_alarm is a member of CallData m_alarm.Set(m_queue, gpr_now(gpr_clock_type::GPR_CLOCK_REALTIME), this); }
Turns out I had a misunderstanding of gRPC and the completion queue. I was calling Write() before the completion queue returns the tag, which caused the crash. To resolve this, I created a static void* member variable in MyServer called m_tag and passed it into the Next function's tag parameter, like so: GPR_ASSERT(m_queue->Next(&m_tag, &ok)); Then, I checked if the tag matches up with the handler's this pointer in the overloaded call operator: if (m_tag != this) return; And I then saw my message stream come through.
71,742,508
71,743,033
GCC/Clang not optimising static global variable
GCC does not seem to be able to trace and optimize programs that read/write global variables in C/C++, even if they're static, which should allow it to guarantee that other compilation units won't change the variable. When compiling the code static int test = 0; int abc() { test++; if (test > 100) \ return 123; --test; return 1; } int main() { return abc(); } with the flags -Os (to produce shorter and more readable assembly) and -fwhole-program or -flto using GCC version 11.2 I would expect this to be optimized to return 1, or the following assembly: main: mov eax, 1 ret This is in fact what is produced if test is a local variable. However, the following is produced instead: main: mov eax, DWORD PTR test[rip] mov r8d, 1 inc eax cmp eax, 100 jle .L1 mov DWORD PTR test[rip], eax mov r8d, 123 .L1: mov eax, r8d ret Example: https://godbolt.org/z/xzrPjanjd This happens with both GGC and Clang, and every other compiler I tried. I would expect modern compilers to be able to trace the flow of the program and remove the check. Is there something I'm not considering that may allow something external to the program to affect the variable, or is this just not implemented in any compilers yet? Related: Why gcc isn't optimizing the global variable? but the answer given there mentions external functions and threads, neither of which apply here
I think you are asking a little bit too much for most of the compilers. While the compiler is probably allowed to optimize the static variable away according to the as-if rule in the standard, it is apparently not implemented in many compilers like you stated for GCC and Clang. Two reasons I could think of are: In your example obviously the link time optimization decided to inline the abc function, but did not optimize away the test variable. For that, an analysis of the read/write semantics of the test variable would be needed. This is very complex to do in a generic way. It might be possible in the simple case that you provided, but anything more complex would be really difficult. The use case of such optimizations is rare. Global variables are most often used to represent some shared global state. I makes no sense to optimize that away. The effort for implementing such a feature in a compiler/linker would be large compared to the benefit for most programs. Addition Apparently GCC optimizes away the variable if you read-only access it. If you compile the following: static int test = 0; int abc() { int test_ = test; test_++; if (test_ > 100) \ return 123; --test_; return 1; } int main() { return abc(); } Where you read the variable once into a local variable and never write to it, it gets optimized away to: main: mov eax, 1 ret (See here for a demo) However using such a local variable would defeat the whole point of having a global variable. If you never write to it, you might as well define a constant.
71,742,686
71,742,778
What is the correct way of declaring an iterator?
I am wondering if there is any difference between using std::set<int,std::greater<int>>::iterator itr; and std::set<int>::iterator itr; I tried the two of them in the code below and the result is the same, I would like know is there is any difference between one and the other or if there is any instance in which I should need to use one over the other (when using the STL library or another case). CODE: #include<iostream> #include<iterator> #include<set> int main(){ std::set<int,std::greater<int>> s1; s1.insert(40); s1.insert(30); s1.insert(60); s1.insert(20); s1.insert(50); s1.insert(10); // std::set<int>::iterator itr; std::set<int,std::greater<int>>::iterator itr; std::cout<<"\nThe set s1 is: \n"; for(itr=s1.begin();itr!=s1.end();itr++){ std::cout<<*itr<<" "; } std::cout<<"\n"; }
std::set<int>::iterator itr; is wrong. It happens to work on both GCC, Clang, and MSVC by default. But e.g. if I enable GCC's iterator debugging (-D_GLIBCXX_DEBUG), it stops compiling. Normally you don't need to manually spell the iterator type. You can do for (auto itr = s1.begin(); ...). Or, if the iterator needs to be created uninitialized, decltype(s1)::iterator itr;.
71,742,712
71,743,088
What would be the best approach to override cmath functions while still using them?
I'm trying to make my own math library with support for keeping stats on how many times each mathematical function in used. I would like all functions to have the same name as those in cmath so that I can easily just replace my math library header with cmath in my code and have it work the same way, just without the stats. So far I've tried this: my_math.hpp float tanf(float ang); my_math.cpp #include <cmath> float tanf(float ang) { std::cout << "Custom tanf() used..." << std::endl; return std::tan((float)(ang)); } Is this the best approach or is there a better one? I've tried to use return std::tanf(ang) but get the error that "tanf is not a member of std", even though I can use tanf in other parts of the code where I don't have my own tanf declared (I can never use std::tanf though). Is there a way to do this so that I can declare my own functions with the same name as the ones in cmath, add some functionality and then use the cmath version in the return?
To expand on my comment, and presuming this is part of some test-framework type thing, this could work how you want? // my_math.hpp namespace jesper { float tanf(float ang); /* more functions declarations */ } // my_math.cpp #include "my_math.hpp" float jesper::tanf(float ang) { /* function definition */ } /* more function definitions */ // my_test_code.cpp #include <cmath> #include "my_math.hpp" constexpr bool use_my_math = true; // switch this to change between std and jesper in helper functions float generic_tanf(float ang) { if constexpr (use_my_math) return jesper::tanf(ang); else return std::tanf(ang); } /* more helper functions */ int main() { generic_tanf(0.1f); } This style would switch all your functions at compile time, you could also use other methods for compile time checks and re-organise things nicely. Or you could do things at runtime with similar helper functions. You could perhaps also do something more akin to what I think you are asking for using horrible using namepsace std type stuff, but this is usually advised against for the reason you're wanting it, and it would most likely go badly. Name collision is not usually desirable!
71,744,379
71,744,690
What is wrong with this Coin Change solution using DFS with memoization?
I've solved Leetcode's Coin Change 2 problem with a DFS + memoization approach in Python, with the solution below # O(m*n) def change(amount: int, coins: List[int]) -> int: cache = {} def dfs(i, a): if a == amount: return 1 if a > amount: return 0 if i == len(coins): return 0 if (i, a) in cache: return cache[(i, a)] cache[(i, a)] = dfs(i, a + coins[i]) + dfs(i + 1, a) return cache[(i, a)] return dfs(0, 0) As a C++ newbie I've been practising my C++ by converting my Leetcode Python solution into a C++ one. This is what I've done: int dfs(int index, int a, int amount, vector<int> coins, vector<vector<int>>& dp) { if (a == amount) { return 1; } if (a > amount) { return 0; } if (index == coins.size()) { return 0; } if (dp[index][amount] != -1) { return dp[index][amount]; } dp[index][amount] = dfs(index, a + coins[index], amount, coins, dp) + dfs(index + 1, a, amount, coins, dp); return dp[index][amount]; } int change(int amount, vector<int>& coins) { int n = coins.size(); vector<vector<int>> dp(n,vector<int>(amount+1, -1)); return dfs(0, 0, amount, coins, dp); } I cannot for the life of me figure out why my C++ solution is not passing all the test cases like my Python solution did. I feel like my lack of knowledge on C++ is making it difficult for me to figure out why my C++ implementation is wrong. An example of a test case: 5 [1,2,5] should return 4.
Your memoization in the C++ solution looks at index and amount (a constant), when your Python one looks at index and a. Changing it accordingly fixes it, i.e [...] if (dp[index][a] != -1) { return dp[index][a]; } dp[index][a] = dfs(index, a + coins[index], amount, coins, dp) + dfs(index + 1, a, amount, coins, dp); return dp[index][a]; [...]
71,744,856
71,753,248
install_name_tool errors on arm64
I have c++ app that has multiple dependencies that takes the form of dynamic libraries. install_name_tool works fine to change the paths of those libraries in relation to the main executable, but the problem is that some of those libraries have dependencies themselves. For x64, running install_name_tool again on those dependencies works fine, but for arm64, it errors with ‘warning: changes being made to the file will invalidate the code signature’. Running ‘codesign -v /path/to/dylib’ returns ‘invalid signature (code or signature have been modified)’. Trying to run the executable crashes with a segfault. How can I fix this?
Figured it out! Since Big Sur, codesigning for arm64 is much more strict than it is for x64. So, I needed to run codesign --force -s - /path/to/dylib on every dylib
71,744,879
71,744,943
Fastest way to transfer/copy data from float* to vector<float>
I have a float* variable. I want to copy the value in the float* to the vector . Could you suggest the fastest way to do it on C++? This is my baseline code std::vector<float> CopyFloat2Vector(float* input, int size1) { std::vector<float> vector_out; for (int i = 0; i < size1; i++) { vector_out.push_back(input[size1 + i]); } return vector_out; } I also tried memcopy but it does not work float* input =....; //I have some value store in input with size of 1xsize1 std::vector<float> vector_out; memcpy(vector_out.data(), input, size1 * sizeof(float));
std::vector has a constructor for that. I would assume the standard library implementation will make use of as much optimization as it can in that: std::vector<float> CopyFloat2Vector(float* input, int size1) { return {input, input+size1}; }
71,744,958
71,745,139
How to return const& from std::visit?
I have encountered what i consider to be a strange situation with std::visit and overloaded which is giving me a compiler error. To illustrate what i am trying to do I have an example using std::visit 3 different ways. Approach 1, calling std::visit directly on a variant which returns a T const&, Approach 2, wrapping the std::visit code in a free function: T const& fn(variantT const&) Approach 3, wrapping the variant in a structure with an accessor T const& get_XXX() const My goal is to be able to wrap the std::visit part in a function because in my use case it's not a small piece of code. I have multiple lambda overloads. I don't want to have to duplicate this code in each function that uses the variant and wants to get a property, i want to write it once in some kind of wrapper which i can re-use across multiple translation units (Approach 3 is most preferable to me, then Apporach 2, and all else fails, I will investigate something less pleasing like a macro or something.) Can someone explain to me: Why / where std::visit is creating a temporary object? Is there something I can do differently to prevent this temporary from being created? Accepting that a temporary exists for some reason or other, why does the temporary object lifetime extension rule not apply here? Please consider this minimal example which reproduces the problem I am seeing. Minimal example: #include <iostream> #include <string> #include <variant> template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; struct a { std::string name; std::string const& get_name() const { return name; } }; struct b { std::string name; std::string const& get_name() const { return name; } }; std::string const& visit_get_name(std::variant<a, b> const& data) { return std::visit(overloaded{[](auto const& o){return o.get_name();}}, data); } struct wrapper { std::string const& get_name() const { return std::visit(overloaded{[](auto const& o){return o.get_name();}}, data); } std::variant<a, b> data; }; int main(int, char**) { std::variant<a, b> a_thing{a{"sue"}}; wrapper a_wrapper{a_thing}; std::cout << "Approach 1: " << std::visit(overloaded{[](auto const& o){return o.get_name();}}, a_thing); std::cout << "Approach 2: " << visit_get_name(a_thing); std::cout << "Approach 3: " << a_wrapper.get_name(); return 0; } Compiler: GCC 11.2.0 Compiler errors: example.cpp: In function 'const string& visit_get_name(const std::variant<a, b>&)': example.cpp:20:22: error: returning reference to temporary [-Werror=return-local-addr] 20 | return std::visit(overloaded{[](auto const& o){return o.get_name();}}, data); | ~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ example.cpp: In member function 'const string& wrapper::get_name() const': example.cpp:26:26: error: returning reference to temporary [-Werror=return-local-addr] 26 | return std::visit(overloaded{[](auto const& o){return o.get_name();}}, data); | ~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Compiler switches: -Wall -Wextra -Wshadow -Wnon-virtual-dtor -Wold-style-cast -Wcast-align -Wunused -Woverloaded-virtual -Wpedantic -Wconversion -Wsign-conversion -Wnull-dereference -Wdouble-promotion -Wformat=2 -Werror -Wmisleading-indentation -Wduplicated-cond -Wduplicated-branches -Wlogical-op -std=gnu++20
The default behavior when calling a lambda (or a function for that matter) is to have the value returned by copy. Since your lambda expressions that you pass to overloaded return by copy, binding a reference to that in the return type of visit_get_name (or wrapper::get_name) is not allowed, which is why Approach 2 and 3 fail. If you want to return by reference, you have to say so (note the explicit -> auto const & trailing return type for the lambda), like this: return std::visit(overloaded{[](auto const& o) -> auto const & { return o.get_name(); }}, data); (and the same thing for wrapper::get_name as well). This isn't needed for Approach 1, since you're not binding a reference to what's returned. demo.
71,745,234
71,755,027
How to detect which variable/code is creating a stack-based buffer overrun
I have an application that has started failing with 0xc0000409 - The system detected an overrun of a stack-based buffer in this application. This overrun could potentially allow a malicious user to gain control of this application. I have a full crash dump and source code, but this leads me to terminate() and abort() functions in the Windows API and I can't see any application-specific code stepping through the call stack. The user has indicated they get an Out of Memory error when launching the app UI (it can run on the command line or launch a UI). My question is, does the above exception indicate the application is trying to load too much data onto the stack and if it does is there any way to detect which variable and preferably which line of code causes the stack buffer overrun to occur? I am analysing the dump file using WinDbg and Visual Studio. The stack is below. WARNING: Stack unwind information not available. Following frames may be wrong. 00 0019d2f8 00868f91 MyApp+0x4ccf73 01 0019d308 7490e9a2 MyApp+0x468f91 02 0019d39c 7709d30e KERNELBASE!UnhandledExceptionFilter+0x172 03 0019ffdc 77061b34 ntdll!__RtlUserThreadStart+0x3b7d4 04 0019ffec 00000000 ntdll!_RtlUserThreadStart+0x1b
Activate Application Verifier for your application. It helps finding the problem more closely to the actual root cause. Then run it using a debugger. Fix your symbols Use a large CounterString (16 MB or so; funny generators here) and paste it into every textbox you have. This will probably overflow every unprotected buffer you have in your application. Wait for the application to throw an exception. It may not be the exact exception you're seeing, because Application Verifier may have introduced his own exceptions. Analyze the exception and look out for hints given by Application Verifier. It may give you helpful additional information which is only available because you activated Application Verifier. If needed, make use of the CounterString and find it in the memory (likely on the stack in your case)
71,745,650
71,745,711
VS Code :: C++ :: Error with giving inputs to the program
I have just setup the VS Code to run C++ using the YouTube video Now when I write a simple code #include <iostream> using namespace std; int main() { cout << "Enter your first name:"; cin << first_name; cout << "Your name is" + first_name; return 0; } I keep getting the error PS C:\Users\raman\OneDrive\Documents\C++_Projects> cd "c:\Users\raman\OneDrive\Documents\C++_Projects\" ; if ($?) { g++ Input.cpp -o Input } ; if ($?) { .\Input }Input.cpp: In function 'int main()': Input.cpp:8:18: error: 'first_name' was not declared in this scope 8 | cin << first_name;
Your code has two problems: First first_name is not declared cin uses >>, not << #include <iostream> using namespace std; int main() { string first_name; cout << "Enter your first name:"; cin >> first_name; cout << "Your name is" + first_name; return 0; }
71,745,708
71,745,726
What's the right grammar to use this member function?
My goal is knowing the name of this "Planner" by using function "getName()" getName() defined in Planner.cpp: const std::string& ompl::base::Planner::getName() const { return name_; } The way I called this function : void ompl::geometric::SimpleSetup::clear() { std::cout << base::Planner::getName() << std::endl; if (planner_) planner_->clear(); if (pdef_) pdef_->clearSolutionPaths(); } Error message I got : /home/ubuntuvb/ws_mvit/src/ompl/src/ompl/geometric/src/SimpleSetup.cpp: In member function ‘virtual void ompl::geometric::SimpleSetup::clear()’: /home/ubuntuvb/ws_mvit/src/ompl/src/ompl/geometric/src/SimpleSetup.cpp:87:41: error: cannot call member function ‘const string& ompl::base::Planner::getName() const’ without object std::cout << base::Planner::getName() << std::endl; ^ make[2]: *** [src/ompl/CMakeFiles/ompl.dir/geometric/src/SimpleSetup.cpp.o] Error 1 make[1]: *** [src/ompl/CMakeFiles/ompl.dir/all] Error 2 make: *** [all] Error 2 How should I call this function? Thank you
This is a non static method, so you have to call it with an object. For example, if planner_ is a pointer to an instance of a ompl::base::Planner class, then you can use planner_->getName(); or void ompl::geometric::SimpleSetup::clear() { if (planner_ != nullptr) { std::cout << planner_->getName() << std::endl; planner_->clear(); } if (pdef_ != nullptr) { pdef_->clearSolutionPaths(); } }
71,745,756
71,745,817
How to include Vcpkg on CMakeLists.txt?
So I have a project which depends on opencv, which is installed with vcpkg. The project is build with cmake. CMakeLists.txt cmake_minimum_required(VERSION 3.19.1) set(CMAKE_TOOLCHAIN_FILE ~/vcpkg/scripts/buildsystems/vcpkg.cmake) project(mylib) set (CMAKE_CXX_STANDARD 14) find_package(OpenCV REQUIRED) include_directories(~/vcpkg/installed/x64-osx/include) link_libraries(${OpenCV_LIBS}) set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS TRUE) add_library(mylib SHARED mylib another_lib) As can be seen, I'm trying to use the same CMakeLists.txt to build it on macOS and Windows. The link_libraries(${OpenCV_LIBS}) translates nicely between different OSs. But include_directories(~/vcpkg/installed/x64-osx/include) only works on macOS, on Windows it should refer to C:/vcpkg/installed/x64-windows/include instead. Is there any opecv/vcpkg I can use inlace of these?
This include_directories(~/vcpkg/installed/x64-osx/include) looks odd. This should be instead that: include_directories(${OpenCV_INCLUDE_DIRS})
71,746,147
71,747,242
How do I correctly pass converting constructor from an std::queue through to the underlying std::deque?
I have created a custom memory allocator. To use it with STL Containers, I've also created a wrapper so that it adheres to the std::allocator_traits requirements. #include <cstdint> #include <memory> #include <deque> #include <queue> class CustomAlloc { public: CustomAlloc(const std::size_t& maxMem) noexcept : m_maxMem(maxMem), m_usedMem(0) { } CustomAlloc(CustomAlloc&& other) noexcept : m_maxMem(other.m_maxMem), m_usedMem(other.m_usedMem) { } CustomAlloc& operator=(CustomAlloc&& other) noexcept { m_maxMem = other.m_maxMem; m_usedMem = other.m_usedMem; return *this; } CustomAlloc(const CustomAlloc&) = delete; CustomAlloc& operator=(CustomAlloc&) = delete; [[nodiscard]] void* Allocate(const std::size_t& size) { if(m_usedMem + size > m_maxMem) { throw std::bad_alloc(); } void* ptr = std::malloc(size); if(ptr == nullptr) { throw std::bad_alloc(); } m_usedMem += size; return ptr; } void Free(void* const ptr) const { return std::free(ptr); } const std::size_t& GetMaxMem() const noexcept { return m_maxMem; } private: std::size_t m_maxMem; std::size_t m_usedMem; }; template<typename T, typename Alloc> class STLAdaptor { public: typedef T value_type; STLAdaptor(Alloc& allocator) noexcept : m_allocator(allocator) { } template<typename U> STLAdaptor(const STLAdaptor<U, Alloc>& other) noexcept : m_allocator(other.m_allocator) {} [[nodiscard]] constexpr T* allocate(std::size_t n) { return reinterpret_cast<T*> (m_allocator.Allocate(n * sizeof(T))); } constexpr void deallocate(T* p, [[maybe_unused]] std::size_t n) { m_allocator.Free(p); } std::size_t MaxAllocationSize() const { return m_allocator.GetMaxMem(); } bool operator==(const STLAdaptor<T,Alloc>& rhs) { return m_allocator.GetStart() == rhs.m_allocator.GetStart(); } bool operator!=(const STLAdaptor<T,Alloc>& rhs) { return !(*this == rhs); } Alloc& m_allocator; }; template<typename T, typename Alloc> using CustomDeque = std::deque<T, STLAdaptor<T,Alloc>>; template<typename T, typename Alloc> using CustomQueue = std::queue<T, CustomDeque<T, Alloc>>; The issue I'm facing: int main() { CustomAlloc customAlloc(3000000); CustomDeque<int, CustomAlloc> customDeque(customAlloc); CustomQueue<int, CustomAlloc> customQueue(STLAdaptor<int, CustomAlloc>{customAlloc}); return 0; } This works perfectly fine, but it's code-gore to have to pass in the STLAdaptor<int, CustomAlloc>{customAlloc} where all other STL Containers can rely on the converting constructor for the STLAdaptor. What I'd like to do is: int main() { CustomAlloc customAlloc(3000000); CustomDeque<int, CustomAlloc> customDeque(customAlloc); CustomQueue<int, CustomAlloc> customQueue(customAlloc); return 0; } Where the customAlloc is somehow passed to the underlying std::deque.
If you can't change CustomAlloc code as Ted Lyngmo suggested, the alternative is to define CustomQueue as a subclass of std::queue: template<typename T, typename Alloc> struct CustomQueue : std::queue<T, CustomDeque<T, Alloc>> { CustomQueue(Alloc& alloc) :std::queue<T, CustomDeque<T, Alloc>>(STLAdaptor<T, Alloc>(alloc)) {} }; Now you can construct it by passing merely the allocator: int main() { CustomAlloc customAlloc(3000000); CustomDeque<int, CustomAlloc> customDeque(customAlloc); CustomQueue<int, CustomAlloc> customQueue(customAlloc); customQueue.push(5); return 0; } This code was tested on VS 2019.
71,746,951
71,747,083
Why is temporary Node necessary in Reversing a linked list in cpp?
Here is the working code: Node* Reverse(Node *head) { Node *prev = NULL; Node *next; Node *current = head; while (current != NULL) { next = current -> next; current -> next = prev; prev = current; current = next; } head = prev; return head; } And this doesn't work when I remove the temporary variable current. Node* Reverse(Node *head) { Node *prev = NULL; // Node *current = head; Node *next; while (head != NULL) { next = head -> next; head -> next = prev; prev = head; head = next; } return head; } I understand that we need next since we have to keep track of it before losing access to it. But I cannot think of why the temporary variable current is necessary? Any help would be appreciated.
You don't need the current variable. (despite it's name head would be confusing) The code is different because you don't assign prev to head in the second snippet. Node* Reverse(Node *head) { Node *prev = NULL; // Node *current = head; Node *next; while (head != NULL) { next = head -> next; head -> next = prev; prev = head; head = next; } // or head=prev; return head; return prev; // <--- }
71,747,171
71,747,414
Mouse right click option using eventFilter in Qt
I have QGraphicsView, which has many QGraphicsItem. I am trying to create a right click menu on these QGraphicsItem. Right click menu has multiple options. But only 1st option works. It means, if I click on 2nd option, it does not work. If I change the sequence ( means 1st one will go to 2nd position, and 2nd one will come to 1st position ) then still 2nd one will not work. bool myClass::eventFilter(QObject *watched, QEvent *event) { switch(event->type()) { case QEvent::ContextMenu: { foreach(QGraphicsItem* pItem, _scene->items()) { if(pItem->isUnderMouse()) { QMouseEvent *mouseEvent = static_cast<QMouseEvent*> (event); menu = new QMenu(this); myMenu = menu->addMenu("Copy"); myMenu ->addAction(Name); myMenu ->addAction(Address); if(Name == menu->exec(mouseEvent->globalPos())) { // logic } if(Address == menu->exec(mouseEvent->globalPos())) { // logic } } } } } Always works only 1st mouse right click option. Why is so ?
The usual way to do something like this is to override the QGraphicsItem::mouseReleaseEvent() or QGraphicsItem::mousePressEvent() function of your item class. This way, you won't have to do anything (no looping, etc...), it is already handled by the event loop. Here you can find a simple example: void MyItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) { if(event->button() == Qt::RightButton) { QMenu my_menu; // Build your QMenu the way you want my_menu.addAction(my_first_action); my_menu.addAction(my_second_action); //... my_menu.exec(event->globalPos()); } } From the Qt documentation: Note that all signals are emitted as usual. If you connect a QAction to a slot and call the menu's exec(), you get the result both via the signal-slot connection and in the return value of exec(). You just need to QObject::connect() the QActions you added to the context menu to the proper slots (here goes the "logic") and the job is done. If you prefer to check the returned value by yourself, you just have to get the returned QAction* once and for all (only one call to QMenu::exec()) and branch on it. For example: void MyItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) { if(event->button() == Qt::RightButton) { QMenu my_menu; // Build your QMenu the way you want my_menu.addAction(my_first_action); my_menu.addAction(my_second_action); //... QAction * triggered = my_menu.exec(event->globalPos()); if(triggered == my_first_action) { // Do something } else if(triggered == my_second_action) { // Do some other thing } //... } } I would personnally prefer to stick with the signal-slot connections instead that manually handling the returned value, especially since each QAction is most likely to be already connected to its corresponding slot.
71,747,705
71,748,706
glm::lookAt gives unexpected result for 2D axis
Basically I have a local space where y points down and x points right, like | | ---------> +x | | +y and the center is at (320, 240), so the upper left corner is (0,0). Some windowing system uses it. So I have this code auto const proj = glm::ortho(0.0f, 640.0f, 0.0f, 480.0f); auto const view = glm::lookAt( glm::vec3(320.0f, 240.0f, -1.0f), //eye position glm::vec3(320.0f, 240.0f, 0.0f), //center glm::vec3(0.0f, -1.0f, 0.0f) //up ); I imagine I need to look at the (320,240,0) from the negative position of z towards positive z, and the "up" direction is negative y. However it doesn't seems to provide the right result auto const v = glm::vec2(320.0f, 240.0f); auto const v2 = glm::vec2(0.0f, 0.0f); auto const v3 = glm::vec2(640.0f, 480.0f); auto const result = proj * view * glm::vec4(v, 0.0f, 1.0f); //expects: (0,0), gives (-1,-1) auto const result2 = proj * view * glm::vec4(v2, 0.0f, 1.0f); //expects: (-1,1), gives (-2,0) auto const result3 = proj * view * glm::vec4(v3, 0.0f, 1.0f); //expects: (1,-1), gives (0,-2)
That's not how view and projection work. The view matrix tells you which point should be mapped to [0,0] in view space. It seems you try to map the center of the visible area to [0,0], but then you use a projection matrix which assumes that [0,0] is the top-left corner. Since you first apply the view matrix, that gives a result of view * glm::vec4(v, 0.0f, 1.0f) = [0,0]. Then the projection matrix get's applied where you defined that 0,0 as the top-left corner, thus proj * [0,0] will result in [-1,-1]. I'm not 100% sure what you want to achieve, but if you want to use the given projection matrix, then the view matrix has to transform the scene in a way that the top-left point of the visible area get's mapped to [0,0]. You can also adjust the project to use the range [-320, 320] (and respectively [-240, 240]) and keep mapping the center to [0,0] with the view matrix.
71,747,942
71,748,834
DX12) Part of the Constants buffer is cut off
This is my Constant buffer for Object Drawing. actually, gWorld and gOldWorld have correct values, but gCubemapOn, gMotionBlurOn, gRimLightOn values are going wrong. gCubemapOn must be TRUE and it looks like, but actually that value is 65537. and gRimLightOn must be TRUE, but as you see, actual value is FALSE. The code below is how I use Constant Buffer. template<typename Cnst> class ConstantBuffer { public: ConstantBuffer(ID3D12Device* device, UINT count, bool isConstant=true) { if (isConstant) mByteSize = (sizeof(Cnst) + 255) & ~255; else mByteSize = sizeof(Cnst); ThrowIfFailed(device->CreateCommittedResource( &Extension::HeapProperties(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &Extension::BufferResourceDesc(D3D12_RESOURCE_DIMENSION_BUFFER, mByteSize * count), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&mUploadBuffer))); ThrowIfFailed(mUploadBuffer->Map(0, nullptr, (void**)(&mData))); } ConstantBuffer(const ConstantBuffer& rhs) = delete; ConstantBuffer& operator=(const ConstantBuffer& rhs) = delete; virtual ~ConstantBuffer() { if (mUploadBuffer) mUploadBuffer->Unmap(0, nullptr); mData = nullptr; } D3D12_GPU_VIRTUAL_ADDRESS GetGPUVirtualAddress(int idx) const { return mUploadBuffer->GetGPUVirtualAddress() + idx * mByteSize; } void CopyData(int index, const Cnst& data) { memcpy(&mData[index * mByteSize], &data, sizeof(Cnst)); } UINT GetByteSize() const { return mByteSize; } private: ComPtr<ID3D12Resource> mUploadBuffer = nullptr; BYTE* mData = nullptr; UINT mByteSize = 0; }; and this is how I Update Constant Buffer void Pipeline::UpdateConstants() { UINT matOffset = 0; for (int i = 0; i < mRenderObjects.size(); i++) { mObjectCB->CopyData(i, mRenderObjects[i]->GetObjectConstants()); mRenderObjects[i]->UpdateMatConstants(mMaterialCB.get(), matOffset); matOffset += mRenderObjects[i]->GetMeshCount(); } } ObjectConstants GameObject::GetObjectConstants() { ObjectConstants objCnst = {}; if (mReflected) { objCnst.World = Matrix4x4::Transpose(Matrix4x4::Multiply(mWorld, mReflectMatrix)); objCnst.oldWorld = Matrix4x4::Transpose(Matrix4x4::Multiply(mOldWorld, mReflectMatrix)); } else { objCnst.World = Matrix4x4::Transpose(mWorld); objCnst.oldWorld = Matrix4x4::Transpose(mOldWorld); } objCnst.cubemapOn = mCubemapOn; objCnst.motionBlurOn = mMotionBlurOn; objCnst.rimLightOn = mRimLightOn; return objCnst; } struct ObjectConstants { XMFLOAT4X4 World; XMFLOAT4X4 oldWorld; bool cubemapOn; bool motionBlurOn; bool rimLightOn; };
I believe this is the same problem as seen here. HLSL bool is 4 bytes and C++ bool is 1 byte. If you declare your CPU struct as struct ObjectConstants { XMFLOAT4X4 World; XMFLOAT4X4 oldWorld; int32_t cubemapOn; int32_t motionBlurOn; int32_t rimLightOn; }; it should work.
71,748,073
71,752,783
GL_SHADING_LANGUAGE_VERSION returns a single language
when using glGetString on the enum GL_SHADING_LANGUAGE_VERSION I get only one value for return, while I was expecting space separated values as with glGetString(GL_EXTENSIONS). what is even more confusing is that when I use glGetIntegerv(GL_NUM_SHADING_LANGUAGE_VERSIONS, *); I get a number bigger than one, and when I use glGetStringi(GL_SHADING_LANGUAGE_VERSION, i), and iterate over them I can get all the values. So, why don't I get all the values with glGetString(GL_SHADING_LANGUAGE_VERSION). I just get one value
It is this way because that's how the feature was originally defined. All GLSL versions are backwards compatible with prior ones, so the expectation was that if you had a 1.10 shader, you could feed it to any implementation that accepted 1.10 or higher. But with the break between core and compatibility, that become untenable. Making core implementations tacitly support GLSL shaders that included removed constructs made no sense. So there had to be a way for an implementation to specify exactly which GLSL versions it supported. But they couldn't change the existing version string's definition, so they (eventually) just added a new, indexed-based query.
71,748,115
71,748,351
Can Boost::asio::post can interrupt the running thread?
I am new to Boost::asio and I am currently looking at io_context. I have a question regarding the function io_context::post Posting on thread can preempt what's running on that thread currently ? because in the documentation i have seen : Deprecated: Use post.) Request the io_context to invoke the given handler and return immediately. I'm expecting that post will be added to the event queue, and will only be considered to run again when control is passed back to the event loop
No it cannot interrupt the running thread(s) associated with the io_context. post() enqueues the task to the io_context which will execute it eventually. The "return immediately" is meant in terms of the post() call itself, not the task. So the post() function returns immediately without blocking, but the task is scheduled for later execution.
71,748,795
71,753,236
building a nested JSON
Some data files that I need to read / parse have headers in the style: level0var = value0 level0var.level1field = value1 level0var.level1array[11].level2field = value2 ... In other words, they look like nested C-style structs and arrays, but none of these are declared in the header: I need to infer the structure as I read. My plan was to use the famous nlohmann::json library to store this, because its flexibility would allow me to change the structure of the data during parsing, and save the header in a more readable form. I read the assignments in as lhs = rhs, and both of those are strings. Given json header; to deal with the unknown, variable depth of the structures I want to do something like // std::string lhs = "level0var.level1field.level2field"; // std::string rhs = "value2"; auto current_level = header; while ( lhs != "" ) { auto between = lhs.substr ( 0, lhs.find_first_of ( "." ) ); lhs.erase ( 0, lhs.find_first_of ( "." ) + 1 ); if ( lhs == between ) break; current_level [ between ] = json ( {} ); current_level = current_level [ between ]; } current_level = rhs; std::cout << std::setw(4) << header; for every line that has at least 1 struct level (leaving the arrays for now). The strange thing is that using this loop, the only thing the last line returns is null, whereas when I use header [ "level0var" ] [ "level1field" ] [ "level2field" ] = rhs; std::cout << std::setw(4) << header; it gives the expected result: { "level0var": { "level1field": { "level2field": "value2" } } } Is there a way to build this hierarchical structure iteratively (without supplying it as a whole)? Once I know how to do structs, I hope the arrays will be easy! The example I made at work does not run on coliru (which does not have the JSON library I guess).
This is indeed trivial to do with the json_pointer, using the correct operator[] overload and the json_pointer::get_unchecked() function that already does all this work for you. The only effort is to convert your .-separated key into the /-separated path it expects. #include <nlohmann/json.hpp> #include <algorithm> #include <iostream> #include <string> using json = nlohmann::json; std::string dots_to_path(std::string key) { std::replace(key.begin(), key.end(), '.', '/'); key.insert(0, 1, '/'); return key; } int main() { json header; std::string lhs = "level0var.level1field.level2field"; std::string rhs = "value1"; json::json_pointer key{dots_to_path(lhs)}; header[key] = rhs; std::cout << std::setw(4) << header; } For future reference, the linked code was extended to transform keys including array indices, like level0var.level1field[1].level2field -> level0var/level1field/1/level2field. At this stage, it might be cleaner to tokenize the original string and simply append each token with json_pointer::operator/=, but since it's not in the original question scope I'll leave that as an exercise for the reader.
71,748,860
71,749,245
Make a curl request for xml_rpc c++ server
I am trying to make a curl request for a c++ xml-rpc server. After a bit of reading, I came to know the xml-rpc request using curl will look like this curl --connect-timeout 10 -d' <xml request> ' -H 'Content-type:text/xml' https://<Billing Core server>:<Port>/RPC2 In my case it will be curl --connect-timeout 10 -d' <xml request> ' -H 'Content-type:text/xml' https://127.0.0.1:40405/RPC2 I am not sure how to fill in <xml request> and xml_rpc c++ code looks like this class Data { public: Data(); ~Data(); std::string getTitle() const; void setTitle(std::string title); std::string getMessage(std::string name) const; private: std::string title; }; class SetTitle: public xmlrpc_c::method { public: SetTitle(Data* data); void execute(xmlrpc_c::paramList const& paramList, xmlrpc_c::value * const retvalP); private: SetTitle(); // Hereby disabled Data* data; }; void SetTitle::execute(xmlrpc_c::paramList const& paramList, xmlrpc_c::value * const retvalP) { string const title(paramList.getString(0)); paramList.verifyEnd(1); data->setTitle(title); *retvalP = xmlrpc_c::value_string(title); // XML-RPC void return values are an extension to the protocol and not always available or compatible between languages. } serviceRegistry.addMethod("set_title", new SetTitle(data)); How to create xml_request ? I would like to call set_tittle function. How to fill in Data information in xml_request set_title
I created a file name set_title.xml <?xml version="1.0" encoding="UTF-8"?> <methodCall> <methodName>set_title</methodName> <params> <param> <value> <string>BhanuKiran</string> </value> </param> </params> </methodCall> And made a curl request curl -H "Content-Type: text/xml" -d @set_title.xml -X POST http://127.0.0.1:40405/RPC2 -v Here are specs from http://xmlrpc.com/
71,748,924
71,754,560
How to count index of vectors in C++?
I have 5 int vectors v1 to v5. I want to count the index of the same vectors separately. If a different vector appears in the next vector, it outputs the index of the previous same vectors and starts counting for the new vector. Any help would be appreciated. std::vector<int>v1={1, 2, 3}; std::vector<int>v2={1, 2, 3}; std::vector<int>v3={1, 2, 3, 4}; std::vector<int>v4={1, 2, 3, 4}; std::vector<int>v5={1, 2, 3}; The output should be: vector value = vector of index {1,2,3} = {0,1}; {1,2,3,4} = {2,3}; {1,2,3} = {4};
You want to just search the collection of vectors and find in which positions are the elements that match your criterion? Then maybe like this: std::vector<int> v1={1, 2, 3}; std::vector<int> v2={1, 2, 3}; std::vector<int> v3={1, 2, 3, 4}; std::vector<int> v4={1, 2, 3, 4}; std::vector<int> v5={1, 2, 3}; std::vector<std::vector<int>> collection({v1, v2, v3, v4, v5}); auto found = std::find(collection.begin(), collection.end(), v1); while (found != collection.end()) { std::cout << "found at idx = " << std::distance(collection.begin(), found) << std::endl; // begin next search after previously found element found = std::find(++found, collection.end(), v1); } Can be also with custom predicate if you prefer.
71,748,947
71,758,962
Using Boost/odeint with class (calling integrate from outside the class with ODE-function inside the class)
I have written a lot of code that got VERY messy over the last couple of weeks/months and I wanted to clean up, by putting most of it into classes. However, I can't figure out, how to call an ODE-function, that is inside a class with Boost/integrate from outside the class. I'm not sure, if this is the cleanest/best practise, but I tried something like this: class ODEclass { public: // Lots of stuff here (initialization, methods, properties, parameters) void odefun(std::vector<double> x, std::vector<double>& dxdt, const double t) { // ... } } And then calling somewhere outside the class: integrate_adaptive(make_controlled<runge_kutta_cash_karp54<std::vector<double>>>(errTol[0], errTol[1]), odefun, Data, 0.0, something, something); With odefun as ODEclass::odefun, ODEinstance.odefun, ODEinstance->odefun and every other way I could think of, but nothing works. Putting a void odefun(...) outside the class works perfectly fine, but that would go against my current cleaning urge. I found answers here on Stackoverflow that would use std::bind, but those do odeint-calls form inside that class and don't seem to work in my case. So how can I pass an ODE-function to odeint that is inside a class? Or is there a better (clean) way to do this? I hope, I put all the necessary information in here. If something is missing, please let me know.
Calling a non-static member function requires an instance of the class. The simplest fix is to mark the odefun as static. This will work unless you wanted to access the internals. Assuming that the correct signature for odefun is actually void(std::vector<double>, std::vector<double>&, const double) or compatible: ODEclass instance; auto odefun = std::bind(&ODEclass::odefun, &instance, _1, _2, _3);
71,749,257
71,750,090
How to use a string entered in a txt file as an if condition
A function containing the function of a vector is included in a class called Vector. I will determine which function to use in the main function by the string entered in the txt file. class Vector { public: // private? double x, y, z; public: Vector() { x = 0; y = 0; z = 0; } Vector(int _x, int _y, int _z) { x = _x; y = _y; z = _z; } Vector Add(Vector v) { Vector output; output.x = x + v.x; output.y = y + v.y; output.z = z + v.z; return output; } double Dot(Vector v) { double output; output = (x * v.x) + (y * v.y) + (x * v.y); return output; } }; This is the main function. I want to use the string that I want to receive in the txt file, but it doesn't work well. A detailed example is below this code. int main() { FILE* fpInput; FILE* fpOutput; int vectorAx, vectorAy, vectorAz, vectorAdim; int vectorBx, vectorBy, vectorBz, vectorBdim; char VecFun[10]; fpInput = fopen("input.txt", "r"); fscanf(fpInput, "%d %d %d", &vectorAx, &vectorAy, &vectorAz); fscanf(fpInput, "%d %d %d", &vectorBx, &vectorBy, &vectorBz); fclose(fpInput); fpInput = fopen("input.txt", "r"); fgets(VecFun, sizeof(VecFun), fpInput); fclose(fpInput); Vector vectorA(vectorAx, vectorAy, vectorAz); Vector vectorB(vectorBx, vectorBy, vectorBz); if (VecFun == "Add") { Vector vectorO = vectorA.Add(vectorB); fpOutput = fopen("output.txt", "w"); fprintf(fpOutput, "%.f %.f %.f", vectorO.x, vectorO.y, vectorO.z); fclose(fpOutput); } else if (VecFun == "Dot") { fpOutput = fopen("output.txt", "w"); fprintf(fpOutput, "%.f", vectorA.DotProduct(vectorB)); fclose(fpOutput); } else { printf("Invalid input.. (%s)\n", VecFun); } return 0; } input.txt: Add 1 2 3 4 5 6 ouput.txt: 5 7 9 input.txt: Dot 1 2 3 4 5 6 ouput.txt: 32 However, the if condition did not work, so I tried debugging with: printf("Invalid input.. (%s)\n", VecFun); and found this result: Why are these results coming out? Also, how can I modify the if condition to work?
You can't compare C-style strings for equality using the == operator. In code like if (VecFun == "Add"), both the VecFun variable (the name of a char array) and the "Add" (a string literal) decay to pointers to their first elements; and, since they are different items in different memory locations, that test will always result in a false value. In C, you would need to use the strcmp function, as shown in the answer(s) to the question linked above. However, in C++ (since C++14), you can specify your literals as std::string objects, using the s suffix; then, tests like VecFun == "Add"s will work as expected.1 Here's a short demo: #include <iostream> #include <string> using namespace std::string_literals; int main() { char test[10] = "Add"; // Wrong - comparing two different pointers ... if (test == "Add") { std::cout << "Raw comparison succeeded!\n"; } else { std::cout << "Raw comparison failed!\n"; } // Plain "C" way, using the strcmp function ... if (strcmp(test, "Add") == 0) { std::cout << "strcmp comparison succeeded!\n"; } else { std::cout << "strcmp comparison failed!\n"; } // C++ way, using std::string literals ... if (test == "Add"s) { std::cout << "std::string comparison succeeded!\n"; } else { std::cout << "std::string comparison failed!\n"; } return 0; } 1 If your compiler doesn't support the C++14 Standard or string literal operators, you could construct a std::string object explicily from the literal(s), using expressions like std::string("Add") in place of the "Add"s.
71,749,389
71,749,579
c++ switch - not evaluating and showing "Condition is always true"
I was experimenting whether I can use "logical or" inside case clause for a switch statement. I tried this way for the first case and the system skipped it all together when I gave input as "A" or "a" in both the cases. # include <iostream> using namespace std; int main () { /* prg. checks if the input is an vowel */ char ch; cout << "please input a word to check if it is vowel or not" << endl; cin >> ch; switch (ch) { case ('A'|| 'a') : cout << "it is vowel" << endl; break; case 'E': cout << "it is vowel" << endl; break; case 'I': cout << "it is vowel" << endl; break; case 'O': cout << "it is vowel" << endl; break; case 'U': cout << "it is vowel" << endl; break; default: cout << "it is not a vowel" << endl; break; } is there a proper way to use or inside the case clause ? Thank you for the help.
The case ('A'|| 'a') should be written as: switch (ch) { case 'A': case 'a': cout << "it is vowel" << endl; break; // ... If it matches on 'A' it will fall through to the next case (unless there's a break in between). In this case, you may want to combine all vowles: switch (ch) { case 'A': case 'a': case 'E': case 'e': //... all of them ... std::cout << "it is vowel\n"; break; // ... Note that some compilers will issue a warning for fall through cases with statements in them (which is not the case above). Since C++17, if you use fall through cases, you can use the fallthrough attribute to silence such warnings where you actually want a fall through.
71,749,809
71,750,570
Switch QPoint to struct in mathematical expression
Don't understand how QPoint is being calculated here. QPoint has x and y. I've tried running this with a custom struct but I get errors such as Invalid operands to binary expression. Works: void test(QPoint p0, QPoint p1, QPoint p2, QPoint p3) { QPoint point; for(double t = 0.0; t<=1.0; t+=0.001){ point = pow((1-t),3) * p0 + 3 * pow((1-t),2) * t * p1 + 3 * (1-t) * pow(t,2) * p2 + pow(t,3) * p3; } } Doesn't work struct Point { int x; int y; }; void test(Point p0, Point p1, Point p2, Point p3) { Point point; for(double t = 0.0; t<=1.0; t+=0.001){ point = pow((1-t),3) * p0 + 3 * pow((1-t),2) * t * p1 + 3 * (1-t) * pow(t,2) * p2 + pow(t,3) * p3; } } Can I get this to work somehow using the Point structure instead of QPoint?
If you look at the Qt documentation about QPoint, you'll see that the operator*() and operator+() (that you use here) are overloaded for QPoint. If you want to make it work with your class, you will need to overload them as well. The minimum required overloads you need to make your test() function work are: Point operator*(double factor, const Point & p) { return Point{ static_cast<int>(std::round(p.x * factor)), static_cast<int>(std::round(p.y * factor)) }; } Point operator+(const Point & p1, const Point & p2) { return Point{p1.x + p2.x, p1.y + p2.y}; } For more consistency, you could add the symetric: Point operator*(const Point & p, double factor) { return factor * p; } Anyway, if you want to replace QPoint with Point with full arithmetic compatibility, I would recommend you to write all the overloads (for arithmetic comparison) listed in the documentation of QPoint.
71,751,299
71,751,420
Efficient sorting of multiple vectors with respect to one vector?
I have a 2D vector, S, and a 1D vector, I. Both S and I contain integers. Here is an example: vector<int> I={6,2,3,1,4,5,0}; vector<vector<int>> S; S[0]={0,1,3}; S[1]={1,2,4}; S[2]={4,5,6}; S[3]={0,3,5}; I contains numbers 0..n and vectors S are all subsets of I. I want to sort items in vectors S, with respect to the order of items in I. So that: S[0]={3,1,0}; S[1]={2,1,4}; S[2]={6,4,5}; S[3]={3,5,0}; My real vectors are large in size, so I need to do it in the most efficient way (in c++).
You can populate a map of weights used for the sorting and then provide a custom comparator for sort: #include <iostream> #include <vector> #include <algorithm> #include <unordered_map> int main() { std::vector<int> I={6,2,3,1,4,5,0}; std::unordered_map<int,unsigned> weights; for (unsigned i = 0; i < I.size(); ++i) weights[I[i]] = i; std::vector<int> s{3,6,5}; std::sort(s.begin(),s.end(), [&weights](int a,int b){ return weights[a] < weights[b]; }); for (const auto& e : s) std::cout << e << " "; } To sort many vectors you just need to call sort in a loop. If the numbers in I are always consecutive with no holes in between then using an array as look up table would be more efficient.
71,751,610
71,754,741
Ensure derived class implements static method while maintaining default move / move assign
I'd like to ensure some derived classes implement a static method and found this SO question: Ensure derived class implements static method The top answer uses CRTP to solve the issue with a static_assert in the base class destructor to ensure that the template argument type implements a static int foo(int). However, as noted by a comment on the answer "There is a slight issue with this answer: writing out a destructor has the consequence of disabling the generation of a move constructor and move assignment operator. It also prevents the object from being trivially_destructible. So, while it works, there are downsides to the approach (and such downsides apply to other special members)." – @Matthieu M Is there a way to avoid this downside? I've tried moving the static_assert to both a member function and static member function of Base, but in both cases it doesn't produce a compile-time error when a derived class doesn't implement static int foo(). Here's the code I've been working with (tweaked from the above SO thread): #include <type_traits> template <class T> class Base { public: //~Base() //This works as expected! Compile error because Bad doesn't implement static int foo() //{ // static_assert(std::is_same<decltype(T::foo()), int>::value, "ERROR: No 'static int foo()' member provided"); //} static void static_test() //This does not work. No compile time error. { static_assert(std::is_same<decltype(T::foo()), int>::value, "ERROR: No 'static int foo()' member provided"); } }; class Good : public Base<Good> { public: static int foo() { return 42; }; }; class Bad : public Base<Bad> { public: static double foo() { return 42; }; }; int main() { Good g; Bad b; }
What you have is a concept that the class needs to fulfil. You can simply check for it after the definition of the class, probably easiest with a static_assert: template<typename T> static constexpr bool assert_is_fooable() { static_assert(std::is_same<decltype(T::foo()), int>::value, "ERROR: No 'static int foo()' member provided"); static_assert(condition_2(), "ERROR: condition 2"); // More specific error messages given above, this is always // true so it can be used in a static_assert return true; } class Good { public: static int foo() { return 42; }; }; static_assert(assert_is_fooable<Good>()); And it even works if that class is unused anywhere else. You could also put the assert at the place where Good is used that expects it to have static int foo() instead. This allows the class to be trivially destructible and does not suppress the move constructor or move assignment operator, since it does not actually modify the class.
71,751,861
71,751,993
Deallocating std::list without going out of scope
In STL one of the ways to create a dynamically allocated array is to create a list. When lists go out of scope destructor for every element is called and the list is deleted. Is there a way to destroy list (and more importantly release the memory used) before list going out of scope, and if it's possible then what is the best way to do it? Will delete[] or list::clear() do the job?
In STL one of the ways to create a dynamically allocated array is to create a list. Linked lists and arrays are quite different data structures. Is there a way to destroy list (and more importantly release the memory used) before list going out of scope You can erase all elements of std::list, or any other standard container (excluding std::array) using the clear member function. All standard containers except for std::vector and std::basic_string release the memory allocated for elements when they are erased in practice. You may achieve the same with vector and string using shrink_to_fit after clearing. Alternatively, it may be a good idea to make the scope of the list smaller instead. Will delete[] ... do the job? No. delete[] may be used only with pointers to first element of array created using an allocating new-expression. std::list is not a pointer created using an allocating new-expression. You may not use delete[] on a std::list.
71,752,259
71,752,619
Purpose of explicitly deleting the default constructor
The codebase I’m working on was developed mostly pre-C++11. A lot of classes have a never-defined default constructor declared in the private section. I’m rather confident that in Modern C++, the Correct Way™ is to make them public and = delete them. I “upgraded” classes to this countless times by now and it never lead to problems. My question is rather: Why was that done at all? This answer said that a default constructor is only ever provided if there’s no constructor given by the user (I guess that’s not including = default) and there’s no hint that it doesn’t apply to pre-C++11. Of course, there is a non-trivial constructor in all of my classes I’m talking about. So, is there a rationale for it that I am missing?
Any function can be = deleted. A default constructor is a function, so it can be deleted. There's no need to make a language carveout for that. That some users choose to explicitly delete the default constructor (or the pre-C++ pseudo-equivalent of a private declaration with no definition) when it would not have been generated by the compiler is harmless. Indeed, it has some small benefits. If someone changes the class to remove its constructors, the class won't suddenly gain a default constructor. You don't have to remember what the rules are about when a default constructor is generated. For example: I guess that’s not including = default This proves my point, because you guessed wrong. Explicitly defaulted constructors do count as "user-provided", and thus they do suppress the creation of an implicit default constructor. Having to remember that is bothersome; it's clearer to just state it outright.
71,752,270
71,752,593
std::make_shared leads to undefined behavior, but new works
Consider the following example class: class Foo { public: void* const arr_; Foo() = delete; Foo(const size_t size, bool high_precision) : arr_(Initialize(size, high_precision)) {}; template <typename T> T* GetDataPointer() { return (T* const)arr_; } private: static void* Initialize(const size_t size, bool high_prec) { if (high_prec) { return new double[size]; } else { return new float[size]; } } }; When I created a shared pointer to a Foo object using std::make_shared, I often find the array data I initialize displays undefined behavior/becomes corrupted. For example: std::shared_ptr<Foo> sp_foo = std::make_shared<Foo>(Foo(3,false)); auto foo_data = sp_foo->GetDataPointer<float>(); foo_data[0] = 1.1; foo_data[1] = 2.2; foo_data[2] = 3.3; std::cout << "First Value: " << sp_foo->GetDataPointer<float>()[0]; // Sometimes this is 1.1, sometimes it is meaningless. However, when I initialize the shared pointer using new, this problem seems to go away. std::shared_ptr<Foo> sp_foo (new Foo(3,false)); auto foo_data = sp_foo->GetDataPointer<float>(); foo_data[0] = 1.1; foo_data[1] = 2.2; foo_data[2] = 3.3; std::cout << "First Value: " << sp_foo->GetDataPointer<float>()[0]; // Correctly prints 1.1 Any thoughts as to what is happening? Small side note: I am constrained to not template the Foo class and to indeed have a void* const to the onboard data array.
Your call to make_shared is using a copy constructor for your Foo class, which you haven't defined. Thus, the default (compiler-generated) copy will be used, and the destructor will be called to delete the temporary. As your class doesn't properly implement the Rule of Three, this (potentially) causes undefined behaviour. The copy constructor is being used because the argument list in your call to std::make_shared is Foo(3, false) – a Foo object, so the call fits only the first overload listed on this cppreference page. (Note that there is nothing resembling a std::make_shared<T>(const T& src) overload.) From that page, we see: Constructs an object of type T and wraps it in a std::shared_ptr using args as the parameter list for the constructor of T. So, with your "args" of Foo(3, false), that make_shared actually calls the following constructor for the object to wrap: Foo(Foo(3, false)) For correct behaviour, just pass the 3 and false as arguments to make_shared: std::shared_ptr<Foo> sp_foo = std::make_shared<Foo>(3, false); You can demonstrate the error in your original code by adding a destructor to the Foo class that logs some output, like: ~Foo() { std::cout << "Destroying...\n"; }. You will see that output after execution of the call to make_shared. You can prevent this accidental error/oversight by deleting the Foo copy constructor: Foo(const Foo& f) = delete;. This will generate a compiler error along the following lines: error : call to deleted constructor of 'Foo' However, in your second case, you use a std::shared_ptr constructor (the third form shown on the linked page). This has no problem, because that constructor 'just' wraps the given pointer into the managed object, and no copying or destruction is needed.
71,753,355
71,756,155
Virtual function with non-shared method
I'm on a personal project and I need to do something unusual. My code is kinda long but the problem comes from the structure so I'll use a very simplified version of the problem. I have two classes (A and B), with B derived from A. B uses every attributes and methods of A, including one which creates a modified clone of the instance of the class. The problem is that I need to be able to use a method of B after cloning (moo in this case) that doesn't exists in A. I tried to make my methods virtual but it doesn't fix the problem. Is there any way to do this without CRTP ? I really don't want to use CRTP because it would be really complicated. (In my real code I have a chain of 4 class inheritances, and all 4 are already templated) #include <iostream> class A { public: /*Common function*/ virtual void foo(){ std::cout << "call from A" << std::endl; } A* clone(){ /* ... ... Code I don't want to write again for B ... */ return this; } }; class B: public A { public: /*Common function*/ virtual void foo(){ std::cout << "call from B" << std::endl; } /*Not derived from A*/ void moo(){ //Doesn't work even with virtual keyword std::cout << "only exist in B" << std::endl; } }; int main(int argc, char const *argv[]) { auto tB = new B(); tB->foo(); tB->moo(); tB->clone()->foo(); tB->clone()->moo(); return 0; } Compilator: error: 'class A' has no member named 'moo'; did you mean 'foo'? 38 | tB->clone()->moo(); | ^~~ | foo I'm not English so sorry if it's unclear.
Well, according to the comments, my research and how I think c++ works, I give up finding something that looks like virtual methods and still be satisfying. So I resolved to use the CRTP, for those who are interested here's the code of my model of a 3 (I deleted one) inherited class CRTP with an additional type template argument :) #include <iostream> //CRTPI = "CRTP Interface", used for inheritances between CRTPs template<typename Derived, typename T> class CRTPI_A { protected: T x = 0; public: T getX(){ return x; } Derived* clone(){ /* ... ... Code I don't want to write again for B and it's childs ... */ return new Derived(); } }; template<typename Derived, typename T> class CRTPI_B: public CRTPI_A<Derived, T> { public: //Only for B and its childs void iwd(){ std::cout << "Hi, i'm a B child !" << std::endl; } }; template<typename Derived, typename T> class CRTPI_C: public CRTPI_B<Derived, T>{}; template<typename T> class A: public CRTPI_A<A<T>, T> { public: A(){}; A(T z){ this->x = z; } void foo(){ std::cout << "call from A" << std::endl; } }; template<typename T> class B: public CRTPI_B<B<T>, T> { public: B(){}; B(T z){ this->x = z; } void foo(){ std::cout << "call from B" << std::endl; } //Not in CRTP interface so won't be inherited by C void UwU(){ std::cout << "I'm exclusive to B" << std::endl; } }; template<typename T> class C: public CRTPI_C<C<T>, T> { public: C(){}; C(T z){ this->x = z; }; void foo(){ std::cout << "call from C" << std::endl; } }; int main(int argc, char const *argv[]) { auto tA = new A<char>('A'); auto tB = new B<int>(2); auto tC = new C<float>(420.69); tA->foo(); tA->clone()->foo(); printf("\n"); tB->foo(); tB->iwd(); tB->clone()->foo(); tB->clone()->iwd(); tB->UwU(); printf("\n"); tC->foo(); tC->iwd(); // tC->UwU(); //Won't work but that's planned std::cout << "\n" << tA->getX() << ":" << tB->getX() <<":" << tC->getX() << std::endl; return 0; } Note that, here, the CRTP interface for C is optional because it has no child class and no exclusive methods, so we can just write: template<typename T> class C: CRTPI_B<C<T>, T> { ... }
71,753,426
71,808,652
Need help expanding particle system spread / divergence from 2 to 3 dimensions
I need help. I've been struggling with this for a week now and getting nowhere. I am building a 3D particle system mainly for learning and I am currently working on particle spread / divergence. In specific, introducing random direction to the particle direction so as to create something that looks more like a fountain as opposed to a solid stream. I have been successful in getting this to work in one axis but no matter what I do, I cannot get it to work in 3 dimensions. Here is what I am doing: // Compute a random angle between -180 to +180 for velocity angle x, y and z. spreadAmount is a float from 0.0 to 1.0 to control degree of spread. float velangrndx = spreadAmount * ((((double)(rand() % RAND_MAX) / (RAND_MAX)) - 0.5) * 360.0 * 3.14159265359 / 180.0); float velangrndy = spreadAmount * ((((double)(rand() % RAND_MAX) / (RAND_MAX)) - 0.5) * 360.0 * 3.14159265359 / 180.0); float velangrndz = spreadAmount * ((((double)(rand() % RAND_MAX) / (RAND_MAX)) - 0.5) * 360.0 * 3.14159265359 / 180.0); // Compute Angles float vsin_anglex_dir = -PF_SIN(velangrndx); float vcos_anglex_dir = -PF_COS(velangrndx); float vsin_angley_dir = -PF_SIN(velangrndy); float vcos_angley_dir = -PF_COS(velangrndy); float vsin_anglez_dir = -PF_SIN(velangrndz); float vcos_anglez_dir = -PF_COS(velangrndz); // Assign initial velocity to velocity x, y, z. vel is a float ranging from 0.0 - 0.1 specified by user. velx, vely, and velz are also floats. velx = vel; vely = vel; velz = vel; And finally, we get to the particle spread / divergence function below. If I use only the first X axis (comment out the Y and Z) it works as it should (see images), but if I use the Y and Z axis, it works totally incorrectly. px0, py0, and pz0 are temporary float variables so as to preserve the velocity variables. // X Divergence px0 = (velx * vsin_anglex_dir); py0 = (velx * vcos_anglex_dir); pz0 = velz; velx = px0; vely = py0; velz = pz0; // Y Divergence py0 = (vely * vsin_angley_dir); pz0 = (vely * vcos_angley_dir); px0 = velx; velx = px0; vely = py0; velz = pz0; // Z Divergence pz0 = (velz * vsin_anglez_dir); px0 = (velz * vcos_anglez_dir); py0 = vely; velx = px0; vely = py0; velz = pz0; The velx, vely, and velz are then used to calculate for particle screen position. This is what the particle spread looks like at 25%, 75% and 100% for the X axis only (if I comment out the Y and Z code). This works as it should and in theory, if the rest of my code was working correctly, I should get this same result for the Y and Z axis. But I don't. I could really use some help here. Any suggestions on what I am doing wrong and how to correctly expand the currently working spread function from 2 dimensions to 3? Thanks, -Richard
Likely it is because the values of velx, vely and velz are getting overwritten on subsequent calculations. See whether the below works the way you are expecting. // X Divergence float velxXD = (velx * vsin_anglex_dir); float velyXD = (velx * vcos_anglex_dir); float velzXD = velz; // Y Divergence float velxYD = velx; float velyYD = (vely * vsin_angley_dir); float velzYD = (vely * vcos_angley_dir); // Z Divergence float velxZD = (velz * vcos_anglez_dir); float velyZD = vely; float velzZD = (velz * vsin_anglez_dir); velx=velxXD+velxYD+velxZD; vely=velyXD+velyYD+velyZD; velz=velzXD+velzYD+velzZD;
71,753,517
71,857,528
How to include flex ops to the tensorflow lite for microcontrollers interpreter?
Good afternoon, I am trying to implement a transformer network onto a DE10-nano board (2xCortex-A9, armv7-a), using tensorflow lite for microcontrollers (TFLM). I trained the network using python and converted it to .tflite format. When doing so, I get a warning : "TFLite interpreter needs to link Flex delegate in order to run the model since it contains the following Select TFop(s): Flex ops: FlexEinsum" And when I deploy the model on the board using an AllOpsResolver I get the error: Failed to get registration from op code CUSTOM When I inspect the operations that my network uses, flexEinsum is indeed part of the list: === TFLite ModelAnalyzer === Subgraph#0 main(T#0, T#1) -> [T#79] Op#0 CAST(T#1) -> [T#21] Op#1 GATHER(T#9, T#21) -> [T#22] Op#2 MUL(T#22, T#18) -> [T#23] Op#3 FlexEinsum(T#23, T#5) -> [T#24] Op#4 ADD(T#24, T#3) -> [T#25] Op#5 FlexEinsum(T#23, T#4) -> [T#26] Op#6 ADD(T#26, T#3) -> [T#27] Op#7 MUL(T#27, T#11) -> [T#28] Op#8 FlexEinsum(T#25, T#28) -> [T#29] Op#9 SOFTMAX(T#29) -> [T#30] Op#10 FlexEinsum(T#23, T#2) -> [T#31] Op#11 ADD(T#31, T#3) -> [T#32] Op#12 FlexEinsum(T#30, T#32) -> [T#33] Op#13 FlexEinsum(T#33, T#6) -> [T#34] Op#14 ADD(T#34, T#7) -> [T#35] ... **From my understanding, some operations are not yet supported by TFLM and I would need to directly use the einsum implemented in TF. My question is: how do I do that ? ** From the error sent by tensorflow when converting the model, I would need to 'link the flex delegate' but I don't understand what this means... To give more context, I am using the Altera baremetal GCC toolchain on DS-5 to compile and deploy on the board. To include TFLM in my project, I generated the 'hello world' project and then used the generated 'tensorflow' and 'third_party' folders as a library in my project This works very well until flex ops show up... Does anybody have solutions or ideas about this problem? Have a great day!
Flex delegates are not available in TFLM: https://groups.google.com/a/tensorflow.org/g/micro/c/b4v-84f8J5Q. The thing to do is to modify the network to avoid using it. Also, some ops are not compatible between TFLM and TFLite, follow this guide if you're in the case: https://github.com/tensorflow/tflite-micro/blob/main/tensorflow/lite/micro/docs/porting_reference_ops.md
71,754,010
71,754,097
Why does the base constructor get called instead of the one with parameters (virtual inheritance)?
#include <iostream> using namespace std; class Point { int x,y; public: Point() { x=0; y=0; } Point(int x, int y) { this->x=x; this->y=y; } Point(Point &p) { x=p.x; y=p.x; } friend class Square; }; class Square { Point _point; int side; public: Square() {cout<<"Square.\n";} Square(Point &p, int side_val): _point(p), side(side_val) { cout<<"Square constructor that should be used.\n"; } }; class Rectangle: public virtual Square { int side2; public: Rectangle() {} Rectangle(Point &p, int side_1, int side_2): Square(p,side_1), side2(side_2) {} }; class Rhombus: public virtual Square { Point opposite_point; public: Rhombus() {cout<<"Rhombus. \n";} Rhombus(Point &p, Point &q, int side_1): Square(p, side_1), opposite_point(q) { cout<<"Rhombus constructor that should be used \n"; } }; class Paralellogram: public Rectangle, public Rhombus { public: Paralellogram(Point &p, Point &q, int side_1, int side_2): Rhombus(p,q,side_1),Rectangle(p,side_1,side_2) { cout<<"Parallelogram constructor that should be used\n"; } }; int main() { Point down_left(3,5); Point up_right(2,6); int side_1=5; int side_2=7; Paralellogram par(down_left,up_right,side_1,side_2); } The output I get is: Square Rhombus constructor that should be used Paralellogram constructor that should be used And what I'm trying to do is instantiate a Paralellogram that has combined variables from a Rhombus and a Rectangle (it should have a _point, opposite_point, side, side2) and I don't want them to double up hence I'm using virtual inheritance. But the constructor of Square that I intended should be used never gets called, even once, instead the base constructor gets called. What should I do? Give up on the virtual inheritance?
In virtual inheritance, virtual base is constructed according to the most derived class. class Paralellogram: public Rectangle, public Rhombus { public: Paralellogram(Point &p, Point &q, int side_1, int side_2) : Square(), // You have implicitly that Rectangle(p,side_1,side_2), Rhombus(p,q,side_1) { cout<<"Parallelogram constructor that should be used\n"; } }; You probably want class Paralellogram: public Rectangle, public Rhombus { public: Paralellogram(Point &p, Point &q, int side_1, int side_2) : Square(p, side_1), Rectangle(p,side_1,side_2), Rhombus(p,q,side_1) { cout<<"Parallelogram constructor that should be used\n"; } };
71,754,032
71,777,388
Is It Possible To Use Reflection To Pass A COM Object From C# to C++?
I have a C# assembly that does some work and sends the results of the work back to a C++ core. I am trying to use Reflection to pass it back since the C# assembly runs on a different thread than the one it was initialized by from the C++ core. I have tried using the COM interface as the parameter type. IDL: HRESULT SendEvent([in] IEventData *pEventData); C#: WECOInspectionCoreIDL.IEventData eventData = new EventData() as WECOInspectionCoreIDL.IEventData; var parameters = new object[1]; parameters[0] = eventData; _piInspectionCore.GetType().InvokeMember("SendEvent", BindingFlags.InvokeMethod, null, _piInspectionCore, parameters); This gets the error "0x80020005 Type mismatch" in the atlcom.h hRes = m_pInfo->Invoke(...) call which apparently eventually gets converted to "Unable to cast COM object of type 'System.__ComObject' ... No such interface supported. I've also tried making the parameter an IDispatch* and then the call goes through to C++, but it doesn't seem to be the real object. IDL: HRESULT SendEvent([in] IDispatch *pEventData); C++: STDMETHODIMP CInspectionCore::SendEvent(IDispatch *pEventData) { IEventData *pIEventData = (IEventData *)pEventData; Even calling pIEventData->GetIDsOfNames() fails. Is there a way to pass a COM object created in C# to C++ when the C# object is called from a different C++ thread?
With COM, you should never cast a COM interface into another COM interface like this: STDMETHODIMP CInspectionCore::SendEvent(IDispatch *pEventData) { IEventData *pIEventData = (IEventData *)pEventData; // wrong! } Instead you must use QueryInterface, this works fine: STDMETHODIMP CInspectionCore::SendEvent(IDispatch *pEventData) { IEventData* pIEventData; HRESULT hr = pEventData->QueryInterface(&pIEventData); if (FAILED(hr)) // etc. } In some cases (in fact often), raw casting may work which can give the false impression that it's ok. In your case, it doesn't work because you use different threads which creates implicit proxies (COM apartments, etc.). You can see that if you breakpoint in SendEvent have a look at the call stack when it's called, it's all COM marshaling stuff.
71,754,165
71,754,799
Why are unqualified names from nondependent base classes favored over template parameters
The C++ standard says that unqualified names from nondependent base classes are preferred over template parameters. What is the reasoning behind this? The following snippet is from C++ Templates: #include <iostream> template <typename X> class Base { public: int basefield; using T = int; }; class D1 : public Base<Base<void>> { public: void f() { basefield = 3; // works as normal } }; template <typename T> class D2 : public Base<double> { public: void f() { basefield = 7; } T strange; // what type am I ??? }; int main() { D2<std::string> d; d.strange = 100; }
Unqualified lookup is approximately equivalent to trying a qualified lookup in each containing scope and keeping the first hit. Since D2<…>::T can find Base<double>::T, it is the lookup in the class’s scope that succeeds; that lookup naturally precedes that for the template parameters that are introduced lexically outside the class. This preference also avoids having an unqualified name change meaning between template<class T> struct A : B { Z z; void f(); // … }; and template<class Z> void A<Z>::f() { Z z; // … } although the same change is still possible for namespace-scope names. That said, even the committee has been divided on this particular rule because it is weird to prefer a name you can’t see in a base class over one you can see in the template-head.
71,754,645
71,754,919
C++ killing child thread stops execution of the main thread
I am completely confused with timers and how threads (pthread) work in C++ Timers arent timers but clocks and you cant (I at least cant) kill a thread without killing main thread. What I need - a bit of code which executes once in 24hrs on a separate thread. However if the app needs to stop it - I cant do anything but send SIGKILL to it (because join will wait till midnight). Once I kill that thread the app (main thread) seems to kill itself also. I am open to suggestions. On condition - I cannot use std::threads and I dont want to wake this thread more than once a day But easiest for me would be to kill a child thread without stopping execution of the main thread (why this is the case anyway??) Here is the sample: #include <stdlib.h> #include <string.h> #include <iostream> #include <stdio.h> #include <unistd.h> #include <thread> #include <pthread.h> #include <signal.h> using namespace std; void* Logger(void* arg) { int* thread_state = (int*)arg; cout << "Logger started" << endl; sleep(24 * 60 * 60); cout << "Logger thread exiting" << endl; pthread_exit(0); } int main() { int thread_state = 0; pthread_t logger_t; int rc = pthread_create(&logger_t, NULL, Logger, (void*)&thread_state); sleep(2); //thread_state = 1; pthread_kill(logger_t, SIGKILL); cout << "i wuz here" << endl; return 0; } output: Logger started Killed
I dont know how I missed it but if I call pthread_cancel instead of pthread_kill it works just fine.
71,754,789
71,754,952
Erase row from 2D vector where element appears?
I want to delete evry row in a 2d vector, where an element x appears in row for example : x = 2 vec= {{1,2,4,5},{3,7,9},{2,5,7},{1,6,10}} result vec= {{3,7,9},{1,6,10}} I try this #include <iostream> #include <vector> #include <algorithm> void Delete(std::vector<std::vector<int> > &v, int x) { v.erase(std::remove_if(v.begin(), v.end(), [](const std::vector<int>& v) {int i=0; return v.size() > 1 && v[i] == x; }), v.end()); } int main() { int x = 1; std::vector<std::vector<int>> test = {{1,144,64,62,64,1132}, {1,144,4,62,3,40}, {1,20,64,67,64,1122}, {2,128,1,64}}; Delete(test, x); for (auto& v : test) { std::cout << "{"; for (auto& v2 : v) std::cout << v2 << " "; std::cout << "}\n"; } }
One of many errors is the comparing only first elements of the subvectors. You wish v.erase(std::remove_if(v.begin(), v.end(), [x](const std::vector<int>& v) { return std::find(v.begin(), v.end(), x) != v.end(); }), v.end());
71,755,034
71,755,308
C++ use sort function on a struct type of array
#include<bits/stdc++.h> using namespace std; ifstream f ("date.in"); ofstream g ("date.out"); int v[10001],maxi,i,maxi1,n,k,mini=INT_MAX,j; struct interval { int stg,dr; } x,a[10001]; int main() { f>>n; for(i=1;i<=n;i++) { f>>x.stg>>x.dr; a[i].stg=x.stg; a[i].dr=x.dr; v[x.stg]++; v[x.dr]-=1; if(maxi<x.dr) maxi=x.dr; } for(i=1;i<=maxi;i++) v[i]+=v[i-1]; for(i=1;i<=maxi;i++) { if(v[i]>maxi1) maxi1=v[i]; } g<<maxi1<<'\n'; for(i=1;i<=n;i++) for(j=1;j<=n;j++) if(a[i].stg<a[j].stg) { swap(a[i].stg,a[j].stg); swap(a[i].dr,a[j].dr); } for(i=1;i<=n;i++) for(j=i;j<=n;j++) if(a[i].dr<a[j].stg) { k++; g<<a[i].stg<<" "<<a[i].dr; g<<'\n'; i=j; } if(a[n].stg>a[k].dr) { g<<a[n].stg<<" "<<a[n].dr; g<<'\n'; k++; } g<<k; } So my program works fine, but I want to optimize it. I want to use the sort function (not qsort) instead of the bubble sort, like this sort(a+1,a+n+1, comp), but I don't know how to write the comp function for this scenario. Your help would be very much appreciated.
The solution was not that hard: bool cmp( interval a, interval b ) { return (a.stg < b.stg && a.dr < b.dr); }
71,755,049
71,755,228
conditional type define in c++?
I need to define a template class A, which has a nested type according to nested type in template argument. Like this: template<typename Container> class A { public: using NestedType = if (Container has nested type Container::NestedTypeA) { Container::NestedTypeA; } else if (Container has nested type Container::NestedTypeB) { Container::NestedTypeB; } else { Container::NestedTypeC; } }; How to implement this using declaration? Or is there another way to acheive the same effect? Thanks the answers by 康桓瑋 and Jarod42. But the two answers both use C++20's concepts. How about use C++17 at most?
In C++20, you can just use concepts template<typename Container> struct B { }; template<typename Container> requires requires { typename Container::NestedTypeA; } struct B<Container> { using NestedType = typename Container::NestedTypeA; }; template<typename Container> requires requires { typename Container::NestedTypeB; } && (!requires { typename Container::NestedTypeA; }) struct B<Container> { using NestedType = typename Container::NestedTypeB; }; template<typename Container> requires requires { typename Container::NestedTypeC; } && (!requires { typename Container::NestedTypeA; }) && (!requires { typename Container::NestedTypeB; }) struct B<Container> { using NestedType = typename Container::NestedTypeC; }; template<typename Container> class A : public B<Container> {}; Demo In C++17, you can use std::void_t to detect the validity of member types. #include <type_traits> template<typename Container, typename = void> constexpr bool HasNestedTypeA = false; template<typename Container> constexpr bool HasNestedTypeA< Container, std::void_t<typename Container::NestedTypeA>> = true; template<typename Container, typename = void> constexpr bool HasNestedTypeB = false; template<typename Container> constexpr bool HasNestedTypeB< Container, std::void_t<typename Container::NestedTypeB>> = true; template<typename Container, typename = void> constexpr bool HasNestedTypeC = false; template<typename Container> constexpr bool HasNestedTypeC< Container, std::void_t<typename Container::NestedTypeC>> = true; template< typename Container, bool = HasNestedTypeA<Container>, bool = HasNestedTypeB<Container>, bool = HasNestedTypeC<Container>> struct B { }; template<typename Container> struct B<Container, false, false, false> {}; template<typename Container, bool B1, bool B2> struct B<Container, true, B1, B2> { using NestedType = typename Container::NestedTypeA; }; template<typename Container, bool B1> struct B<Container, false, true, B1> { using NestedType = typename Container::NestedTypeB; }; template<typename Container> struct B<Container, false, false, true> { using NestedType = typename Container::NestedTypeC; }; template<typename Container> class A : public B<Container> {}; Demo
71,755,420
71,755,637
GCC mod() definition
I was making faster mod(x,2) function in C++ with GCC (compiled using -O3 -ffast-math) and bumped to difference in results between GCC and Octave: float fast_fmod2(float x){ // over 50x faster than std::fmod(x, 2.0f) x *= 0.5f; return 2.0f * ( x - std::floor(x)); } Result (mod(input,2.0f)): Input : -7.8539786 std::fmod() : -1.853978633881 Octave mod(): 0.146021366119 fast_fmod2 : 0.146021366119 ... Input : 7.8539805 std::fmod() : 1.853980541229 Octave mod(): 1.853980541229 fast_fmod2 : 1.853980541229 I checked couple other math software as well and it looks like at least Sollya and Wolfram|Alpha supports Octave results and before mentioned documented same definition for the function as Octave did. GCC defines mod function as: mod(A, P) = A - (int(A/P) * P) Sollya and Octave defines as: mod(a, b) = a - (b * floor(a / b)) Because of int(a/b) rounds differently compared to floor(a/b), GCC definition gives different answer for negative A's. >> int16(-2.19/2) ans = -1 >> floor(-2.19/2) ans = -2 Is it a bug in GCC version or something else behind the difference?
I'm assuming you mean std:fmod instead of std::mod (there's no std::mod in the official c++ standard) The reason for this difference is that std::fmod doesn't do what you think it does. std::fmod calculates the remainder and not the arithmetic modulus. Computes the floating-point remainder of the division operation x/y If you want the arithmetic modulus you need to use std::remainder instead: Computes the IEEE remainder of the floating point division operation x/y . The IEEE floating-point remainder of the division operation x/y calculated by this function is exactly the value x - n*y, where the value n is the integral value nearest the exact value x/y. When |n-x/y| = ½, the value n is chosen to be even. This will produce the expected result in your example: std::cout << std::remainder(-7.8539786f, 2.0f) << std::endl; // 0.146021 godbolt example So to answer your question: This is not a bug, this is intended behaviour. The functions are just named differently in C++ (albeit with a slighly confusing naming scheme) Octave mod == C++ std::reminder Octave rem == C++ std::fmod
71,755,425
71,756,215
Last notify_all isn't triggering last conditional_variable.wait
What I'm Trying To Do Hi, I have two types of threads the main one and the workers where the workers are equal to the number of cores on the CPU, what I'm trying to do is when the main thread needs to call an update I set a boolean called Updating to true and call condition_variable(cv).notify_all then each thread will do its work and when done it will increment by one an atomic_int called CoresCompleted followed by a cv.notify_all so that the main thread can check if all the work is done then it will wait for the variable Updating to be false so it is sure that all other threads finished and it doesn't update again, once everything is done the main thread sets updating to false and notifies all. CODE Main void UpdateManager::Update() { //Prepare Update CoresCompleted = 0; Updating = true; //Notify Update Started cv.notify_all(); //Wait for Update to end auto Pre = high_resolution_clock::now(); cv.wait(lk, [] { return (int)UpdateManager::CoresCompleted >= (int)UpdateManager::ProcessorCount; }); auto Now = high_resolution_clock::now(); auto UpdateTime = duration_cast<nanoseconds>(Now - Pre); //End Update and nofity threads Updating = false; cv.notify_all(); } Workers void CoreGroup::Work() { Working = true; unique_lock<mutex> lk(UpdateManager::m); while (Working) { //Wait For Update To Start UpdateManager::cv.wait(lk, []{ return UpdateManager::Updating; }); if (!Working) return; //Do Work size_t Size = Groups.size(); auto Pre = high_resolution_clock::now(); for (size_t Index = 0; Index < Size; Index++) Groups[Index]->Update(); auto Now = high_resolution_clock::now(); UpdateTime = duration_cast<nanoseconds>(Now - Pre); //Increment CoresCompleted And Notify All UpdateManager::CoresCompleted++; UpdateManager::cv.notify_all(); //Wait For Update To End UpdateManager::cv.wait(lk, []{ return !UpdateManager::Updating; }); } } Problem Once the workers reach the last wait where they wait for Updating to be false they get stuck and never leave, for some reason the last notify_all in the main thread is not reaching the workers, I tried searching and looked for many examples but I can't figure out why it isn't triggering, maybe I miss understood how the cv and lock works, any ideas why this is happening and how to fix?
Here is how your code works: some waiting in Update is over when notified: cv.wait(lk, [] { return (int)UpdateManager::CoresCompleted >= (int)UpdateManager::ProcessorCount; }); It goes out of waiting and requires the lock on the mutex. Proceed to do its stuff then reaches the end and notifies the other thread that they can continue working with this line: cv.notify_all(); But it lies, they can't continue working because you hold the lock. Release it and they will proceed working: void UpdateManager::Update() { <...> //End Update and nofity threads Updating = false; lk.unlock(); cv.notify_all(); } That probably isn't the only issue in this code but I assume that you lock the mutex before entering the Update method or have some guarantee that it runs before the other one (Work).
71,755,482
71,755,570
How do I assign to a const variable using an out parameter in C++?
In a class header file Texture.h I declare a static const int. static const int MAX_TEXTURE_SLOTS; In Texture.cpp I define the variable as 0. const int Texture::MAX_TEXTURE_SLOTS = 0; Now in Window.cpp class's constructor I attempt to assign to the variable using an out parameter, however this obviously does not compile as &Texture::MAX_TEXTURE_SLOTS points to a const int* and not an int* . glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &Texture::MAX_TEXTURE_SLOTS); I have tried using const_cast, but am greeted with a segmentation fault on runtime. glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, const_cast<int*>(&Texture::MAX_TEXTURE_SLOTS)); I have also tried directly casting to an int * but once again, seg fault. glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, (int*)&Texture::MAX_TEXTURE_SLOTS); Many thanks.
EDIT 2: So since you're trying to abstract OpenGL contexts, you'll have to let go of the "traditional" constructor/destructor idioms. And just for your information (unrelated to this question): OpenGL contexts are not tied to windows! As long as a set of windows and OpenGL contexts are compatible with each other, you may mix and match any way you like. But I digress. The standard idiom to deal with a situation like yours is to use preinitializing factory functions. Like this: class MyOpenGLContextWrapper { public: // Yes, shared_ptr; using a unique_ptr here for objects that are kind // of a nexus for other things -- like an OpenGL context -- just creates // a lot of pain and misery. Trust me, I know what I'm talkink about. typedef std::shared_ptr<MyOpenGLContextWrapper> ptr; struct constdata { NativeGLContextType context; // ... GLint max_texture_image_units; // ... }; static ptr create(); protected: MyOpenGLContextWrapper(constdata const &cdata) : c(cdata) {}; virtual ~MyOpenGLContextWrapper(); constdata const c; } MyOpenGLContextWrapper::ptr MyOpenGLContextWrapper::create() { struct object : public MyOpenGLContextWrapper { object(MyOpenGLContextWrapper::constdata const &cdata) : MyOpenGLContextWrapper(cdata) {} ~object(){} }; MyOpenGLContextWrapper::constdata cdata = {}; // of course this should all also do error checking and failure rollbacks cdata.context = create_opengl_context(); bind_opengl_context(cdata.context); // ... glGetInteger(GL_MAX_TEXTURE_IMAGE_UNITS, &cdata.max_texture_image_units); return std::make_shared<object>(cdata); } EDIT: I just saw that you intend to use this to hold on to a OpenGL limit. In that case you can't do this on a global scope anyway, since those values depend on the OpenGL context in use. A process may have several OpenGL contexts, each with different limits. On most computer systems you'll encounter these days, variables declared const in global scope will be placed in memory that has been marked as read only. You literally can't assign to such a variable. The usual approach to implement global scope runtime constants is by means of query functions that will return from an internal or otherwise concealed or protected value. Like // header.h int runtime_constant(); #define RUNTIME_CONSTANT runtime_constant() // implementation.c / .cpp int runtime_constant_query(){ static int x = 0; // NOTE: This is not thread safe! if( !x ){ x = determine_value(); } return x; } You can then fetch the value by calling that function.
71,756,200
71,838,162
how to transfer QImage from QLocalServer to QLocalSocket
I have two mac apps that communicate with each other using QLocalSocket. Able to send the received QString but not able to send the received QImage Below is my code. SERVER SIDE CODE QImage image(":/asset/logo_active.png"); QByteArray ba; qDebug() << image.sizeInBytes() <<image.size(); ba.append((char *)image.bits(),image.sizeInBytes()); qDebug() <<ba.size(); //262144 this->mSocket->write(ba); if(!this->mSocket->waitForBytesWritten(-1)) { qDebug() << "writen Bytes error " << this->mSocket->errorString(); } this->mSocket->flush(); CLIENT SIDE CODE connect(mLocalSocket,&QLocalSocket::readyRead, [&]() { QByteArray ba; ba = mLocalSocket->readAll(); qDebug() << "size is" << ba.size(); // size is 0 QImage image((uchar *)ba.data(),1024,768,QImage::Format_RGB32); ui->labelStream->setPixmap(QPixmap::fromImage(img)); }); at sender 262144 is the byte-array size but at the receiver, byte-array size is 0 Do let me know if I am missing anything. Thanks In Advance
Finally I got the solutions I used QDataStream below is the code example. SERVER SIDE CODE: QDataStream T(mSocket); T.setVersion(QDataStream::Qt_5_7); QByteArray ba; ba.append((char *)img.bits(),img.sizeInBytes()); T << ba; mSocket->flush(); CLIENT SIDE CODE QByteArray jsonData; QDataStream socketStream(mLocalSocket); socketStream.setVersion(QDataStream::Qt_5_7); for (;;) { socketStream.startTransaction(); socketStream >> jsonData; if (socketStream.commitTransaction()) { QImage image((uchar *)jsonData.data(),640,480,QImage::Format_RGB888); ui->labelStream->setPixmap(QPixmap::fromImage(image)); }else { // the read failed, the socket goes automatically back to the state it was in before the transaction started // we just exit the loop and wait for more data to become available break; } } Thanks, Everyone for your support also Stackoverflow.
71,756,251
71,756,328
Why logical operation is not working properly if i use string::size()
string s; cin >>s ; //input string is: a int i=1; if(i < s.size()-3 ) cout <<"Yes"<<endl; else cout << "No"<<endl; If the input string is a then output should be No but compiler is showing Yes. int i = 1; int len = s.size()-3; if(i < len ) cout <<"Yes"<<endl; else cout << "No"<<endl; If I use the len variable then it is working fine. Now the output is showing No.
s.size() returns an unsigned type. Since s.size() is 1 in your example, unsigned(1)-3 will wrap to a very large positive value. Thus: int i=1; if(i < s.size()-3) compares a signed i to an unsigned value, and so will implicitly convert the value of i to unsigned and evaluate the if as true since 1 is less than that large positive value. Whereas: int len = s.size()-3; will convert the large unsigned positive value into a signed negative value, thus: int i=1; if(i < len) compares two signed values, and will evaluate the if as false since 1 is not less than a negative value.
71,756,300
71,756,593
Passing a concept-constrained function overload
The following code fails to compile (Godbolt link): #include <concepts> template <class Fn> decltype(auto) g(Fn&& fn) { return fn(); } template <typename T> requires(std::integral<T>) int f() { return 0; } template <typename T> int f() { return 1; } int main() { f<int>(); f<void>(); g(f<int>); // error: invalid initialization of non-const reference of type 'int (&)()' // from an rvalue of type '<unresolved overloaded function type>' g(f<void>); } It seems unexpected to me that the overload resolution succeeds when calling f<int>() (selecting the constrained version as a better match than the unconstrained version) but fails when passing f<int> as an argument. Note that changing the unconstrained version to a disjoint constraint does make it compile (Godbolt link): #include <concepts> template <class Fn> decltype(auto) g(Fn&& fn) { return fn(); } template <typename T> requires(std::integral<T>) int f() { return 0; } template <typename T> requires(!std::integral<T>) int f() { return 1; } int main() { f<int>(); f<void>(); g(f<int>); g(f<void>); } So is the compiler behavior correct? And if so, is this an inconsistency in the standard, or is it intended to work this way?
It seems that neither GCC nor Clang has fully implemented the rules for forming pointers to constrained functions: [over.over]/5 definitely considers constraint ordering in choosing an overload. There were some late changes to these, although they’re just as relevant to the disjoint-constraints case as to the unconstrained case.
71,756,956
71,757,341
set empty std::regex
How to create a regex from an input argument? If the argument is empty or undefined no regex should be set int main(int argc, char* argv[]){ std::string arg_name; std::string arg_filter; std::cmatch rem; std::regex re; // Match cmd name if(argc > 1){ arg_name = std::string(argv[1]); } // Match cmd filter if(argc > 2){ arg_filter = std::string(argv[2]); if(!arg_filter.empty()){ const std::regex re(arg_filter); } } std::string cmd = "test"; if(!arg_filter.empty()){ if(!std::regex_search(cmd, rem, re)){ continue; } } return 0; } error # g++ -rdynamic -O2 -std=c++17 proc.cpp -o proc proc.cpp: In function ‘int main(int, char**)’: proc.cpp:49:37: error: no matching function for call to ‘regex_search(std::__cxx11::string&, std::__cxx11::cmatch&, std::__cxx11::regex&)’ if(!std::regex_search(cmd, rem, re)){ ^ In file included from /usr/include/c++/8/regex:62, from proc.cpp:12: /usr/include/c++/8/bits/regex.h:2183:5: note: candidate: ‘template<class _Bi_iter, class _Alloc, class _Ch_type, class _Rx_traits> bool std::regex_search(_Bi_iter, _Bi_iter, std::__cxx11::match_results<_BiIter, _Alloc>&, const std::__cxx11::basic_regex<_CharT, _TraitsT>&, std::regex_constants::match_flag_type)’ regex_search(_Bi_iter __s, _Bi_iter __e, ^~~~~~~~~~~~ update int main(int argc, char* argv[]){ bool use_name = false; std::string arg_name; bool use_filter = false; std::string arg_filter; std::smatch rem; std::regex re; // Match cmd name if(argc > 1){ use_name = true; arg_name = std::string(argv[1]); } // Match cmd filter if(argc > 2){ use_filter = true; arg_filter = std::string(argv[2]); const std::regex re(arg_filter); } std::string cmd = "php /var/www/php/cronjob.php listen_websockets"; std::cout << "Input: " << cmd << std::endl; if(use_filter){ std::cout << "Filter used!" << std::endl; if(std::regex_search(cmd, rem, re)){ std::cout << "Match!" << std::endl; } else{ std::cout << "No match!" << std::endl; } } return 0; } The program is not matching anything.. # ./proc php www Input: php /var/www/php/cronjob.php listen_websockets Filter used! No match!
As mentioned in the comments, you should use smatch instead of cmatch since you are using std::string. Also, you have created 2 separate re variables. You only want one. int main(int argc, char **argv) { // Match cmd name std::string arg_name; if (argc > 1){ arg_name = std::string{argv[1]}; } const std::regex re{argc > 2 ? argv[2] : ""}; // Match cmd filter if (argc > 2){ std::string arg_filter = std::string{argv[2]}; if (!arg_filter.empty()){ std::string cmd{"test"}; std::smatch rem; if (std::regex_search(cmd, rem, re)){ std::cout << "is match\n"; } else { std::cout << "no match\n"; } } } return 0; }
71,757,049
71,757,157
Delaying Movement of Servo after button press - Arduino
Recently I have been working on a project where the main goal is to move a servo on a model rocket to deploy a parachute. I want to make is so that 10 seconds after I press the button the parachute is released. I have some code for this already but It is not working, as it stops the code completely. Does anyone know how to fix this? #include <Servo.h> // constants won't change const int BUTTON_PIN = 7; // Arduino pin connected to button's pin const int SERVO_PIN = 9; // Arduino pin connected to servo motor's pin Servo servo; // create servo object to control a servo // variables will change: int angle = 0; // the current angle of servo motor int lastButtonState; // the previous state of button int currentButtonState; // the current state of button void setup() { Serial.begin(9600); // initialize serial pinMode(BUTTON_PIN, INPUT_PULLUP); // set arduino pin to input pull-up mode servo.attach(SERVO_PIN); // attaches the servo on pin 9 to the servo object servo.write(angle); currentButtonState = digitalRead(BUTTON_PIN); } void loop() { lastButtonState = currentButtonState; // save the last state currentButtonState = digitalRead(BUTTON_PIN); // read new state if(lastButtonState == HIGH && currentButtonState == LOW) { Serial.println("The button is pressed"); time.delay(10000) // change angle of servo motor if(angle == 0) angle = 90; else if(angle == 90) angle = 0; // control servo motor arccoding to the angle servo.write(angle); } }
In Arduino, a delay is usually done with delay(10000); (for 10 seconds). I've never seen or heard of the time.delay() function, so that might be the issue. Otherwise the code looks like it should work as you want. It also might depend on the board you're running it on. I remember having issues using delay() for long periods on an ESP8266 although I'm pretty sure that it is fine for tens of seconds.
71,757,204
71,826,759
Sending a request to my http server hangs indefinitely in CI environment (CircleCI andgithub actions). Works as expected locally
So I’m writing a basic http server in c++ for school. At the moment my service can receive a request and send a basic response. I’m writing a basic acceptance test with python requests and executing it in a shell script by running the webserver in the background and then running the python client. Locally (on Mac) running the tests it works fine, also on a custom ubuntu docker container, which is also used for my config.yml file. But when running the tests on circleCI the client seems to be accepted but the GET request is not being received and the program hangs. Does anyone know why this is and how to solve it? Please not that the include code is still being developed so be kind :slight_smile: My config.yml: version: 2 jobs: build: docker: - image: "rynosaurusrex/ci_for_codam:webserv" steps: - checkout - run: name: Build command: 'echo Building' - run: name: Unit-Test command: "make test && ./unit_test" - run: name: Acceptance-Test command: make acceptence My basic python GET request: import time import requests from requests import Session from enum import Enum class Colors: OKGREEN = '\033[92m' FAILRED = '\033[91m' NATURAL = '\033[0m' OK = 200 BAD_REQUEST = 400 NOT_FOUND = 404 URI_TOO_LONG = 414 TEAPOT = 418 NOT_IMPLEMENTED = 501 localhost = "http://localhost:80" EXIT_CODE = 0 print("Connecting to server...") r = requests.get(localhost) print("Request send!") if r.status_code != OK: print(f"{Colors.FAILRED}[KO] {Colors.NATURAL} Get request on http://localhost:80") EXIT_CODE = 1; else: print(f"{Colors.OKGREEN}[OK] {Colors.NATURAL} Get request on http://localhost:80") # sleep so that the exit code is that of the python script and not the server time.sleep(1) exit(EXIT_CODE) and my messy bash script to run everything: #!/bin/bash # the & runs a command/program in the background ./Webserver.out & # Save the PID to kill the webserv PID=$! # sleep for 2 second to make sure the server has time to start up sleep 2 # run the tests # curl localhost:80 python3 acceptence_tests/TestClient.py # save the return val of the tests for CI T1=$? kill $PID exit $T1 So I print a few status updates when running the tests. When printing Accepted client on fd 4the accept() call was succesful but the request doesn’t seem to be coming through, possible a handshake issue? As mentioned above, running this locally and directly in the container delivers the expected results, how does local ports work within CircleCI? I've tried changing the request to https with port 443, also 0.0.0.0 and it seems like the handshake is failing any ideas? Thanks in advance!
This could be caused by trying to run as root in your container, since this could be blocked/limited by the host system (which is configured/owned by circleCI/github in this case) for security reasons. You could try explicitly creating and using a separate user in your Dockerfile, avoiding weird permission issues. As an example, if you add this to your Dockerfile you'll use test_user instead of root: RUN useradd -m test_user USER test_user
71,757,320
71,757,370
Why does my QT C++ application not update a pushbuttons' text inside the event routine when directed to do so?
I'm very new to Qt Creator and have a question regarding the reason that an update to a pushbuttons text is not occurring at the time I am expecting it to. Below is a snippet of the code showing the pushbutton event. The pushbutton launches another external process (AVRDUDE), which in turn reads the contents of the EEPROM of an Arduino board connected through USB. Data is then processed and displayed in the UI. As the process of reading the EEPROM takes a few seconds to perform, I would like to change the UI pushbutton that calls this routine from "READ FROM EEPROM" to "READING !!" during the execution of this routine. When routine is completed, then return the pushbutton label to "READ FROM EEPROM". Here is the code void MainWindow::on_READ_FROM_EEPROM_clicked() // Read EEPROM into file "fromEEPROM.bin", then output values to UI { ui->READ_FROM_EEPROM->setText("READING !!"); call_AVRDUDE_read(); int mBufferLength = 1024; // AVR 1K EEPROM space in 328p char mBuffer[mBufferLength]; float fB[mBufferLength/4]; QString filename = "fromEEPROM.bin"; QFile mFile(filename); ui->fileCurrentlyDisplayed->setText(filename); // make this filename visable in UI if (mFile.exists()) { if (mFile.open(QFile::ReadOnly)) while (!mFile.atEnd()) mFile.read(mBuffer,sizeof(mBuffer)); mFile.close(); memcpy(&fB, &mBuffer, mBufferLength); // Next, take mBuffer array of chars and copy them into a float array format moveFloatArrayToGUI(fB); // Fill in the tables in the GUI from this array of floats. Pass fB ARRAY to function } // that fills in UI ui->READ_FROM_EEPROM->setText("READ FROM EEPROM"); } Everything in the routine performs exactly as expected with the exception of the very first line ui->READ_FROM_EEPROM->setText("READING !!)" and the last line ui->READ_FROM_EEPROM->setText("READ FROM EEPROM"); What I see in the pushbutton text is just the READ FROM EEPROM label before, throughout, and after execution of the routine. If I change the text string of the last line, this new text will appear in the UI pushbutton. If I COMMENT OUT that last line, then the "READING !!" will appear in the UI pushbutton, BUT ONLY AFTER THE ROUTINE IS COMPLETED. What I was expecting here was the "READING !!" msg to be displayed immediately upon entry, then the time consuming AVRDUDE call would take place, then the pushbutton text would be restored to READ FROM EEPROM. I tried executing ui->READ_FROM_EEPROM->setText("READING !!)" from a separate pushbutton, and it updates the read from EEPROM pushbutton immediately, so I am bewildered as why that line does not execute right upon entry. What am I missing and/or what am I doing wrong? Regards, Mark
The UI is updated only when the code gets to the Event Loop, which won't happen until your application returns. You can force events processing by calling QCoreApplication::processEvents(); after your UI updates, but the recommended way would be to push that blocking code to another thread and use signals/slots to update your UI. See https://doc.qt.io/archives/qq/qq27-responsive-guis.html#manualeventprocessing for reference. The article is old but still holds.
71,757,442
71,758,841
Can you do C++-style CUDA?
I follow some guidelines to deal with memory management in C++. Some examples: I never use malloc. I almost never need or use new or delete. I use smart pointers, and almost never need to write destructors. I want to learn CUDA. I have been looking online for tutorials that match my C++ style of programming, but everything looks C-style. It is not clear to me when this C style of programming is necessary and when it is just the style of the author. As an example, here is a snippet of code from a NVIDIA tutorial: int main(void) { int N = 1<<20; float *x, *y, *d_x, *d_y; x = (float*)malloc(N*sizeof(float)); y = (float*)malloc(N*sizeof(float)); cudaMalloc(&d_x, N*sizeof(float)); cudaMalloc(&d_y, N*sizeof(float)); //... printf("Max error: %f\n", maxError); cudaFree(d_x); cudaFree(d_y); free(x); free(y); } This code uses malloc, free, owning raw pointers, and C-style arrays. Are these all necessary? Can I write modern C++-style CUDA?
CUDA started out (over a decade ago) as a largely C style entity. Over time, the language migrated to be primarily a C++ variant/definition. For understanding, we should delineate the discussion between device code and host code. For device code, CUDA claims compliance to a particular C++ standard, subject to various restrictions. One of the particular restrictions is that there is no general support for standard libraries. For device code, (with some overlap with host code) there is an evolution underway to provide a set of STL-like libraries/features. But as an example, std::vector is not usable in CUDA device code (you can use new in CUDA device code). For host code, there really isn't anything that is intended to be out-of-bounds, as long as we are talking about things that are strictly host code. The exceptions to this are undocumented issues that crop up from time to time for example with boost and perhaps many other libraries. These aren't intentional omissions, but arise via the fact that CUDA uses a special preprocessor/front-end, even for host code, coupled with incomplete testing against every imaginable library one might want to use. It might also be worthwhile to say regarding user-supplied libraries (as opposed to standard libraries or system libraries) that CUDA generally requires functions to be decorated appropriately in order to be usable in device code. Whether we are talking about compiled libraries or header-only libraries, these should generally be usable in host code (subject to the caveat above), but not necessarily in device code, unless the library has been specifically decorated for CUDA usage. Where host code is interfacing with device code, you'll need to follow the limitations fairly closely. Again, a std::vector container cannot be easily passed to a device code function call (a CUDA kernel). But as already mentioned in the comments, there is something similar you can do with the thrust library which is included with the CUDA toolkit install. Are these all necessary? malloc and free are not necessary. You can similarly use new and delete, or use the thrust containers. regarding use of raw pointers and relatedly, C-style arrays, this will probably be more-or-less unavoidable, as these are part of C++ and there are no higher level containers in C++ apart from what is in standard libraries, AFAIK. Use of raw pointers at least at the host-device interface is certainly typical. If you use thrust::device_vector, for example, you will still need to extract a raw pointer to pass to the kernel. The CUDA runtime and driver APIs still have largely a C-style feel to them. It's not formally part of CUDA, but others have created wrappers to make things more "C++ like". One such example is this library from einpoklum/eyalroz. I have no personal experience with it, but the maintenance of it seems to be relatively energetic, a going concern. And as hinted in the comments, via C++ overloads and e.g. replaceable functionality in various containers and library constructs, you can probably build a container or construct that does what you want, perhaps by replacing standard allocators, etc. As already mentioned, thrust intends to provide a container/algorithm approach to leverage those kinds of C++ concepts in a CUDA environment. It's not part of CUDA, but NVIDIA offers a way to accelerate standard C++ code also.
71,757,836
71,757,985
How to make a function dispatch table with a two dimensional map
I want to make a function dispatch table with a 2 dimensional map but i can't figure out how to make a brace enclosed list. enum state_t{ OPENED, CLOSED, OPENING, CLOSING, } state_t do_something(instance_data *data); state_t do_bar(instance_data *data); std::map<const state_t, std::map<const state_t, std::function<state_t(instance_data *data)>>> state_table { {{OPENED, OPENED}, do_something}, {{OPENED, CLOSING}, do_bar} };
You seem misunderstood smth. The proper initializer list for map in map should look like bellow. const for the key type argument is odd, the key type is const inside the map. std::map<state_t, std::map<state_t, std::function<state_t(instance_data *data)>>> state_table {{ OPENED, { {OPENED, do_something}, {CLOSING}, do_bar} }} }; However you might want to use std::pair or std::tuple std::map<std::pair<state_t, state_t>, std::function<state_t(instance_data *data)>> state_table { {{ OPENED, OPENED }, do_something}, {{ OPENED, CLOSING}, do_bar} };
71,758,110
71,758,336
How can I make a template class within a template class
I am working on recreating the forward linked list class so I can better understand pointers. I have hit a roadblock, I have a template class called forward_list. Within this class in the private section I have another class which I want to have the same type as the main (external) class, this class is called node. #ifndef FORWARD_LIST_HPP #define FORWARD_LIST_HPP template <class T> class forward_list { private: class node { T data; node<T>* next; }; node<T>* head, tail; public: forward_list(); ~forward_list(); void pushBack(T t); void print(); }; #endif When I compile the above code with the rest of my code I produce this error: ./forward_list.hpp:11:19: error: non-template type ‘node’ used as a template 11 | node<T>* next; | I also have tried this (I will add a '*' on the line I have added.) #ifndef FORWARD_LIST_HPP #define FORWARD_LIST_HPP template <class T> class forward_list { private: template <class T> // * class node { T data; node<T>* next; }; node<T>* head, tail; public: forward_list(); ~forward_list(); void pushBack(T t); void print(); }; #endif Here is the error this change has produced: ./forward_list.hpp:8:19: error: declaration of template parameter ‘T’ shadows template parameter 8 | template <class T> |
Your first example is pretty close to what you want. The thing to realize is that while forward_list is a class template, forward_list<T> is a class, and forward_list<T>::node is also a class, not a class template. But also forward_list<int>::node is a totally separate class from forward_list<double>::node, even though they're both just called node. So, the following would work: template <class T> class forward_list { private: class node { T data; node* next; // Just node*, not node<T>* }; node* head, tail; // Just node*, not node<T>* public: forward_list(); ~forward_list(); void pushBack(T t); void print(); }; This way forward_list<int> will have a nested class forward_list<int>::node with an int data; member variable, and forward_list<double> will have a nested class forward_list<double>::node with a double data; member variable.
71,758,665
71,761,221
OpenGL draw transparent sphere over solid sphere
I have a small sphere with an Earth texture and I want to have a slightly bigger sphere with clouds texture over it, that is transparent. I draw my objects like this. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPushMatrix(); auto sphere = gluNewQuadric(); gluQuadricDrawStyle(sphere, GLU_FILL); gluQuadricTexture(sphere, true); gluQuadricNormals(sphere, GLU_SMOOTH); th4->bind(); // Cloud texture gluSphere(sphere, 0.42, 32, 32); glPopMatrix(); glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); glPushMatrix(); sphere = gluNewQuadric(); gluQuadricDrawStyle(sphere, GLU_FILL); gluQuadricTexture(sphere, true); gluQuadricNormals(sphere, GLU_SMOOTH); th2->bind(); // Earth texture gluSphere(sphere, 0.4, 32, 32); glPopMatrix(); glutSwapBuffers(); I initialize glut like this glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); The problem is, if I draw them in this order, my Earth sphere appears in front of the cloud texture sphere, and if I swap the drawing order I can no longer see my Earth sphere through my clouds sphere. Updated Code: glCullFace(GL_BACK); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glDisable(GL_BLEND); glPushMatrix(); auto sphere = gluNewQuadric(); gluQuadricDrawStyle(sphere, GLU_FILL); gluQuadricTexture(sphere, true); gluQuadricNormals(sphere, GLU_SMOOTH); th2->bind(); gluSphere(sphere, 0.4, 32, 32); glPopMatrix(); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPushMatrix(); sphere = gluNewQuadric(); gluQuadricDrawStyle(sphere, GLU_FILL); gluQuadricTexture(sphere, true); gluQuadricNormals(sphere, GLU_SMOOTH); th4->bind(); gluSphere(sphere, 0.42, 32, 32); glPopMatrix(); glDisable(GL_BLEND);
Do the following: enable backface culling enable depth test disable blending draw solid earth enable blending draw transparent clouds
71,758,785
71,758,912
no matching function for call to CLASS:CLASSCPP(C++)
ERROR : Description Resource Path Location Type no matching function for call to 'Saat::Saat()' Ucus.cpp /project9/src line 4 C/C++ Problem This my class called Saat #ifndef SAAT_H_ #define SAAT_H_ #include <string> class Saat { public: Saat(int, int); std::string to_string() const; private: int saat, dakika; }; #endif /* SAAT_H_ */ #include "Saat.h" Saat::Saat(int s, int d){ saat = s; dakika = d; } std::string Saat::to_string() const{ return std::to_string(saat) + ":" + std::to_string(dakika); } And this is my class called Ucus #ifndef UCUS_H_ #define UCUS_H_ #include <string> #include "Saat.h" class Ucus { public: Ucus(std::string, std::string, std::string, Saat); static int get_ucus_sayisi(); std::string to_string(); private: std::string cikisSehir; std::string varisSehir; std::string ucusNo; Saat kalkis_saati; static int ucus_sayisi; }; #endif /* UCUS_H_ */ #include "Ucus.h" /*ERROR IS HERE */Ucus::Ucus(std::string cs, std::string vs, std::string un, Saat s) { cikisSehir = cs; varisSehir = vs; ucusNo = un; kalkis_saati = s; } int Ucus::get_ucus_sayisi(){ return ucus_sayisi; } std::string Ucus::to_string(){ return cikisSehir + varisSehir + ucusNo + kalkis_saati.to_string(); } I am watching a video about classes and i want to use my Saat class in Ucus class. I am doing the same things in video but it gives me this error: ***( Description Resource Path Location Type no matching function for call to 'Saat::Saat()' Ucus.cpp /project9/src line 4 C/C++ Problem ) There is nothing different but not works for me.
In a class, members are created before the body of the constructor is entered. Your code is attempting to default construct a Saat, and then overwrite it in the body through assignment. Because your Saat class does not have a default constructor, your code doesn't compile. WHY doesn't your class have a default constructor? The compiler can generate one for you if you don't provide any constructors, but once you write one, the default constructor is no longer provided without request. But if this compiled you'd have been slightly worse off. It's nice to catch a mistake instead of silently living with it. The proper way to do this is to NOT default construct your object, but to copy-construct it, and other members, in the constructors member initializer list: Ucus::Ucus(std::string cs, std::string vs, std::string un, Saat s) cikisSehir{cs}, varisSehir{vs}, ucusNo{un}, kalkis_saati{s}, { } It's more efficient too. No reason to create an object, and then overwrite it via assignment. Better to create it directly by a copy, which is a constructor you'll get generated automatically (unless you have a member that is not copyable, but in your case you don't.) Of course, you really should consider passing in your strings as std::string const & instead, to avoid needless copies.
71,758,822
71,758,921
Strange behaviour of vector in cpp
I was writing the naive version of the polynomial multiplication algorithm. I tried the following code: #include <iostream> #include <vector> using namespace std; vector<int> multp(const vector<int>& A, const vector<int>& B) { vector<int> result = {0}; for(int i = 0; i < A.size() + B.size(); i++) { result[i] = 0; } for (int i = 0; i < A.size(); i++) { for (int j = 0; j < B.size(); j++) { result[i + j] += A[i] * B[j]; } } return result; } int main () { vector<int> A = {1, 1}; vector<int> B = {1, 1, 1}; vector<int> result = multp(A, B); for (int i = 0; i < 4; i++) { cout << result[i] << " "; } return 0; } And it worked just fine, but then, I changed the initialization of the vector from vector<int> result = {0}; to only vector<int> result;. Here I got a seg fault! Why is that? What difference does the = {0} make? Also, in main, after the line vector<int> result = multp(A, B);, when I tried to print the length of the vector (cout << result.size() << endl;) I got 1 even tho the vector had 4 elements in it. Why does this happen?
vector<int> result = {0}; creates a vector with one element so you aren't allowed to access anything but result[0]. An alternative would be to create the vector with as many elements that you need, A.size() + B.size() - 1. Example: #include <iostream> #include <vector> std::vector<int> multp(const std::vector<int>& A, const std::vector<int>& B) { std::vector<int> result(A.size() + B.size() - 1); // correct size /* this is not needed, they will be 0 by default for(int i = 0; i < A.size() + B.size(); i++) { result[i] = 0; } */ for(size_t i = 0; i < A.size(); i++) { for(size_t j = 0; j < B.size(); j++) { result[i + j] += A[i] * B[j]; } } return result; } int main() { std::vector<int> A = {1, 1}; std::vector<int> B = {1, 1, 1}; std::vector<int> result = multp(A, B); for(int resval : result) { // a convenient range based for-loop std::cout << resval << ' '; } std::cout << '\n'; }
71,758,847
71,796,997
ANTLR4: Re-visiting parse rules after the whole ast is visited
I am currently implementing generic functions for my own language, but I got stuck and currently have the following problem: Generic functions can get called from another source file (another parser instance). Let's assume we have a generic function in source file B and we call it from source file A, which imports source file B. When this happens, I need to type-check the body of the function (source file B) once again for every distinct manifestation of concrete types, derived from the function call (source file A). For that, I need to visit the body of the function in source file B potentially multiple times. Source file B: type T dyn; public p printFormat<T>(T element) { printf("Test"); } Source file A: import "source-b" as b; f<int> main() { b.printFormat<double>(1.123); b.printFormat<int>(543); b.printFormat<string[]>({"Hello", "World"}); } I tried to realize that approach by putting the code for analyzing the function body and its children in an inner function and call it every time I encounter a call to that particular function from anywhere (also from other source files). This seems not to work for some reason. I always get a segmentation fault. Maybe this is because the whole tree was already visited once? For additional context: C++ source code of my visitor Would appreciate some useful answers or tips, thank you! ;)
I don't think the best approach is to hack around with parsers. Parsers should turn one array of characters into one AST. In your case, you've got a fairly complex but new language, using multiple files. When you import B, you really want to import the AST. C++ historically messed with a literal #include and the parsing problems that brings, and only now is getting modules. Languages like Java did away with this textual inclusion, but retrofitted generics later on. You've got a clean slate. You should design your language such that the compiler can just take a bunch of AST's as its input. Since the compiler will take AST's as input, each AST will be read-only. You can of course have a cache for instantiations so you don't need to re-instantiate printFormat<int> every time you encounter it in an AST, but that's a detail. What's not an detail is how instantiation should work in your language. A common mistake is the assumption that C++ templates work like macro's, at text level. That's not the case; they work at the language level. Yours should work also at the language level. It would be really convenient for you if instantiation took an AST (or at least a subtree thereof) and would then produce a new AST for the instantiation, again read-only. It's no coincidence that the C++ template meta-language is effectively a functional language. These kinds of problems become much easier the more you can make read-only.
71,758,865
71,758,936
Compile-time arithmetic via generic types in Rust, similar to C++?
I'm just learning Rust and would like to write code that uses generic types to perform compile-time arithmetic. For example, in C++ I can write the following code (on Goldbolt): #include <iostream> template <int X> struct Test { constexpr static int x = X; }; template <int X1, int X2> auto operator+(const Test<X1>&, const Test<X2>&) { return Test<X1 + X2>{}; } int main() { const Test<4> a{}; const Test<6> b{}; const auto c = a + b; std::cout << c.x << '\n'; // prints 10 } I try to write analogous code in Rust (on Playground): use std::ops::Add; pub struct Test<const X: u8>; impl<const X: u8> Test<X> { pub fn x(&self) -> u8 { X } } impl<const X1: u8, const X2: u8> Add<Test<X2>> for Test<X1> { type Output = Test<{X1 + X2}>; fn add(self, rhs: Test<X2>) -> Test<{X1 + X2}> { Test::<{X1 + X2}>{} } } fn main() { let a: Test<4> = Test{}; let b: Test<6> = Test{}; let c = a + b; println!("{}", c::x()); } ...but this won't compile, since generic parameters may not be used in const operations. Is this kind of thing simply impossible to do with Rust, or is there another strategy I can try?
You can do it, but const generics aren't complete yet, so it currently requires a nightly compiler and an explicitly enabled feature: #![feature(generic_const_exprs)] #![allow(incomplete_features)] use std::ops::Add; pub struct Test<const X: u8>; impl<const X: u8> Test<X> { pub fn x(&self) -> u8 { X } } impl<const X1: u8, const X2: u8> Add<Test<X2>> for Test<X1> where [(); (X1 + X2) as usize]: { type Output = Test<{X1 + X2}>; fn add(self, _rhs: Test<X2>) -> Test<{X1 + X2}> { Test::<{X1 + X2}>{} } } fn main() { let a: Test<4> = Test{}; let b: Test<6> = Test{}; let c = a + b; let Test::<10> = c; println!("{}", c.x()); } (Permalink to playground)
71,759,207
71,759,455
I need to track changes to files, but I cannot think of a way
I have an idea that I am working on. I have a windows mini-filter driver that I am trying to create that will virtualize changes to files by certain processes. I am doing this by capturing the writes, and sending the writes to a file that is in a virtualized location. Here is the issue: If the process tries to read, it needs to get unaltered reads for parts of the file it has not written to, but it needs to get the altered reads from parts that have been written to. How do I track the segments of the file that have been altered in an efficient way? I seem to remember a way you can use a bitmask to map file segments, but I may be misremembering. Anyway any help would be greatly appreciated.
Two solutions: Simply copy the original file to virtualized storage, and use only this file. For small files, it will probably be the best and fastest solution. To give an example, let's say that any file smaller than 65536 bytes would be fully copied - use a power of two in any case. If file is growing above limit, see solution 2. For big files, keep overwritten segments in virtualized storage, use them according to current file position when needed. Easiest way will be to split it in 65536 bytes chunks... You get the chunk number by shifting file's position by 16 to the right, and the position within the chunk is obtained by masking only the lower 16 bits. Example: file_position = 165 232 360 chunk_number = file_position >> 16 (== 2 521) chunk_pos = file_position & 0xFFFF (== 16 104) So, your virtualized storage become a directory, storing chunk named trivially (chunk #2521 = 2521.chunk, for example). When a write occurs, you start to copy the original data to a new chunk in virtualized storage, then you allow application to write inside. Obviously, if file is growing, simply add chunks that will exist only in virtualized storage. It's not perfect - you can use delta chunks instead of full ones, to save disk space - but it's a good start that can be optimized later. Also, it's quite easy to add versions, and keep trace of: Various applications that use the file (keep multiple virtualized storages), Successive launches (run #1 modifies start of file, run #2 modifies end of file, you keep both virtualizations and you can easily "revert" the last launch).
71,760,243
71,781,767
Use std::function to wrap a function with optional arguments (using maybe boost::optional), and serve as a template in another class
In my recent project I want to define a class X which has an input functional in its constructor, i.e., std::function<double(const A&, const B&)>. In real applications, the argument of class B is optional (sometimes it will not have this argument). So I am trying to use the boost::optional for the second argument in my function. All of class A and B will show up as template in my class X. What is the best way to achieve this behavior I want? I have tried: The code for class X: template <typename Function, typename A, typename B, typename... Args> class X{ X(Function _f, A _a, boost::optional<B> _b){ f_{_f}; a_{_a}; if (_b){b_{_b};} } ... private: Function f_; A a_; boost::optional<B> b_; public: void call_function(Args... args){ f_(args..., a_, boost::option<B> b_); } }; The code for the definition of function Function f and instantiation of X: double f_example(const A_actual& a, boost::optional<B_actual> b, const OTHER& other){ ... if (b)... } ... (declare and define instances of A_actual and B_actual and OTHER)... X<std::function<double(const A_actual&, boost::option<B_actual>, const OTHER&)>, A_actual, boost::option<B_actual>> x(...); Is this code correct and can achieve what I want to achieve?
With typo fixed, it would be #include <functional> #include <optional> template <typename Function, typename A, typename B, typename... Args> class X { public: X(Function f, A a, std::optional<B> b) : f_{f}, a_{a}, b_{b} { } void call_function(Args... args){ f_(a_, b_, args...); } //... private: Function f_; A a_; std::optional<B> b_; }; and double f_example(const A_actual& , std::optional<B_actual> , const OTHER& ){ // ... return 0.0; } void foo(const A_actual& some_a, const std::optional<B_actual>& some_b, const OTHER& some_other) { X<std::function<double(const A_actual&, std::optional<B_actual>, const OTHER&)>, A_actual, B_actual, const OTHER&> x(f_example, some_a, some_b); x.call_function(some_other); } Demo
71,760,259
71,760,305
How to forward a non-movable object in std::pair
I can't figure out the syntax to perfectly forward a std::pair when it contains something that's non-movable. #include <mutex> #include <list> #include <utility> struct A { A(int x) { } }; int main() { std::list<std::pair<std::mutex, std::mutex>> v; v.emplace_back(); // ok std::list<std::pair<A, A>> v2; v2.emplace_back(3, 4); // ok std::list<std::pair<A, std::mutex>> v3; v3.emplace_back(3, std::forward<std::mutex>(std::mutex{})); // help }
You must construct the std::mutex in-place from an empty argument list. This can be done using the std::piecewise_construct constructor, which allows you to forward arguments for the constructors of the two elements as std::tuples. // for std::forward_as_tuple #include<tuple> // ... v3.emplace_back(std::piecewise_construct, std::forward_as_tuple(3), std::forward_as_tuple());
71,760,656
71,760,732
How to transferring an array of main functions to a class?
First of all, I made this class. class Matrix { public: double ele[4][4]; int numOfRow; int numOfColumns; public: Matrix() { numOfRow = 0; numOfColumns = 0; ele[4][4] = 0; } Matrix(double mat[][4], int Row, int Col) { numOfRow = Row; numOfColumns = Col; for (int i = 0; i < numOfRow; i++) { for (int j = 0; i < numOfColumns; j++) { ele[i][j] = mat[i][j]; } } } Matrix Add(Matrix m) { Matrix output; for (int i = 0; i < numOfRow; i++) { for (int j = 0; j < numOfColumns; j++) { output.ele[i][j] = ele[i][j] + m.ele[i][j]; } } return output; } Matrix Subtract(Matrix m); Matrix Multiply(Matrix m); Matrix Transpose(void); }; This is part of the main function. In this way, I'm going to bring up the values of the txt files that I've already made in matA and matB and replace them. It's just a process of putting numbers in. double matA[4][4]; for (int i = 0; i < RowA; i++) { for (int j = 0; j < ColA; j++) { fscanf(fpInput, "%lf", &matA[i][j]); } } double matB[4][4]; for (int i = 0; i < RowB; i++) { for (int j = 0; j < ColB; j++) { fscanf(fpInput, "%lf", &matB[i][j]); } } And we substitute matrixA and matrixB class objects, respectively. Matrix matrixA(matA, RowA, ColA); Matrix matrixB(matB, RowB, ColB); I tried substitute Value obtained by 'Add' function into class object called matrixO. but, The substituted values did not work smoothly. For example, if matrixA contains (1, 2, 3) in order and matrixB has (4, 5, 6), then the 'add function' requires that the array of matrixO contains (5, 7, 9), but it does not. The value of the matrixO.ele is not output at all. Matrix matrixO = matrixA.Add(matrixB); for (int i = 0; i < RowA; i++) { for (int j = 0; j < ColA; j++) { fprintf(fpOutput, "%lf ", matrixO.ele[i][j]); printf("%lf", matrixO.ele[i][j]); } fprintf(fpOutput, "\n"); } In the Matrix constructor section, I changed it like this. public: Matrix() { numOfRow = 0; numOfColumns = 0; ele[4][4] = ele[0][0]; } public: Matrix() { numOfRow = 0; numOfColumns = 0; ele[4][4] = {}; } But both of these cases are wrong. How do we solve this issue?
You are assigning a value to your matrix out-of-bounds: ele[4][4] = 0; The last element of double ele[4][4]; is ele[3][3]; This is undefined behavior, so it makes no sense to analyze what happens after it. You can 0-initialize your Matrix in its constructor like this: Matrix(): ele(), numOfRow(), numOfColumns() {}
71,761,445
71,773,988
why does wxDC::GetTextExtent() return the same value for a high DPI display in wxWidgets?
I am trying to scale my application written in c++ with wxWidgets for high DPI displays. I am following the guidelines in the official link. Everythings work fine so far except the return value of wxDC::GetTextExtent() function. When I move my window to a monitor with a different DPI, the font size scales but the return value of the wxDC remains the same as before. However if I use wxWindow::GetTextExtent(), it returns the correct value! In the document, it says all wxWidgets API use logical pixels but it does not seem so. In other words, if you try to draw "text" on a device context (dc) in a high DPI display, the drawn text would be small cause the measured value of the font height by wxDC is small ( e.g does not scale ). However all other text drawn by wxWindow scales correctly. Is this behavior intentional? what should I do to have a correct value? I am using wxWidgets 3.1.5 and Win 10. Also it is not clear whether wxWidgets use Device Independent Pixels (DIP) or logical Pixels?
wxDC::GetTextExtent() and wxWindow::GetTextExtent() should return the same value and if I insert this code in the minimal sample: void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) { wxClientDC dc(this); wxLogMessage("wxDC: %d, wxWindow: %d", dc.GetTextExtent("Hello").x, GetTextExtent("Hello").x); } it displays "wxDC: 28, wxWindow: 28" with default DPI screen and "wxDC: 56, wxWindow: 56" when using 200% DPI scaling with wxWidgets 3.1.6, so you probably just need to update to this release.
71,761,810
71,762,002
sleep_for causes buffering effect
If I comment out the sleep_for, the program churns out commas and dots without issues. But when I add the sleep_for, it hangs for a while before suddenly writing all of the commas and dots you would have expected to come evenly during the hang all in one go. This program was reduced to a minimum working example from something that was much larger and more complex, but fortunately the issue remains. (Compiled using apt-installed g++ 11.2.0 on Ubuntu 20.04.4 LTS) #include <chrono> #include <iostream> #include <RingBuffer.h> #include <thread> void writeCharToBuffer(volatile bool& quit, char, std::chrono::milliseconds); int main() { bool quit { false }; using namespace std::literals; std::thread dotToBufferThread { writeCharToBuffer, std::ref(quit), '.', 100ms}; std::thread commaToBufferThread { writeCharToBuffer, std::ref(quit), ',', 200ms}; int quitKey; std::cin >> quitKey; quit = true; dotToBufferThread.join(); commaToBufferThread.join(); } void writeCharToBuffer(volatile bool& quit, char c, std::chrono::milliseconds d) { while (!quit) { std::cout << c; std::this_thread::sleep_for(d); } }
Output to std::cout is buffered. It might be that the output without the delay will fill up the buffer quick enough that you won't notice it. If you want immediate output you need to explicitly flush it: std::cout << c << std::flush;
71,762,727
71,762,912
Is there a data structure for implementing a function equivalent to 'tail -n' command in C++?
I want to write a function equivalent to the Linux tail -n command in C++. While, I parsed over the data of that file line-by-line thereby incrementing the line count, if the file size gets really big(~gigabytes), this method will take a lot of time! Is there a better approach or a data structure to implement this function? Here are my 2 methods: int File::countlines() { int lineCount = 0; string str; if (file) { while (getline(file, str)) { lineCount += 1; } } return lineCount; } void File::printlines() { int lineCount = 0; string line; if (file) { lineCount = countlines(); file.clear(); file.seekg(ios::beg); if (lineCount <= 10) { while (getline(file, line)) { cout << line << endl; } } else { int position = lineCount - 10; while (position--) { getline(file, line); } while (getline(file, line)) { cout << line << endl; } } } } This method is time consuming if the file size increases, so I want to either replace it with another data structure, or write a more efficient code.
One of the things that is slowing down your program is reading the file twice, so you could keep the last n EOL positions (n=10 in your program) and the most convenient data structure is a circular buffer but this isn't provided by the standard library as far as I know (boost has one). It can be implemented by an std::vector with size n, with an index where a modulo of n is done after incrementing. With that circular buffer, you can jump immediately to the lowest offset (next one if buffer is full) in the file and print the needed lines.
71,762,790
71,762,872
Why do I get a not declared in this scope error even though the header file is included?
The error I get is /opt/workspace/IhmActon/ihm_acton/src/model_inference/retinanet/engine.cpp:213:5: error: ‘trt_unique_ptr’ was not declared in this scope trt_unique_ptr<trt::IHostMemory> serialized_engine = wrap_trt_ptr(engine->serialize()); This is a photo snippet of that function and where the error is The declaration of trt_unique_ptr is in this header file(tensorrt.hpp). In engine.hpp, I have an import statement to include that header file - #include "model_optimizer/tensorrt.hpp" . I do not see any errors with the import statement Why do I still get this not declared in scope error?
trt_unique_ptr is inside namespace ihm_springfield. Use ihm_springfield::trt_unique_ptr instead.
71,763,111
71,763,730
How make std::set insertions faster?
I am using the std::set container to store some scalar integer values. I've noticed that the insert operation is slow when I call it in a loop. How can I make it faster? Here is some representative code: std::set<unsigned long> k; unsigned long s = pow(2,31); for(unsigned long i = 0; i < s; i++){ k.insert(i); } std::cout << k.size() << std::endl; This code takes a very long time to execute. How can I modify this code (and/or change my algorithm) in order to make it run faster?
How make set function faster? You can make this faster by using hints, since you know that every insert is to the end of the set: for(unsigned long i = 0; i < s; i++){ k.insert(k.end(), i); } Alternatively, you could potentially make it faster using another data structure, such as std::unordered_set for example. Most significantly, you could make it faster by not creating such a massive set in the first place. For example, if you need to know whether some unsigned long ul is in the set of integers [0, s), then you can simply use ul < s instead of creating the set that contains all the integers.
71,763,247
71,763,485
Compare vector<int> with no name
#include <iostream> #include <string> #include <vector> #include <list> using namespace std; int main() { std::list<int> list{ 1, 2, 3, 4, 5 }; std::vector<int> vec1{ 1, 2, 3, 4, 5 }; std::vector<int> vec2{ 1, 2, 3, 4 }; if(vector<int>(list.begin(), list.end()) == vec1) { cout << "haha"; } return 0; } There is no name in vector<int>(list.begin(), list.end()). How is it possible to compare vector<int> with no name and vec1.
How is it possible to compare vector with no name and vec1. std::vector has overloaded operator== as a non-member function. template< class T, class Alloc > bool operator==( const std::vector<T,Alloc>& lhs, const std::vector<T,Alloc>& rhs ); This means that when you wrote: vector<int>(list.begin(), list.end()) == vec1 a temporary std::vector<int> object is created and is passed as the first argument to the above shown overloaded operator== while vec1 is passed as the second argument to the same overloaded operator== and thus the comparison succeeds. In other words, the first parameter lhs is bound to the temporary std::vector<int> while the second parameter rhs is bound to vec1.
71,763,498
71,763,598
Why does the following not compile?
Given the following code, #include <iostream> #include <string> #include <string_view> #include <unordered_map> struct sstruct { std::string content; std::string_view name; virtual std::string get_content() { return ""; } }; int main() { std::unordered_map<std::string, sstruct> map{ { "pippo", {"dddd", ""} } }; std::cout << map["pippo"].content << std::endl; } when the method get_content() is virtual it does not compile, otherwise, it does. Why is that?
If the member function is not virtual, then your class is an aggregate class. (For the requirements making a class aggregate, see here.) An aggregate class can be aggregate initialized, which means it can be initialized with a braced initializer list such as {"dddd", ""} and aggregate initialization will initialize each non-static data member of the class by successive entries in the list, without calling a constructor of the class. If you add a virtual member function the class is no longer an aggregate class, because aggregate classes may not have virtual member functions at all, and therefore aggregate initialization is not possible. Then the only way to initialize the class is via a constructor, but the only constructor your class has are the implicit default constructor, which doesn't take any arguments, and the implicit copy and move constructors, which take exactly one argument. You are trying to construct with two arguments ({"dddd", ""}) and so it will fail. if you want the virtual member function, then you need to provide an appropriate constructor, e.g.: struct sstruct { std::string content; std::string_view name; virtual std::string get_content() { return ""; } sstruct(std::string content_, std::string_view name_) : content(std::move(content_)), name(name_) { } };
71,763,917
71,764,165
How much can I change code to keep rand() giving same output for given seed?
I'm implementing an algorithm. Because calculations takes time, and I need to repeat them multiple times, I'm saving to output file seed values as well. The idea was that I could repeat same instance of a program if I'll need to get more info about what was happening (like additional values, some percentage, anything that will not mess in the algorithm itself). Unfortunately, even though I thought everything worked as intended, about 20% of the seeded instances gave different values in at least one of the outputted values. My question is - what type of changes in the code affects how srand() / rand() works in C++? Each class is compiled separately and all are linked together at the end. Can I implement functions and everything will be fine? Does it break only when I change the size of any class in the program by adding/removing class fields? Is it connected with heap/stack allocation? Until now, I thought that if I seed srand() I will have same order of rand() values no matter what (eg. for srand(123) I'll always get first rand() == 5, second rand() == 8 etc.). And I can break it only when I'll put more rand() calls in between. I hope you could find where I'm thinking wrong, or you could link something that will help me. Cheers mrozo
Your understanding about srand is correct: seeding with a specific value should be enough to generate a reproducible sequence of random numbers. You should debug your application to discover why it behaves in a non-reproducible way. One reason for such behavior is a race condition on the hidden RNG state. Quoting from the C++ rand wiki: It is implementation-defined whether rand() is thread-safe. ... It is recommended to use C++11's random number generation facilities to replace rand().
71,764,074
71,764,235
srand(n) giving same values for any n
void generator() { int n = <some number>; srand(n); int first = randint(9); digits.push_back(first); while (digits.size() < 4) { bool flag = true; int num = randint(9); for (int j = 0; j < digits.size(); j++) { if (num == digits[j]) { flag = false; break; } } if (flag == true) { digits.push_back(num); } } for (int i : digits) { cout << i << " "; } } int main() { generator(); } This code is supposed to generate 4 random and distinct digits on execution. randint(x) is a function which generates a single random value anywhere between 0 and x. While my digits are distinct, they aren't random. No matter what value I put inside srand(), I'm getting the same four digits: 2 4 5 1 Help me out if I'm doing something wrong.
std::experimental::randint is coupled with std::experimental::reseed to set the seed per thread: srand will have no effect on the generated output. You'll probably find that randint is automatically seeded with a constant value which accounts for your output. As it never became part of the C++ standard, I cannot comment further with certainty. This is all non-standard, all non-portable, and best avoided from C++11 now we have <random>.
71,764,991
71,766,247
gdb watch a variable by address stop at where it cannot be modified
A program crashes. I use gdb to check, find that a private member of a instance is changed in a very weird way. This variable refreshRank,is only modified at line 283 and 286. I use gdb to watch refreshRank by watch its address, i.e., watch *0x5555559ec278. I get the address by p &refreshRank when I am in a member function of the class. However, with watch command, gdb says that where refreshRank is modified is before line 594. But it cannot be modified! refreshRank is even not referenced in those lines, as l command gives. Hardware watchpoint 1: *0x5555559ec278 Old value = 0 New value = 1 DRAMSim::MemoryController::update (this=0x5555559ec020) at MemoryController.cpp:594 594 newTransactionBank, transaction->data, dramsim_log); (gdb) l 589 totalReads[transaction->core]++; 590 } 591 592 BusPacket *command = new BusPacket(bpType, transaction->address, 593 newTransactionColumn, newTransactionRow, newTransactionRank, 594 newTransactionBank, transaction->data, dramsim_log); 595 596 597 598 commandQueue.enqueue(ACTcommand); So I wonder, how can this happen? The variable is modified at a place which it cannot be.
As @j6t points out, the last line it executes, totalReads[transaction->core]++;, transaction->core is out of bound. And in the class definition: uint64_t totalReads[NUM_CPU]; uint64_t totalPrefReads[NUM_CPU]; uint64_t totalWrites[NUM_CPU]; unsigned channelBitWidth; unsigned rankBitWidth; unsigned bankBitWidth; unsigned rowBitWidth; unsigned colBitWidth; unsigned byteOffsetWidth; int totalRead, totalWrite; unsigned refreshRank; Those two variables are close.
71,765,067
71,765,414
Error about operator overloading when I try to compile this code
#include<iostream> #include<iomanip> using namespace std; class Rice { float price_per_kg, total_weight; public: Rice(float w) { price_per_kg = 10.0; total_weight = w; } void display_rice() { cout<<"----------------------------------------"<<endl; cout<<"\tRice Details"<<endl; cout<<fixed<<setprecision(2); cout<<"Total weight\t : "<<total_weight<<endl; cout<<"Price perkg (RM): "<<price_per_kg<<endl; cout<<"Total (RM)\t : "<<total_weight*price_per_kg<<endl; } }; class Product:public Rice { float kg; public: Product operator+(const Product &p) { return Rice(kg + p.kg); } void Setdata() { cout << "Enter product's weight(kg): "; cin >> kg; } }; int main() { Product a, b; a.Setdata(); b.Setdata(); Rice h = a + b; h.display_rice(); } I got this error: [Error] could not convert 'Rice((((Product*)this)->Product::kg + ((float)p.Product::kg)))' from 'Rice' to 'Product' Is there any way to solve the error? I have tried to use other ways to solve but the question requires operator overloading.
The compiler is telling you a Rice isn't a Product. Either you change the return type Rice operator+(const Product &p) Or you change the expression you return { Product result = *this; result.kg += p.kg; // or some other things? return result; } Or you re-think your classes. Do you really mean that a Product is a Rice and not the other way around? At the moment a Product has both a kg member directly, and a total_weight member within the Rice base-subobject.
71,765,698
71,765,798
Use class as type in other class constructor
i would like to use a class Point in an other class Rect. class Point { int x, y; public: Point (int px, int py){ x = px; y = py; } }; class Rect { Point top_left; Point bottom_right; public: Rect (Point p1, Point p2){ top_left = p1; bottom_right = p2; } }; error message is: "main.cpp:31:30: error: no matching function for call to ‘Rect::Point::Point()’". In my understanding the constructor method of the Rect class uses two parameters of type Point to instantiate a Rect object. I guess that i cannot use "Point" as type since it sounds to me as the compiler wants to call a function. The error message doesn't help me so i hope you will. Thanks for that in advance.
The problem is that when a Rect object is created, the member variables are constructed and initialized before the Rect constructor body is executed. Since there's no explicit initialization of the Point member variables, they will need to be default constructible, which they aren't because you don't have a default Point constructor. There are a couple of possible possible solutions, of which the simplest one is: Create a Point default constructor. It doesn't have to do anything and can be compiler generated (but you must still tell the compiler to generate it): class Point { public: Point() = default; ... }; While Point can now be default constructed, it will leave the x and y members uninitialized. But I would rather recommend another solution: Create a Rect constructor initializer list to initialize the member variables of Rect: class Rect { Point top_left; Point bottom_right; public: Rect(Point p1, Point p2) : top_left(p1), bottom_right(p2) { // Empty } ... }; With the second solution no Point default constructor is needed. As for why there's no default constructor created for Point, it's because you have declared another constructor. That prohibits the compiler from generating its own default constructor (without being told to do so as in the first alternative).
71,765,955
71,770,854
How to place a space at the end of cout
I need to know why c++ doesn't see the space just at the end of cout function. I'm using CLion and C++ 23 (language_standart) int main() { string Item ; double Price ; int Quantity ; double Total ; cout << "Your item to buy : " ; getline(cin, Item) ; cout << "Price of the item : " ; cin >> Price ; cout << "Quantity of the item : " ; cin >> Quantity ; cout << endl ; Total = Price * Quantity ; cout << "Item : " << Item << endl ; cout << "Price : " << Price << endl ; cout << "Quantity : " << Quantity << endl ; cout << "Total is : " << Total << endl ; } When I run the code, it returns me Your item to buy :**HereIsNoSpace** **HereIsSpace**Price of the item : **HereIsSpace**Quantity of the item : So I need to enter an Item just after ":" and not ": " And as you can see probably my spaces somehow goes just after my input and passes to the next string
Apparently one of the workarounds is, try doing the following: in Registry (Help | Find Action..., type Registry there) disable the run.processes.with.pty option and restart CLion. Does that help? According to the response in CPP-12752 disabling PTY (without CLion restart, since the run.processes.with.pty option is not saved after CLion's restart - CPP-8395) helps. Guys I've found the solve of this heck !
71,765,969
71,767,336
Binary Search Implementation in C++
I have written a program which should do the following: read product item data from an inventory file and add them in a vector object. The program will allow user to view, search and order the product items. The inventory file should be updated after the order of any item. For operation #2 (searching) and #3 (ordering), appropriate messages should be displayed for the input of invalid item name, then program should proceed to process next operation Expected output: >: 2 Enter the item name to search: table table not found. >: 2 Enter the item name to search: Microwave Microwave is in stock. For operation #3 (ordering), program should validate the input number of order and make sure there are enough items in the inventory. Otherwise, display error message and skip the ordering – Expected output: >: 3 Enter the name of the item: Microwave Enter the nuber of items: 100 Insufficient inventory. >: 3 Enter the name of the item: Microwave Enter the nuber of items: 2 Total cost is $300 >: 3 Enter the name of the item: table table not found. but when I try to search for the name of the item by name using binary search, it doesn't give me the result I want, example: 1. >: 2 Enter the item name to search: Cooking Range Cooking Range not found. >: 2 Enter the item name to search: Circular Saw Circular Saw not found. This is the file that contains the data: itemData.txt 1111 Dish Washer 20 550.5 2222 Microwave 75 150 3333 Cooking Range 50 850 4444 Circular Saw 150 125 And this is the definition of the function I tried to implement to search the items by name: int searchItemByName(vector<Item> items, string searchName) { int low, high, mid; low = 0; high = items.size() - 1; while (low <= high) { mid = (low + high) / 2; if (items[mid].getName() == searchName) return (mid); else if (items[mid].getName() > searchName) high = mid - 1; else low = mid + 1; } return (-1); } Here is the entire program (I've also added a clearer and broader "description" of what the program should do with some tests.): https://github.com/jrchavez07/project_07
I checked your GitHub project. I think you have to sort data before binary search. Current Data in the sample text file list like this: Dish Washer Microwave Cooking Range Circular Saw And these are not sorted, so you can not use Binary Search.
71,765,979
71,766,399
Double derived class produces error unless call to Base
The following code causes my compiler to produce two errors: type name is not allowed and expected an expression. #include <iostream> class Base { protected: template <typename T1> void print_pi() { std::cout << (T1)3.141596 << std::endl; }; }; template <typename T2> class Derived : public Base { }; template <typename T3> class DoubleDerived : public Derived<T3> { public: void test() { print_pi<int>(); // This creates error, however changing to Base::print_pi<int>(); works. } }; int main() { DoubleDerived<float> dd; dd.test(); } The issue is the line print_pi<int>() in the test() function of the DoubleDerived class. However, if this is changed to Base::print_pi<int>() everything compiles without error. What is going on here and is changing to the Base function call the only way around this issue? Additionally, why doesn't this happen if the test() function were to be in the Derived class? Edit: The associated answer listed above still causes errors on some compilers (NVCC) so I cannot endorse that question as an actual substitute.
In the class Derived the name print_pi is a dependent name. You can use for example template <typename T3> class DoubleDerived : public Derived<T3> { public: void test() { Derived<T3>::template print_pi<int>(); } }; or template <typename T3> class DoubleDerived : public Derived<T3> { public: void test() { DoubleDerived::template print_pi<int>(); } };
71,766,043
71,767,154
Why does a segmentation fault not occur?
I am expecting a seg-fault to occurr after the execution of the code below, but it doesn't. Could someone tell me why? int main(){ float *arr; cout << arr[0] << "\n" --> This prints out a ZERO. I am expecting a seg-fault. cout << arr[1000] << "\n" --> This gives me a seg-fault return 0; } I am wondering if this due to the "smart" design of the compiler that alleviates the crash. But I can't be sure.
Since the pointer arr is not initialized, it probably has the value of whatever value that memory address had when it was previously used. In your case, the code that used that memory address previously probably used that memory address for storing a pointer, i.e. for storing another memory address that points to a valid object. Even if the lifetime of that object has expired in the mean time, the operating system will probably not be able to detect this, because the memory page was probably not returned to the operating system. Therefore, as far as the operating system is concerned, that memory page is still readable (and possibly also writable) by the program. This probably explains why dereferencing the uninitialized value of arr does not produce a segmentation fault. The expression arr[1000] will attempt to dereference an address that is 4000 bytes apart from the uninitialized value of arr (assuming sizeof(float)==4). A typical size of a memory page is 4096 bytes. Therefore, assuming that the uninitialized value of arr is a memory address that points near the start of a memory page of 4096 bytes, then adding 4000 to that address will not change the memory address sufficiently to make the address point to a different memory page. However, if the uninitialized value of arr is a memory address that points somewhere in the middle of a memory page, then adding 4000 to that address will make it point to a different memory page (assuming a memory page size of 4096 bytes). This probably explains why your operating system treats both addresses differently, so that one memory access causes a segmentation fault and the other memory access does not fail. However, this is all speculation (which is made clear by my frequent use of the word "probably"). There could be another reason why your code does not cause a segmentation fault. In any case, when your program invokes undefined behavior (which it does by dereferencing an uninitialized pointer), you cannot rely on any specific behavior. On some platforms, it may cause a segmentation fault, while on other platforms, the program may work perfectly. Even changing the compiler settings (such as the optimization level) may be enough to change the behavior of the program. I am wondering if this due to the "smart" design of the compiler that alleviates the crash. The "smart" thing to do in such a case would be to report some kind of error (i.e. to crash), and not to attempt to alleviate the crash. This is because crashing makes the bug easier to find. The reason why your program is not crashing immediately is that neither your compiler nor your operating system are detecting the error. If you want such errors to be detected more reliably, then you may want to consider using a feature offered by some compilers that tries to detect such bugs. For example, both gcc and clang support AddressSanitizer. On those two compilers, all you have to do is compile with the -fsanitize=address command-line option. However, this will cause the compiler to add additional checks, which will significantly decrease performance (by a factor of about two) and increase memory usage. Therefore, this should only be done for debugging purposes.
71,766,426
71,768,080
Sort in descending order the array elements that belong to the shaded area
#include <iostream> #include <cmath> #include <stdlib.h> #include <iomanip> using namespace std; int **CreateMatrix (int rows, int cols); void FillMatrix (int **matrix, int rows, int cols); void OutputMatrix (int **matrix, int rows, int cols); void SortMatrix (int **matrix, int rows, int cols); void DellMatrix(int **matrix, int rows); int main(){ srand(time(NULL)); int rows = 9, cols = 9; int **matrix = CreateMatrix(rows, cols); FillMatrix(matrix, rows, cols); cout << "Цикл до сортування: " << endl; OutputMatrix(matrix, rows, cols); cout << endl; SortMatrix(matrix, rows, cols); cout << "Цикл після сортування: " << endl; OutputMatrix(matrix, rows, cols); DellMatrix(matrix, rows); system("pause"); return 0; } int **CreateMatrix(int rows, int cols){ int **matrix = new int *[rows]; for (int i = 0; i < rows; i++) { matrix[i] = new int [cols]; } return matrix; } void FillMatrix(int **matrix, int rows, int cols){ int N = 19; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { matrix[i][j] = N; } } for (int i = rows - 1; i > rows / 2 - 1; i--) { for (int k = cols - 1 - i; k < 1 + i; k++) { matrix[i][k] = rand() % 100; } } } void OutputMatrix(int **matrix, int rows, int cols){ for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { cout << setw(5) << matrix[i][j]; } cout << endl; } } void SortMatrix (int **matrix, int rows, int cols){ //selection sort int max, maxi; for (int k = rows - 1; k > rows / 2 - 1; k--) { for (int i = cols - 1 - k; i < 1 + k; i++) { max = matrix[k][i]; maxi = i; for (int j = i + 1; j <= k; j++) { if (matrix[k][j] > max) { max = matrix[k][j]; maxi = j; } } matrix[k][maxi] = matrix[k][i]; matrix[k][i] = max; } } } void DellMatrix(int **matrix, int rows){ for (int i = 0; i < rows; i++) { delete matrix[i]; } delete[] matrix; } Цикл до сортування: 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 64 19 19 19 19 19 19 19 64 47 94 19 19 19 19 19 59 5 54 70 4 19 19 19 56 21 49 45 17 87 61 19 48 3 5 33 40 70 84 46 68 Цикл після сортування: 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 64 19 19 19 19 19 19 19 94 64 47 19 19 19 19 19 70 59 54 5 4 19 19 19 87 61 56 49 45 21 17 19 84 70 68 48 46 40 33 5 3 Hi all, Task: The elements in the shaded area are generated randomly. All others = N. Arrange the elements in the shaded area in descending order. I did a sort in rows, but I need all elements in general to be sorted in descending order, i.e. at the top the biggest elements, below the smallest. I can not figure out how to re-do it, hope for your help! Thank you.
I would do it like that: int NumberOfValues(int cols) { int count = 0; for (int i = cols; i > 0; i -=2) count += i; return count; } void FillMatrix(int **matrix, int rows, int cols){ int N = 19; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { matrix[i][j] = N; } } std::vector<int> random_numbers(NumberOfValues(cols)); for (auto &i : random_numbers) i = rand() % 100; std::sort(begin(random_numbers), end(random_numbers)); int index = 0; for (int i = rows - 1; i > rows / 2 - 1; i--) { for (int k = cols - 1 - i; k < 1 + i; k++) { matrix[i][k] = random_numbers[index++]; } } } make an array (a std::vector is perfect for that) with the correct number of values in the pyramid (for 9 cols you have 9 values in the last row, 7 above that, 5 above the 7, 3 above the 5 and 1 above the 3, so 9+7+5+3+1), fill it with random numbers, sort it and then use these values instead of random numbers. In your del function you forgot to use delete[] matrix[i]; instead of delete matrix[i];. A new[] needs a delete[]. Running example: https://godbolt.org/z/o34vncYor
71,767,545
71,777,790
OpenMP parallel loop much slower than regular loop
The whole program has been shrunk to a simple test: const int loops = 1e10; int j[4] = { 1, 2, 3, 4 }; time_t time = std::time(nullptr); for (int i = 0; i < loops; i++) j[i % 4] += 2; std::cout << std::time(nullptr) - time << std::endl; int k[4] = { 1, 2, 3, 4 }; omp_set_num_threads(4); time = std::time(nullptr); #pragma omp parallel for for (int i = 0; i < loops; i++) k[omp_get_thread_num()] += 2; std::cout << std::time(nullptr) - time << std::endl; In the first case it takes about 3 seconds to run through the loop, in the second case the result is inconsistent and may be 4 - 9 seconds. Both of the loops run faster with some optimization enabled (like favouring speed and whole program optimization), but the second loop is still significantly slower. I tried adding barrier at the end of the loop and explicitly specifying the array as shared, but that didn't help. The only case when I managed to make the parallel loop run faster is by making the loops empty. What may be the problem? Windows 10 x64, CPU Intel Core i5 10300H (4 cores)
As already pointed out in the various comments, the crux of your problem is false sharing. Indeed, your example is the typical case where one can experiment this. However, there are also quite a few issues in your code, such as: You will likely see overflows, both in your loops variable and in all of your j and k tables; Your timer isn't really the best choice ever (admittedly, that is a bit pedantic from my part in this case); You do not make use of the values you computed, which allows the compiler to completely ignore the various computations; Your two loops are not equivalent and won't give the same results; In order to get it right, I went back to your original i%4 formula and added a schedule( static, 1) clause. This is not a proper way of doing it, but it was only to get the expected results without using the correct reduction clause. Then I rewrote your example and also augmented it with what I believe is a better solution to the false sharing issue: using a reduction clause. #include <iostream> #include <omp.h> int main() { const long long loops = 1e10; long long j[4] = { 1, 2, 3, 4 }; double time = omp_get_wtime(); for ( long long i = 0; i < loops; i++ ) { j[i % 4] += 2; } std::cout << "sequential: " << omp_get_wtime() - time << std::endl; time = omp_get_wtime(); long long k[4] = { 1, 2, 3, 4 }; #pragma omp parallel for num_threads( 4 ) schedule( static, 1 ) for ( long long i = 0; i < loops; i++ ) { k[i%4] += 2; } std::cout << "false sharing: " << omp_get_wtime() - time << std::endl; time = omp_get_wtime(); long long l[4] = { 1, 2, 3, 4 }; #pragma omp parallel for num_threads( 4 ) reduction( +: l[0:4] ) for ( long long i = 0; i < loops; i++ ) { l[i%4] += 2; } std::cout << "reduction: " << omp_get_wtime() - time << std::endl; bool a = j[0]==k[0] && j[1]==k[1] && j[2]==k[2] && j[3]==k[3]; bool b = j[0]==l[0] && j[1]==l[1] && j[2]==l[2] && j[3]==l[3]; std::cout << "sanity check: " << a << " " << b << std::endl; return 0; } Compiling and running without optimizations gives on my laptop: $ g++ -O0 -fopenmp false.cc $ ./a.out sequential: 15.5384 false sharing: 47.1417 reduction: 4.7565 sanity check: 1 1 Which speaks for itself in regard to the improvement the reduction clause brings. Now, enabling optimizations from the compiler gives a more mitigated picture: $ g++ -O3 -fopenmp false.cc $ ./a.out sequential: 4.8414 false sharing: 4.10714 reduction: 2.10953 sanity check: 1 1 If anything, that shows that compilers are quite good at avoiding most of false sharing nowadays. Indeed, with your initial (erroneous) k[omp_get_thread_num()], there was no time difference with and without the reduction clause, showing that the compiler was able to avoid the issue.
71,767,599
71,767,745
no matching function for call to ‘std::exception::exception(<brace-enclosed initializer list>)
My project builds on Windows (vc++17) and I am new to Linux builds so I am not sure what is going on. I created CMakeLists files for my project (with a C++17 requirement), generated the makefile, and then I used make to try build it on Linux. The error is: /home/julien/source/zipfs/zipfs/include/zipfs/zipfs_assert.h:30:70: error: no matching function for call to ‘std::exception::exception(<brace-enclosed initializer list>)’ 30 | zipfs_usage_error_t(const char* message) : std::exception{ message } {} | ^ In file included from /usr/include/c++/9/exception:38, from /usr/include/c++/9/new:40, from /usr/include/c++/9/ext/new_allocator.h:33, from /usr/include/x86_64-linux-gnu/c++/9/bits/c++allocator.h:33, from /usr/include/c++/9/bits/allocator.h:46, from /usr/include/c++/9/string:41, from /home/julien/source/zipfs/zipfs/include/zipfs/zipfs_path_t.h:3, from /home/julien/source/zipfs/zipfs/include/zipfs/zipfs_error_t.h:3, from /home/julien/source/zipfs/zipfs/source/zipfs_error_t.cpp:1: The incriminated code is: zipfs_usage_error_t(const char* message) : std::exception{ message } {} I don't see what is wrong with this; is it a c++ version mismatch ?
std::exception does not provide a constructor that accepts a const char* parameter. If one exists on the Windows standard library you are using, it is a non-portable extension to the language. There are many derived classes that could be used as your base class instead, which do support this constructor.
71,768,643
71,769,027
what is stopping the random num generator from randomizing every time a player starts a new game?
{ int i,game = 0,guess,count = 0; int rando; srand (time(0)); rando = rand() % 50 + 1; cout << "****Welcome To The Game****\n"; cout << "1: Start the game\n"; cout << "2: End the game\n"; cin >> game; while (game != 2 && count != 11) { cout << "Enter a number between 1 and 50: "; cin >> guess; count++; if(guess == rando) { cout << "you got it!\n"; cout << "would you like to play again?\n"; cin >> game; } else if(guess < rando) { cout << "too low, try again " << endl; } else if(guess > rando) { cout << "Too high, try again" << endl; } if (count == 11) { cout << "too many guesses. the number was: " << rando << "." << endl; cout << "would you like to play again?\n"; cin >> game; } if (game == 2) { cout << "@@@ Thank you. See you next time.@@@\n"; } } return 0; } when I start the game, it generates a new number every time I run the program, but not when I ask to play again. I tried putting it in the while, but that messes up the code. how do I fulfill the second option in the first sentence?
int randomGame() { int gameMenuChoice = 0; srand(time(0)); std::cout << "****Welcome To The Game****\n"; std::cout << "1: Start the gameMenuChoice\n"; std::cout << "2: End the gameMenuChoice\n"; std::cin >> gameMenuChoice; while (gameMenuChoice != 2) { const int rando = rand() % 50 + 1; int guess = 0; for (int count = 0; count < 11 && guess != rando; ++count) { std::cout << "Enter a number between 1 and 50: "; std::cin >> guess; if (guess < rando) { std::cout << "too low, try again \n"; } else if (guess > rando) { std::cout << "Too high, try again\n"; } } if (guess == rando) { std::cout << "you got it!\n"; } else { std::cout << "too many guesses. the number was: " << rando << ".\n"; } std::cout << "would you like to play again?\n"; // I think people will enter Y for yes here. std::cin >> gameMenuChoice; } std::cout << "@@@ Thank you. See you next time.@@@\n"; return 0; } I have split you menu and game routine loops and simplified the logic a bit.
71,768,869
71,769,034
Polymorphic pointer change at run time
I am really confused about polymorphic pointers. I have 2 classes derived from an interface as shown below code. #include <iostream> using namespace std; class Base { public: virtual ~Base() { } virtual void addTest() = 0; }; class B: public Base { public: B(){} ~B(){} void addTest(){ cout << "Add test B\n"; } }; class C: public Base { public: C(){} ~C(){} void addTest(){ cout << "Add test C\n"; } private: void deleteTest(){ } }; int main() { Base *base = new B(); base->addTest(); base = new C(); base->addTest(); return 0; } I want to change the pointer dynamically according to a condition at run time to use the same pointer with different kinds of scenarios. Derived classes are different from each other, so what happens in memory when the polymorphic pointer object changes? If that usage is not good practice, how can I change the polymorphic pointer object dynamically at the run time?
It's perfectly fine to change what a pointer points to. A Base* is not an instance of Base, it is a pointer that points to an instance of a Base (or something derived from it -- in this case B or C). Thus in your code, base = new B() sets it to point to a new instance of a B, and then base = new C() sets it to point to a new instance of a C. Derived classes are different from each other, so what happens in memory when the polymorphic pointer object changes? Because Base* points to an instance of a Base, all this is doing is changing which instance (or derived instance) Base* points to. In effect, it just changes the memory address of the pointer. From that Base* pointer, you still have access to anything defined in that Base class -- which still allows polymorphic calls to functions satisfied by derived types if the function is defined as virtual. The exact mechanism for how this is dispatched to derived types is technically an implementation-detail of the language, but generally this is done through a process called double-dispatch, which uses a "V-Table". This is additional type-information stored alongside any classes that contain virtual functions (it's conceptually just a struct of function pointers, where the function pointers are satisfied by the concrete types). See: Why do we need a virtual table? for more information on vtables. What is problematic, however, is the use of new here. new allocates memory that must be cleaned up with delete to avoid a memory leak. By doing the following: Base *base = new B(); base->addTest(); base = new C(); // overwriting base without deleting the old instance base->addTest(); The B object's destructor is never run, no resources are cleaned up, and the memory for B itself is never reclaimed. This should be: Base *base = new B(); base->addTest(); delete base; base = new C(); // overwriting base without deleting the old instance base->addTest(); delete base; Or, better yet, this should be using smart-pointers like std::unique_ptr to do this for you. In which case you don't use new and delete explicitly, you use std::make_unique for allocation, and the destructor automagically does this for you: auto base = std::make_unique<B>(); base->addTest(); base = std::make_unique<C>(); // destroy's the old instance before reassigning base->addTest(); This is the recommended/modern way to write dynamic allocations
71,768,929
71,775,108
check boolean expression in dataframe Rcpp (C++)
I have a dataframe dat with data and a vector rule with logical rules set.seed(124) ro <- round(runif(n = 30,1,10),2) dat <- as.data.frame(matrix(data =ro,ncol = 3)) ; colnames(dat) <- paste0("x" ,1:ncol(dat)) rule <- c("x1 > 5 & x2/2 > 2" , "x1 > x2*2" , "x3!=4") I need to check if the expression is true id <- 2 for(i in 1:nrow(dat)){ cr <- with(data = dat[i,] , expr = eval(parse(text = rule[id]))) print(cr) } [1] FALSE [1] FALSE [1] FALSE [1] FALSE [1] FALSE [1] TRUE [1] FALSE [1] FALSE [1] FALSE [1] TRUE How to do this with Rcpp ?
Two things worth stressing here are you do not need a low over all rows as R is vectorized, and that already fast you can sweep the rules over your data and return a result matrix Both of those are a one-liner: > res <- do.call(cbind, lapply(rule, \(r) with(dat, eval(parse(text=r))))) > res [,1] [,2] [,3] [1,] FALSE FALSE TRUE [2,] FALSE FALSE TRUE [3,] TRUE FALSE TRUE [4,] FALSE FALSE TRUE [5,] FALSE FALSE TRUE [6,] FALSE TRUE TRUE [7,] TRUE FALSE TRUE [8,] TRUE FALSE TRUE [9,] TRUE FALSE TRUE [10,] FALSE TRUE TRUE > (I used the R 4.1.* anonymous function there, you can relace \(r) with the standard function(r) as well.) As this is already vectorised it will be faster than your per-row call, and even if you did it with Rcpp if would not be (much) faster than already vectorised code.
71,768,987
71,770,102
Type Punning via constexpr union
I am maintaining an old code base, that is using a union of an integer type with a bit-field struct for type-punning. My compiler is VS2017. As an example, the code is similar to the following: struct FlagsType { unsigned flag0 : 1; unsigned flag1 : 1; unsigned flag2 : 1; }; union FlagsTypeUnion { unsigned flagsAsInt; FlagsType flags; }; bool isBitSet(unsigned flagNum, FlagsTypeUnion flags) { return ((1u << flagNum) & flags.flagsAsInt); } This code has a number of undefined behavior issues. Namely, it is hotly debated whether type punning is defined behavior or not, but on top of that, the implementation of packing bit-fields is implementation-defined. To address these issues, I would like to add static-assert statements to validate that the VS implementation enables using this type of approach. However, when I tried to add the following code, I get error C2131: expression did not evaluate to a constant. union FlagsTypeUnion { unsigned flagsAsInt; FlagsType flags; constexpr FlagsTypeUnion(unsigned const f = 0) : flagsAsInt{ f } {} }; static_assert(FlagsTypeUnion{ 1 }.flags.flag0, "The code currently assumes bit-fields are packed from LSB to MSB"); Is there any way to add compile-time checks to verify the type-punning and bit-packing code works as the runtime code is assuming? Unfortunately, this code is spread throughout the code base, so changing the structures isn't really feasible.
You might use std::bit_cast (C++20): struct FlagsType { unsigned flag0 : 1; unsigned flag1 : 1; unsigned flag2 : 1; unsigned padding : 32 - 3; // Needed for gcc }; static_assert(std::is_trivially_constructible_v<FlagsType>); constexpr FlagsType makeFlagsType(bool flag0, bool flag1, bool flag2) { FlagsType res{}; res.flag0 = flag0; res.flag1 = flag1; res.flag2 = flag2; return res; } static_assert(std::bit_cast<unsigned>(makeFlagsType(true, false, false)) == 1); Demo clang doesn't support it (yet) though. gcc requires to add explicitly the padding bits for the constexpr check.
71,769,919
71,770,164
what does func() = var_name; assignment do in c++?
I was studying about l-values and r-values but I am confused with this: #include<iostream> int& get_val(){ return 10; } int main(){ get_val() = 5; int a = get_val(); std::cout<<a<<std::endl; return 0; } I know about int a = get_val(); (i.e., it will assign the returned value to the variable), but I want to know what this does: get_val() = 5;. What does int& get_val() do? I know we cannot run this code but I want to learn the concept behind this.
Your get_val function is defined as returning a reference to an integer; however, what you actually return is a reference to a constant, so any attempt to assign a value to that will not compile. In fact, the function itself (attempting to return a reference to 10) won't compile; clang-cl gives this: error : non-const lvalue reference to type 'int' cannot bind to a temporary of type 'int' However, if you add a static int1 inside your function, and return (a reference to) that, then you can use statements like getval() = x; to assign the value of x to that internal static int (which is otherwise 'invisible' outside the function). Here's a short demonstration: #include <iostream> int& get_val() { static int inside = 42; std::cout << inside << "\n"; return inside; } int main() { get_val() = 5; // Prints INITIAL value of "inside" then (after the call) assigns // the value 5 to it, via the returned reference get_val(); // Prints the modified value return 0; } The above example is trivial and would likely not serve any real-world purpose; it is purely for demonstration purposes. However, there may be cases where you would want a function to return a reference to any one of a number of different objects, depending on calculations and decisions made in that function; the selected, referenced object can then be suitably modified using code like that shown here. 1 The inside variable needs to be declared as static so that: Its lifetime does not end when the function returns (thus creating a dangling reference). Its value is maintained from one call to the next.
71,770,190
71,778,887
Implementing two pointer technique in sets in C++
I am trying to implement two pointer technique in sets in C++. I want to check if the difference of two elements of a set equals to a constant 'k'. void solve(int n,int k,set<int> s){ auto it_1 = s.begin(); auto it_2 = s.end(); while(it_1 < it_2){ if(*it_2 - *it_1 == k){ cout << "YES" << endl; return; } else if(*it_2 - *it_1 > k){ it_1++; } else{ it_2--; } } cout << "NO" << endl; return; } I get the following error:- error: no match for 'operator<' (operand types are 'std::_Rb_tree_const_iterator' and 'std::_Rb_tree_const_iterator') while(it_1 < it_2) I do know that the error is because I am comparing two pointers. How can I check whether the it_1 is behind it_2 ?
The problems with the iterators can be solved quickly. Simply use the != operator instead of < Do not start from the end-iterator, but one element before. Because the end-iterator points at past the last valid element. But, unfortunately the 2 pointer approach will not work, if you want to find a pair with a given delta. The reason for that is that you would increment one pointer too much, and the delta can never be reached. With summing up the values, it would work. Let us take your initial approach as an example fix the minor bugs and look at the output: #include <iostream> #include <set> void solve(int k, std::set<int>& s) { auto it_1 = s.begin(); auto it_2 = std::prev(s.end()); while (it_1 != it_2) { std::cout << *it_1 << ' ' << *it_2 << '\n'; if (*it_2 - *it_1 == k) { std::cout << "YES\n"; return; } else if (*it_2 - *it_1 > k) { it_1++; } else { it_2--; } } std::cout << "NO\n"; return; } int main() { std::set test{ 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 }; solve(8, test); } This will result in: 1 89 2 89 3 89 5 89 8 89 13 89 21 89 34 89 55 89 NO You see the problem. By the way, finding the sum is a typical use case for the 2 pointer approach. Then it will always work. The set is sorted. And we start with the min value at the beginning and the max value at the end. So building the first sum will give us the maximum possible sum. Then we move first the pointer with the small numbers, or depending of the sum, decrement the upper pointer. Example: #include <iostream> #include <set> void solve(int k, std::set<int>& s) { auto it_1 = s.begin(); auto it_2 = std::prev(s.end()); while (it_1 != it_2) { std::cout << *it_1 << ' ' << *it_2 << '\n'; if (*it_2 + *it_1 == k) { std::cout << "YES\n"; return; } else if (*it_2 + *it_1 < k) { it_1++; } else { it_2--; } } std::cout << "NO\n"; return; } int main() { std::set test{ 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 }; solve(8, test); } Output: 1 89 1 55 1 34 1 21 1 13 1 8 1 5 2 5 3 5 YES But how to solve the delta problem? What will always work is brute forcing. This will lokk like: #include <iostream> #include <set> void solve(int k, std::set<int>& s) { auto it_1 = s.begin(); auto it_2 = std::next(s.begin()); while ((it_1 != s.end()) and (it_2 != s.end())) { std::cout << *it_1 << ' ' << *it_2 << '\n'; if ((it_1 != it_2) and ((*it_2 - *it_1 == k) or (*it_1 - *it_2 == k))) { std::cout << "YES\n"; return; } else if (*it_2 - *it_1 < k) ++it_2; else ++it_1; } std::cout << "NO\n"; return; } int main() { std::set test{ 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 }; solve(8, test); } With the following output: 1 2 1 3 1 5 1 8 1 13 2 13 3 13 5 13 YES A little bit optimized opproach would use a std::unordered_map. But maybe this is too much for here.
71,770,439
71,771,023
c++ arduino multiple display objects in a structured array
I have declarations for multiple OLED displays running via an 8 channel i2c Mux: Adafruit_SSD1306 display1(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire2, OLED_RESET); Adafruit_SSD1306 display2(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire2, OLED_RESET); Adafruit_SSD1306 display3(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire2, OLED_RESET); Adafruit_SSD1306 display4(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire2, OLED_RESET); Adafruit_SSD1306 display5(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire2, OLED_RESET); I want to be able to access these using an identifier like this: display[0].print("etc"); display[1].print("etc"); display[2].print("etc"); so I can then call a function like this: sendTitleDisplay(1); void sendTitleDisplay(uint8_t id) { display[id].print("title example"); } How would i define these objects so I can access them in this array format?
You could initialize your array like this: Adafruit_SSD1306 display[]{ {SCREEN_WIDTH, SCREEN_HEIGHT, &Wire2, OLED_RESET}, {SCREEN_WIDTH, SCREEN_HEIGHT, &Wire2, OLED_RESET}, {SCREEN_WIDTH, SCREEN_HEIGHT, &Wire2, OLED_RESET}, {SCREEN_WIDTH, SCREEN_HEIGHT, &Wire2, OLED_RESET}, {SCREEN_WIDTH, SCREEN_HEIGHT, &Wire2, OLED_RESET}, }; This would use the first of the new recommended constructors for each of the Adafruit_SSD1306 instances, with clkDuring using the default value 400000UL and clkAfter using the default value 100000UL. // NEW CONSTRUCTORS -- recommended for new projects Adafruit_SSD1306(uint8_t w, uint8_t h, TwoWire *twi = &Wire, int8_t rst_pin = -1, uint32_t clkDuring = 400000UL, uint32_t clkAfter = 100000UL); Adafruit_SSD1306(uint8_t w, uint8_t h, int8_t mosi_pin, int8_t sclk_pin, int8_t dc_pin, int8_t rst_pin, int8_t cs_pin); Adafruit_SSD1306(uint8_t w, uint8_t h, SPIClass *spi, int8_t dc_pin, int8_t rst_pin, int8_t cs_pin, uint32_t bitrate = 8000000UL); // DEPRECATED CONSTRUCTORS - for back compatibility, avoid in new projects Adafruit_SSD1306(int8_t mosi_pin, int8_t sclk_pin, int8_t dc_pin, int8_t rst_pin, int8_t cs_pin); Adafruit_SSD1306(int8_t dc_pin, int8_t rst_pin, int8_t cs_pin); Adafruit_SSD1306(int8_t rst_pin = -1);
71,770,724
71,771,036
Generating simple format string at compile time
I'm trying to generate a simple format string for fmt at compile time, but I can't quite figure out the string concatenation. I'm limited to c++ 14. What I'd like is to be able to generate a format string for N items, so it could be used as follows: auto my_string = fmt::format(format_string_struct<2>::format_string, "Item", "key1", "value1", "key2", "value2"); The generated format string would be: "{} {}={} {}={}", resulting in a formatted string of "Item key1=value1 key2=value2". The base of the format string would be "{}", and it appends a " {}={}" for each N. I'm trying to use recursive templates, but I just can't quite get everything to work. I got some code from Concatenate compile-time strings in a template at compile time? for concatenating strings (though I get a undefined reference to `concat_impl<&base_format_string_struct::format_string, std::integer_sequence<int, 0, 1>, &format_string_parameter_struct::parameter_string, std::integer_sequence<int, 0, 1, 2, 3, 4, 5, 6, 7> >::value' error) template<int...I> using is = std::integer_sequence<int,I...>; template<int N> using make_is = std::make_integer_sequence<int,N>; constexpr auto size(const char*s) { int i = 0; while(*s!=0){++i;++s;} return i; } template<const char*, typename, const char*, typename> struct concat_impl; template<const char* S1, int... I1, const char* S2, int... I2> struct concat_impl<S1, is<I1...>, S2, is<I2...>> { static constexpr const char value[] { S1[I1]..., S2[I2]..., 0 }; }; template<const char* S1, const char* S2> constexpr auto concat { concat_impl<S1, make_is<size(S1)>, S2, make_is<size(S2)>>::value }; struct base_format_string_struct { static constexpr const char format_string[] = "{}"; }; struct format_string_parameter_struct { static constexpr const char parameter_string[] = " {}=\"{}\""; }; template <int arg_count, const char[]... params> struct format_string_struct: public format_string_struct<arg_count - 1, format_string_parameter_struct, params...> { }; template <int arg_count> struct format_string_struct: public format_string_struct<arg_count - 1, format_string_parameter_struct> { }; template <const char[]... params> struct format_string_struct<0> { static const char* format_string() { return concat<base_format_string_struct, params...>; } };
You have several typos (and a concat limited to 2 argument). template<int...I> using is = std::integer_sequence<int,I...>; template<int N> using make_is = std::make_integer_sequence<int,N>; constexpr auto size(const char*s) { int i = 0; while(*s!=0){++i;++s;} return i; } template<const char*, typename, const char*, typename> struct concat_impl; template<const char* S1, int... I1, const char* S2, int... I2> struct concat_impl<S1, is<I1...>, S2, is<I2...>> { static constexpr const char value[] { S1[I1]..., S2[I2]..., 0 }; }; template<const char* S1, const char* S2, const char*... Ss> struct concat { constexpr static const char* value = concat_impl<S1, make_is<size(S1)>, concat<S2, Ss...>::value, make_is<size(concat<S2, Ss...>::value)>>::value; }; template<const char* S1, const char* S2> struct concat<S1, S2> { constexpr static const char* value = concat_impl<S1, make_is<size(S1)>, S2, make_is<size(S2)>>::value; }; struct base_format_string_struct { static constexpr const char format_string[] = "{}"; }; struct format_string_parameter_struct { static constexpr const char parameter_string[] = " {}=\"{}\""; }; template <int arg_count, const char*... params> struct format_string_struct: public format_string_struct<arg_count - 1, format_string_parameter_struct::parameter_string, params...> { }; template <int arg_count> struct format_string_struct<arg_count>: public format_string_struct<arg_count - 1, format_string_parameter_struct::parameter_string> { }; template <const char*... params> struct format_string_struct<0, params...> { static const char* format_string() { return concat<base_format_string_struct::format_string, params...>::value; } }; Demo But I would probably go with constexpr functions: #if 1 // missing some constexpr for std::array/std::copy template <typename T, std::size_t N> struct my_array { T data[N]; }; template <typename CIT, typename IT> constexpr void copy(CIT begin, CIT end, IT dest) { for (CIT it = begin; it != end; ++it) { *dest = *it; ++dest; } } #endif template <std::size_t N> constexpr my_array<char, 2 + 8 * N + 1> format_string_struct_impl() { my_array<char, 2 + 8 * N + 1> res{}; constexpr char init[] = "{}"; // size == 2 constexpr char extra[] = R"( {}="{}")"; // size == 8 copy(init, init + 2, res.data); for (std::size_t i = 0; i != N; ++i) { copy(extra, extra + 8, res.data + 2 + i * 8); } return res; } template <std::size_t N> constexpr my_array<char, 2 + 8 * N + 1> format_string_struct() { // Ensure the computation is done compile time. constexpr auto res = format_string_struct_impl<N>(); return res; } Demo
71,771,147
71,771,211
Why does my DLL not require a DllMain function?
I just added a C++ Windows DLL project to a Visual Studio (2022) solution. The wizard put a DllMain in there. That jumped out at me; I didn't remember my other DLLs having DllMain functions; Searching my code, it turns out that none of my 9 DLLs have DllMain functions. Yet they all build and work fine. I checked the project settings for all of these projects: None of them have the linker /NOENTRY option set. They all have /SUBSYSTEM:WINDOWS set. None of them have the linker /NODEFAULTLIB option set They are certainly all DLLS. So I commented out that DllMain in the new project I just added. It still built just fine. My knowledge is clearly out of date. I thought a DllMain used to be required. I remember years ago getting linker errors in my DLLs when I failed to add a DllMain. So my questions are: Why do my DLLs not require DllMain? Is there some build setting I did not check? Is there any downside to not having one? (Note that these DLLS all export C++ classes. None of them are resource DLLs. All have been working fine for 6 years. Some of them use thread-local storage. Some of them have static variables inside of functions. I always thought that using things like these necessitated a DllMain)
The runtime library ("CRT" = C/C++ Runtime Library) provides the real DLL entry point _DllMainCRTStartup, that does things like initializing global variables before calling your DllMain. There's documentation on MSDN that describes this: DLLs and Visual C++ run-time library behavior Documentation of the linker /ENTRY option is also relevant: /ENTRY (Entry-Point Symbol) There's also a library-provided weak symbol for your DllMain, so the call from the real entrypoint to DllMain doesn't fail at link time with an unresolved external. From the first document above: By default, if you do not provide a DllMain function, Visual Studio provides one for you and links it in so that _DllMainCRTStartup always has something to call. The things you mentioned like thread-local storage do require using the library-provided entrypoint; they'll break if you use the /ENTRY option to link.exe to replace the library entrypoint with your own or /NOENTRY to disable it. None of them require anything to be done by the DllMain that the library entrypoint calls.