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,645,516
71,646,043
C++ std::fstream how to move to a certain line and column of a file
So I have been searching on how to move to a certain line and column in a file , but I can't seem to find an answer . I want something like this : std::fstream file("example.txt"); file.move_to( line number , column number );
The following function can do just you want: std::string GetLine(std::istream& fs, long long index) { std::string line; for (size_t i = 0; i <= index; i++) { std::getline(fs, line); } return line; } The above function gets the line at index (index == 0 - 1st line, index == 2 - 3rd line, etc.). Usage: #include <iostream> #include <string> #include <fstream> std::string GetLine(std::istream& fs, long long index) { std::string line; for (size_t i = 0; i <= index; i++) { std::getline(fs, line); } return line; } int main() { std::ifstream fs("input.txt"); // fstream works too std::cout << GetLine(fs, 1); } input.txt This is a test file Output: a
71,646,113
71,648,684
C++ with OpenMP try to avoid the false sharing for tight looped array
I try to introduce OpenMP to my c++ code to improve the performance using a simple case as shown: #include <omp.h> #include <chrono> #include <iostream> #include <cmath> using std::cout; using std::endl; #define NUM 100000 int main() { double data[NUM] __attribute__ ((aligned (128)));; #ifdef _OPENMP auto t1 = omp_get_wtime(); #else auto t1 = std::chrono::steady_clock::now(); #endif for(long int k=0; k<100000; ++k) { #pragma omp parallel for schedule(static, 16) num_threads(4) for(long int i=0; i<NUM; ++i) { data[i] = cos(sin(i*i+ k*k)); } } #ifdef _OPENMP auto t2 = omp_get_wtime(); auto duration = t2 - t1; cout<<"OpenMP Elapsed time (second): "<<duration<<endl; #else auto t2 = std::chrono::steady_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count(); cout<<"No OpenMP Elapsed time (second): "<<duration/1e6<<endl; #endif double tempsum = 0.; for(long int i=0; i<NUM; ++i) { int nextind = (i == 0 ? 0 : i-1); tempsum += i + sin(data[i]) + cos(data[nextind]); } cout<<"Raw data sum: "<<tempsum<<endl; return 0; } Access to a tightly looped int array (size = 10000) and change its elements in either parallel or non-parallel way. Build as g++ -o test test.cpp or g++ -o test test.cpp -fopenmp The program reported results as: No OpenMP Elapsed time (second): 427.44 Raw data sum: 5.00009e+09 OpenMP Elapsed time (second): 113.017 Raw data sum: 5.00009e+09 Intel 10th CPU, Ubuntu 18.04, GCC 7.5, OpenMP 4.5. I suspect that the false sharing in the cache line leads to the bad performance of the OpenMP version code. I update the new test results after increasing the loop size, the OpenMP runs faster as expected. Thank you!
Since you're writing C++, use the C++ random number generator, which is threadsafe, unlike the C legacy one you're using. Also, you're not using your data array, so the compiler is actually at liberty to remove your loop completely. You should touch all your data once before you do the timed loop. That way you ensure that pages are instantiated and data is in or out of cache depending. Your loop is pretty short.
71,646,233
71,646,450
selecting a move-constructor in a lambda-captured object
As a test, a class has the copy-constructor defined and the move-constructor explicitly deleted so that an object cannot be move-constructed. struct foo { foo()=default; foo(const foo&) { std::cout << "foo copied\n"; } foo(foo&&)=delete; }; foo f; foo a = f; // ok foo b = move(f); // fails (expected) It is my understanding that when a move-constructor is explicitly deleted, its declaration is still around for the overload process and that's why foo b cannot be constructed. With only the copy-constructor defined, the move-constructor would not be declared and the copy-constructor const foo& argument would accept the rvalue. However, when I put the object in a lambda, it compiles: foo f; auto lmb = [f]() { }; // f copied into the closure object auto x = std::move(lmb); The lambda is cast to an rvalue, but the object it holds is still copied (per the output). (When the foo move-constructor is defined, it is called, as expected). Question: why is the (deleted) foo move-constructor not selected (so that it fails to compile) ?
Question: why is the (deleted) foo move-constructor not selected (so that it fails to compile) ? Because the lambda's definition is defaulted and not explicitly deleted, therefore overload resolution is tuned to ignore it. [over.match.funcs.general] 8 A defaulted move special member function ([class.copy.ctor], [class.copy.assign]) that is defined as deleted is excluded from the set of candidate functions in all contexts. It's hard-coded into the language since C++11 and move semantics being introduced. Otherwise, older code that was written prior to move operations being available (and that would have had the move operations implicitly deleted) would silently break on upgrade. Bad.
71,646,288
71,646,322
Null pointer check via "myPtr > 0"
In some legacy code I came across the following null pointer check. if( myPtr > 0 ) { ... } Are there any technical risks of checking for a null pointer via this if-check?
Ordered comparison between a pointer and an integer is ill-formed in C++ (even when the integer is a null pointer constant such as it is in this case). The risk is that compilers are allowed to, and do, refuse to compile such code. You can rewrite it as either of these: if(myPtr != nullptr) if(myPtr)
71,646,883
71,646,999
Why were parentheses disambiguated as a function declaration with std::istream_iterator?
auto queue = [](string str) { istringstream ss(str); //std::copy(std::istream_iterator<string>(ss), // std::istream_iterator<string>(), // std::ostream_iterator<string>(std::cout, " ")); //deque<string> q(std::istream_iterator<string>(ss), std::istream_iterator<string>{}); deque<string> q(std::istream_iterator<string>(ss), std::istream_iterator<string>()); return q; }; Why would the compiler complain parentheses were disambiguated as a function declaration [-Wvexing-parse] if I construct a container with istream_iterator<string>(). Is there any difference with parameters in std::copy and container constructor?
This line deque<string> q(std::istream_iterator<string>(ss), std::istream_iterator<string>()); is a function declaration with the return type deque<string> and two parameters of the type std::istream_iterator<string>. The first parameter has the name ss and the second parameter is unnamed. To make this line a declaration of the variable q you should write either deque<string> q( ( std::istream_iterator<string>(ss) ), ( std::istream_iterator<string>() ) ); or deque<string> q(std::istream_iterator<string>{ ss }, std::istream_iterator<string>{}); In this case there are used expressions instead of parameter declarations. You may include declarators in parentheses. For example int ( x ); When a declaration is a parameter declaration then you may omit a declarator like int() Here is an example of three declarations of the same function. int f( int( x ) ); int f( int x ); int f( int( x ) ) { return 2 * x; }
71,647,043
71,650,683
Wrong value for the last element of the array c++
I am trying to make an array (in this case int b[]) that stores all numbers that are larger than their neighbor, int a[10] are all the elements. I'm getting everything put out correctly only the last element is some random large number do you guys have any ideas? Concole everything is alright except the #include <iostream> using namespace std; int main() { int n; cout << "how many elements do you want "; cin >> n; int a[10]; int b[10]; for (int i = 0; i < n; i++) cin >> a[i]; cout << endl; int c = 0; for (int i = 0; i < n; i++) { if (a[0] > a[1] && i == 0) { swap(a[0], b[0]); c++; } if (a[i] > a[i + 1] && a[i] > a[i - 1] && i != 0 && i != n) { swap(a[i], b[c]); c++; } { if (a[n] > a[n - 1] && i == n - 1) { swap(a[n], b[c]); c++; } } } for (int i = 0; i < c; i++) cout << b[i] << endl; }
In your code when you get the number of inputs the array indexes will be from 0 to n-1 so the last index is n-1 but if you look at this if statement: if (a[n] > a[n - 1] && i == n - 1) { swap(a[n], b[c]); c++; } you have used a[n] as the last array index and because a[n] wasn't initialized we don't know what number is stored in it and the random number in your output has come from this index. #include <iostream> using namespace std; int main() { int n; cout << "how many elements do you want "; cin >> n; int a[10]; int b[10]; for (int i = 0; i < n; i++) cin >> a[i]; cout << endl; int c = 0; for (int i = 0; i < n; i++) { if (a[0] > a[1] && i == 0) { swap(a[0], b[0]); c++; } if (a[i] > a[i + 1] && a[i] > a[i - 1] && i != 0 && i != n -1) { swap(a[i], b[c]); c++; } if (a[n-1] > a[n - 2] && i == n - 1) { swap(a[n], b[c]); c++; } } for (int i = 0; i < c; i++) cout << b[i] << endl; } the above code prints the right output.
71,647,356
71,647,864
How to implement zero-overhead Inversion of Control
Almost every OOP programmer has been exposed to the concept of Inversion of control. In C++, we can implement that principle with dynamic callbacks (i.e. functors such as lambdas and function pointers). But if we know at compile time what procedure we are to inject into the driver, theoretically I believe that there is a way to eliminate the overhead of function passing and invoking by composing the callbacks and the driver/signal/what-so-ever function into an "unrolled procedure". Here is an example. For a GUI program, we have logic on window 1) setup, 2) loop, and 3) termination. We can inject code 1) after window setup, 2) in each render loop, 3) and before termination. A procedural approach is to write in this manner: // Snippet 1: init_window(); init_input_handler(); init_canvas(); init_socket(); while (!window_should_close()) { update_window(); handle_input(); draw_on_canvas(); send_through_socket(); } drop_input_handler(); drop_canvas(); drop_socket(); terminate_window(); OOP programmers pride ourselves in decoupling and proper abstraction. Instead, we write this: // Snippet 2: init_window(); on_window_init_signal.send(); while (!window_should_close()) { update_window(); on_render_signal.send(); } on_exit_signal.send(); terminate_window(); But this brings an unwanted overhead as said above. My question is: How can we utilize the C++ metaprogramming mechanisms to achieve zero-overhead inversion of control so that code in a similar form of snippet 2 can be transformed into snippet 1 statically (i.e. at compile time)? EDIT: I can think of loop optimizations widely found in optimizers. Maybe this is a generalized version of that issue.
"Zero Overhead" & "But if we know at compile time what procedure we are to inject into the driver, " is possible. You can use a template class to pass the functions to call like that: struct SomeInjects { static void AtInit() { std::cout << "AtInit from SomeInjects" << std::endl; } static void AtHandleInput() { std::cout << "AtHandleInput from SomeInjects" << std::endl; } static void AtDraw() { std::cout << "AtDraw from SomeInjects" << std::endl; } }; struct OtherInject { static void AtInit() { std::cout << "AtInit from OtherInject" << std::endl; } static void AtHandleInput() { std::cout << "AtHandleInput from OtherInject" << std::endl; } static void AtDraw() { std::cout << "AtDraw from OtherInject" << std::endl; } }; template < typename Mixin > struct Win { void Init() { Mixin::AtInit(); } void HandleInput() { Mixin::AtHandleInput(); } void Draw() { Mixin::AtDraw(); } }; int main() { Win<SomeInjects> wsi; wsi.Init(); wsi.HandleInput(); wsi.Draw(); Win<OtherInject> wso; wso.Init(); wso.HandleInput(); wso.Draw(); } But this has the drawback, that it needs static functions. More elaborated try: struct SomeInjects { void AtInit() { std::cout << "AtInit from SomeInjects" << std::endl; } void AtHandleInput() { std::cout << "AtHandleInput from SomeInjects" << std::endl; } void AtDraw() { std::cout << "AtDraw from SomeInjects" << std::endl; } }; struct OtherInject { void AtInit() { std::cout << "AtInit from OtherInject" << std::endl; } void AtHandleInput() { std::cout << "AtHandleInput from OtherInject" << std::endl; } void AtDraw() { std::cout << "AtDraw from OtherInject" << std::endl; } }; template < typename Mixin > struct Win: Mixin { void Init() { this->AtInit(); } void HandleInput() { this->AtHandleInput(); } void Draw() { this->AtDraw(); } }; int main() { Win<SomeInjects> wsi; wsi.Init(); wsi.HandleInput(); wsi.Draw(); Win<OtherInject> wso; wso.Init(); wso.HandleInput(); wso.Draw(); } The last technique is called Mixin. If your compiler inlines all and everything depends on many things. But typically all calls are inlined if the called functions are not really to big. But if you need any runtime changeable callbacks, you have to use some kind of callable representation. That can be function pointers or things like std::function. The last generates more or less always some minor overhead. But remember: A simple dereferenced pointer is typically not the speed problem at all. More important is, that in such cases constants can not be propagated, the code can't be inlined and as a result an overall optimization is not longer possible. But if runtime flexibility is needed, it will have some cost. As always: Measure before optimize!
71,647,793
71,667,289
Eigen static lib aligned_free "double free or corruption"
This is a continuation of an earlier post. But this time with a hopefully better example. This simple test crashes when setting a vector. I am using Ubuntu 20.04, gcc 9.3.0, c++17, eigen 3.3.7 main.cpp #include <iostream> #include <memory> #include "C.h" using namespace std; class B { public: C c; B() { cout << (uint64_t)this << endl; } ~B(){} }; int main() { shared_ptr<B> b = make_shared<B>(); b->c.v = VectorXd(5); // << crashes here // SIGABRT on `Eigen::internal::aligned_free` when trying to do `std::free()` return 0; } Class C is linked as a static library. The static library is compiled in Release mode (--std=c++17 -DNDEBUG -O3), while the main program is run in Debug - without optimizations. If both the static lib and the main program are run in Debug, then there is no crash. Also, if they are both run in Release, there is no crash. The problem only occurs when the static lib is compiled in Release and the main program in Debug. C.h #pragma once #include <vector> #include <Eigen/Core> using namespace std; using namespace Eigen; class C { public: VectorXd v; C(); ~C(); }; C.cpp #include "C.h" C::C() { v = VectorXd(5); } C::~C() { }
In case you compiled the library and the main executable with mismatching architecture flags (-m... flags for gcc), you can observe the crash. For example, when I compile the library with avx enabled (-mavx) and the main executable without avx, or vice versa, it crashes. The crash also occurs in Eigen 3.4.0. Moreover, it also occurs without optimization (-O0). The Eigen aligned_malloc() and aligned_free() functions are doing different things depending on the value of the EIGEN_DEFAULT_ALIGN_BYTES macro, which has a different value when e.g. AVX (among others) is enabled or disabled. Eigen automatically selects the proper value depending on the used compiler flags. So, if you enable AVX only in the static library, the constructor of C uses handmade_aligned_malloc() internally, which is not returning the pointer received by malloc() directly but instead moves it a bit to ensure proper alignment. On the other hand, assigning a new value to C::v from the executable (which is compiled without AVX) will first try to free the memory by calling b->c.v.~VectorXd(), which then ends up calling just free() instead of handmade_aligned_free(). Thus, free() receives an address that does not point to the start of the allocated memory, which then causes the crash. Of course, if you enable AVX in the executable and disable it in the library, you get mismatching calls to malloc() and handmade_aligned_free() instead, also resulting in a crash. The solution is simple: Ensure that you compile the static library and the executable with the same architecture flags. If for whatever reason this is not possible, ensure that creation and destruction always happens in the same component. For example, you could make C::v private and allow modification of it only via functions that are implemented in the C.cpp file. Note: Your other post is a bit different since it involves no dynamic memory management, while in the present post you use VectorXd which does use dynamic memory management. Note 2: The described problem is unrelated to the use of std::shared_ptr. But for Eigen versions before 3.4.0 you might need to use EIGEN_MAKE_ALIGNED_OPERATOR_NEW to ensure that the pointer b is properly aligned, regardless of the architecture and C++17; at least the original Eigen issue was implemented only for 3.4.0. But I might be wrong on this.
71,647,916
71,648,015
Does “M&M rule” applies to std::atomic data-member?
"Mutable is used to specify that the member does not affect the externally visible state of the class (as often used for mutexes, memo caches, lazy evaluation, and access instrumentation)." [Reference: cv (const and volatile) type qualifiers, mutable specifier] This sentence made me wonder: "Guideline: Remember the “M&M rule”: For a member-variable, mutable and mutex (or atomic) go together." [Reference: GotW #6a Solution: Const-Correctness, Part 1 (updated for C ++11/14)] I understand why “M&M rule” applies to std::mutex data-member: to allow const-functions to be thread-safe despite they lock/unlock the mutex data-member, but does “M&M rule” applies also to std::atomic data-member?
You got it partly backwards. The article does not suggest to make all atomic members mutable. Instead it says: (1) For a member variable, mutable implies mutex (or equivalent): A mutable member variable is presumed to be a mutable shared variable and so must be synchronized internally—protected with a mutex, made atomic, or similar. (2) For a member variable, mutex (or similar synchronization type) implies mutable: A member variable that is itself of a synchronization type, such as a mutex or a condition variable, naturally wants to be mutable, because you will want to use it in a non-const way (e.g., take a std::lock_guard) inside concurrent const member functions. (2) says that you want a mutex member mutable. Because typically you also want to lock the mutex in const methods. (2) does not mention atomic members. (1) on the other hand says that if a member is mutable, then you need to take care of synchronization internally, be it via a mutex or by making the member an atomic. That is because of the bullets the article mentions before: If you are implementing a type, unless you know objects of the type can never be shared (which is generally impossible), this means that each of your const member functions must be either: truly physically/bitwise const with respect to this object, meaning that they perform no writes to the object’s data; or else internally synchronized so that if it does perform any actual writes to the object’s data, that data is correctly protected with a mutex or equivalent (or if appropriate are atomic<>) so that any possible concurrent const accesses by multiple callers can’t tell the difference. A member that is mutable is not "truly const", hence you need to take care of synchronization internally (either via a mutex or by making the member atomic). TL;DR: The article does not suggest to make all atomic members mutable. It rather suggests to make mutex members mutable and to use internal synchronization for all mutable members.
71,647,993
71,648,455
Why does malloc produce seg fault when accessing a member reference from C++ struct?
Consider the following code example: #include <iostream> struct Foo { int x = 2; int &rx = x; }; int main() { Foo *f1 = new Foo[4]; std::cout<< f1[0].rx <<std::endl; //ok Foo *f2 = (Foo*) malloc (4 * sizeof(Foo)); std::cout<< f2[0].rx <<std::endl; //memory leak free(f2); delete [] f1; } When new is used to allocate memory, the member reference rx is accessed normally and the correct value is printed. However, when malloc is used, accessing the member reference produces a segmentation fault. Can you please explain why? I suspect a collision of C vs C++ implementation, but I'm not sure. I ran the code with an address sanitizer which produced the following output: ASAN:SIGSEGV ================================================================= ==32515==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x00000048cb69 sp 0x7ffea3d6bf40 bp 0x7ffea3d6bf70 T0) #0 0x48cb68 in main /home/.../Desktop/test.cpp:15 #1 0x7f9861fb1544 in __libc_start_main (/lib64/libc.so.6+0x22544) #2 0x405578 (/home/.../Desktop/a.out+0x405578) AddressSanitizer can not provide additional info. SUMMARY: AddressSanitizer: SEGV /home/.../Desktop/test.cpp:15 main ==32515==ABORTING
The reason of the SEGV is because the new operator calls the class default constructor, it is where the initialization of the non-static data members is done, in this case setting x to 2 and rx to x. When you allocate the memory with malloc the default constructor is not called. So the SEGV rises because rx is never set to point to x, it is an undefined behavior. You have to call the default constructor explicitly, with "new(f2) Foo", it is called placement new operator. #include <iostream> #include <malloc.h> struct Foo { int x = 2; int &rx = x; }; int main() { Foo *f1 = new Foo[4]; std::cout<< f1[0].rx <<std::endl; //ok Foo *f2 = (Foo*) malloc (4 * sizeof(Foo)); new(f2) Foo; std::cout<< f2[0].rx <<std::endl; //memory leak free(f2); delete f1; } Here the placement new operator doesn't allocate memory it only calls the default constructor for the memory object allocated with malloc. Now the result is what you expect. 2 2
71,648,068
71,648,259
Is there a C++ smart pointer that could wrap up an object to make it thread safe?
I wanted to ask if there is a smart pointer that could take in any class in its template and then any operations done with such pointer would result in a thread-safe operation. Basically an idea would be that such pointer would automatically hold an internal lock during a scope and release it when the pointer goes out of scope. Use case would be for example to pull such pointer from a static, pre-allocated array into some scope and perform thread-safe operations inside that scope on the object itself. I tried to find a C++ library/feature that could perhaps allow for some thread-safe mutation on objects by wrapping it into a single smart pointer object.
if there is a smart pointer that could take in any class in its template and then any operations done with such pointer would result in a thread-safe operation. No, there is no such smart pointer in the C++ standard.
71,648,632
71,648,725
Iterator becomes nvalid
ALL, std::vector<string>::iterator it; string orig; bool found = false; for( it = vec.begin(); it < vec.end() && !found; it++ ) { if( ... ) { found = true; orig = (*it); } } After I get out of the loop the iterator become invalid even if I have found = true. How do I keep the iterator? I need it for later processing.. MSVC 2017, Windows 8.1 TIA!!!
You could decrement it in the case you found it, to undo the final it++ that you don't want. if (found) it--; Or you could use std::find_if, where ... uses value instead of *it. auto it = std::find_if(vec.begin(), vec.end(), [](std::string & value) ( return value.find("abc"); }); auto found = it != vec.end(); auto orig = *it;
71,648,813
71,659,387
How to set a text filter for boost log?
Starting from a logging set-up with a single logging file, a second logging file should be added containing only the lines with a specific text in the message. Example: In the single logging file: "user a logged in" "user b logged in" "user a logged out" In the second logging file only the messages of user b should be include: "user b logged in" Without the code creating the logging being impacted, example: BOOST_LOG_TRIVIAL(debug) << "user " << user << " logged in"; I am searching for a solution which filters on the message in the logging class. I have got this working, however I do not succeed to get this working with a parameter. // Main logging file g_file_sink = logging::add_file_log ( keywords::file_name = "General.%3N", keywords::format = "[%TimeStamp%] [%Severity%] %Message%", keywords::open_mode = (std::ios::out | std::ios::app), keywords::auto_flush = true, keywords::rotation_size = 1024, ); // Second logging file std::string text = "user a"; // define the filter logging::filter flt = [] (std::string text) { std::stringstream ss; ss << expr::smessage; std::string message = ss.str(); return (message.find(text) == std::string::npos); }; g_file1_sink = logging::add_file_log ( keywords::file_name = test + ".%3N", keywords::format = "[%TimeStamp%] [%Severity%] %Message%", keywords::open_mode = (std::ios::out | std::ios::app), keywords::auto_flush = true, keywords::filter = flt, keywords::rotation_size = 1024, ); // Main filter logging::core::get()->set_filter ( logging::trivial::severity >= logging::trivial::warning ); logging::add_common_attributes(); When I hardcode the "text" // define the filter logging::filter flt = [] () { std::stringstream ss; ss << expr::smessage; std::string message = ss.str(); return (message.find("user a") == std::string::npos); }; It is working as wanted, as soon I add variable text, I am getting a compiler error on the interface. Is there a way, without have to change the calling code?
You cannot apply filters to log record message text because message text is composed after the filtering is done. This is intentional, as this allows to avoid composing the text if the log record is to be discarded anyway. If you want to filter log records pertaining to a specific user, the way to do this is to use attributes. For example, you can put the user name in a constant attribute and then apply a filter to that attribute. Depending on your code design, the attribute can be added to a logger or to the current thread (e.g. when user-specific activity is confined in a fixed set of threads). You can also use scoped attributes if user-specific activity is only performed in a given scope. // Define attribute keyword BOOST_LOG_ATTRIBUTE_KEYWORD(a_username, "Username", std::string) void init_logging() { // Main logging file g_file_sink = logging::add_file_log ( keywords::file_name = "General.%3N", keywords::format = "[%TimeStamp%] [%Severity%] %Message%", keywords::open_mode = (std::ios::out | std::ios::app), keywords::auto_flush = true, keywords::rotation_size = 1024 ); // Second logging file g_file1_sink = logging::add_file_log ( keywords::file_name = "A.%3N", keywords::filter = a_username == "A", keywords::format = "[%TimeStamp%] [%Severity%] %Message%", keywords::open_mode = (std::ios::out | std::ios::app), keywords::auto_flush = true, keywords::rotation_size = 1024 ); // Main filter logging::core::get()->set_filter ( logging::trivial::severity >= logging::trivial::warning ); logging::add_common_attributes(); } int main() { init_logging(); // Create a logger that will emit log records not related to any specific user boost::log::severity_logger< boost::log::trivial::severity_level > lg; BOOST_LOG_SEV(lg, boost::log::trivial::warning) << "Log record with no username"; // Create a logger that will emit log records pertaining to user A boost::log::severity_logger< boost::log::trivial::severity_level > lg_a; lg_a.add_attribute(a_username.get_name(), boost::log::attributes::make_constant(std::string("A"))); BOOST_LOG_SEV(lg_a, boost::log::trivial::warning) << "Log record related to user A"; } Note that you can use attributes in the formatter as well. This way you could mark all records associated with a given user in the output.
71,648,817
71,649,016
How to call libjpeg API in an erroneous way?
I want to test my error handling code when using the libjpeg but I cannot find a suitable call which to produce an error. If I simply pass a nullptr to some of the calls expecting a pointer to a structure then the library just crashes. I want to find a statement that calls the set in the jpeg_error_mgr's error_exit function.
I managed to produce an error when calling libjpeg's functions on jpeg_compress_struct or jpeg_decompress_struct without first calling the jpeg_create_compress or jpeg_create_decompress functions respectively.
71,650,523
71,650,682
How to for loop with iterators if vector type is parent of two child types filling vector
I have this problem: this is my loop for previously used child type std::vector<Coin>::iterator coin; for (coin = coinVec.begin(); coin != coinVec.end(); ++coin) { sf::FloatRect coinBounds = coin->getGlobalBounds(); if (viewBox.intersects(coinBounds)) { if (playerBounds.intersects(coinBounds)) { coin = coinVec.erase(coin); break; } else coin->setTextureRect(currentFrame); } } And the similar one for std::vector<Heal>. I rebuild my code structure to: Coin is now child of Collectables. There is now only one vector: std::vector<Collectables> which contains all collactable child classes objects like Coin, Heal etc.. Is there a way to make the code work with only one loop and iterators? If yes, how would you do that? Thanks
I find out that my code is so universal, that I dont need to separate vector elements at all. My solution here: std::vector<Collectables>::iterator collect; for (collect = collectVec.begin(); collect != collectVec.end(); ++collect) { sf::FloatRect collectBounds = collect->getGlobalBounds(); if (viewBox.intersects(collectBounds)) { if (playerBounds.intersects(collectBounds)) { collect = collectVec.erase(collect); break; } else collect->setTextureRect(currentFrame); } } And if you really need to separate elements, try this: if (collect->getType() == ResourceManager::enums::textures::coin) { } else if (collect->getType() == ResourceManager::enums::textures::health) { } Where getType stores simply int id matching enum value.
71,650,689
71,650,809
The initialization of ListNode
I have a question about the initialization of ListNode, if I just announce a ListNode pointer, why can't I assign its next value like showed in the code. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {} }; ListNode* tmp; tmp->next = nullptr;// This is wrong, why is that? ListNode* tmp2 = new ListNode(1); tmp2->next = nullptr;// This is right, what cause that? I just try to announce a ListNode pointer and assign its next value to nullptr. But after I announce a pointer with new function, it goes right. Why?
A pointer is a box that can hold the address of an object ListNode* tmp; tmp->next = nullptr;// This is wrong, why is that? Here you created the box (tmp) but did not put the address of an object in it. The second line says - "at offset 4 from the address stored in tmp please write 0", well there is no valid address in the box so this fails. In the second example ListNode* tmp2 = new ListNode(1); tmp2->next = nullptr;// This is right, what cause that? You say "Please make a new ListNode object" "Put its address in the box called tmp2" "at offset 4 from the address stored in tmp2 please write 0" That can work, becuase the box tmp2 points somewhere valid
71,650,782
71,650,907
When using C++ pointer -> is there implicit Data type conversion
I am trying to debug someone else's code. There is a struct with elements of various size including a member defined as uint16_t attempts elsewhere this element is accessed thus int x = handle->attempts; int in my system is 32 bits Is it safe to assume that 2 bytes are loaded from the position pointed to in the struct (uint16_t) and implicitly convert to int (4 bytes). Or is it possible that the 4 bytes pointed to are loaded as an int (in this case an amalgamation of 2 uint16_t members)?
int x = handle->attempts; is a declaration with an initialization. In this declaration, handle->attempts is an initializer, per the grammar in C 2018 6.7 1. An initializer is an assignment-expression, per C 2018 6.7.9 1, and so rules for expression evaluation will be used. The expression handle->attempts designates the uint16_t member named attempts of the structure pointed to by handle. In other words, it is an lvalue for the member. Per C 2018 6.3.2.1 2, this lvalue is converted to the value stored in the designated object. Thus, the C standard says the bytes representing this object are read and interpreted according to the uint16_t type. Then a rule for initialization in C 2018 6.7.9 11 tells us this value is used as the initial value for the object being defined, x, using the same constraints and conversions as for simple assignment. C 2018 6.5.16.1 specifies simple assignment. Paragraph 2 says “the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand.” Thus, the value we have obtained from the initializer is converted to the type of x, int, and that bytes representing that value in the type int are stored in x.
71,651,028
71,651,491
Accessing private member function via Lambda
In a project, I have a C-API which uses C-style function pointers as callbacks. In one of those callbacks, I need to access a private function of an object Foo. Note that the API-call is done within a function of my class. Because of not shown code, I have a handle to my object as a void* accessible to me. Things aside that the construct is prone to errors, by passing a lambda as callback I am able to access the private function of my object. This is somewhat unexpected but welcome to me. I haven't found anything regarding this behavior, so I would kindly ask if somebody could shed some light why this is actual working. I am not aware that the lambda is catching something, but it appears that is has something to do with the actual scoping. I am using C++17 and gcc 10.2. Here's a sample block of code: void TestFunc(void (*)(void*)) { } class Foo { public: Foo() { TestFunc([](void* handle){ auto foo = reinterpret_cast<Foo*>(handle); foo->BarFunc(); }); }; private: void BarFunc() {}; };
Your code is working because Standard allows it. So first we have this (C++20 [expr.prim.lambda.closure]p2): The closure type is declared in the smallest block scope, class scope, or namespace scope that contains the corresponding lambda-expression. <...> And in your example we have a block scope so in the end we have an unnamed local class declaration and according to [class.local]p1: A class can be declared within a function definition; such a class is called a local class. The name of a local class is local to its enclosing scope. The local class is in the scope of the enclosing scope, and has the same access to names outside the function as does the enclosing function
71,651,184
71,652,699
C++ Return reference to vector of non-copy objects
I have class A with disabled copy semantics and class B which contains vector of A's. How can I write a member function of B that returns reference to the vector of A's?. For those knowing Rust here is what I am trying to do (expressed in the Rust language): struct A {/* ... */} struct B { data: Vec<A>, } impl B { pub fn data(&self) -> &Vec<A> { &self.data } }
As @molbdnilo stated my error was that I used auto data = b.data(); instead of auto& data = b.data();. Therefore following example is working and shows how to do what I asked: #include<vector> class A { public: A(const A&) = delete; A(A&&) = default; A& operator=(const A&) = delete; A& operator=(A&&) = default; private: /* some data */ }; class B { public: B(): m_data {} {} const std::vector<A>& data() const { return this->m_data; } private: std::vector<A> m_data; }; int main() { auto b = B(); auto& data = b.data(); }
71,651,252
71,652,780
How to pass an HWND as a GLFWwindow*?
I have an HWND that I have been using as the target of OpenGL draw operations, and it is necessary that it be an HWND and not a GLFWwindow for other utilities of the application I'm making. The problem is, I need to load and use shaders on textures that I am rendering text to with FreeType. Unfortunately functions like glfwSetFramebufferSizeCallback() and glfwSwapBuffers() require a GLFWwindow*. Is there any way I can pass a normal HWND as a GLFWwindow?
"When in Rome"... Just leave your OpenGL window as GLFWwindow. When (if?) you really need HWND, use glfwGetWin32Window
71,651,504
71,651,639
dereferencing a pointer to set a value vs. assigning an address to the pointer?
Could someone explain the difference between the following two snippets of code? In the function below, *frame_id maybe a nullptr, it's basically the output parameter in the function. bool LRUReplacer::Victim(frame_id_t *frame_id) { long oldest_ts = std::numeric_limits<long>::max(); for (auto & it : this->LRUCache){ if (it.ts < oldest_ts){ oldest_timestamp = it.ts; *frame_id = it.frame_id; } } vs. bool LRUReplacer::Victim(frame_id_t *frame_id) { long oldest_ts = std::numeric_limits<long>::max(); for (auto & it : this->LRUCache){ if (it.ts < oldest_ts){ oldest_timestamp = it.ts; frame_id = &it.frame_id; } } in the first case, we are assigning frame_id the value of it.frame_id and in the second case we are assigning the pointer the address of it.frame_id?
In the first loop, if it.ts < oldest_ts you will assign the value of it.frame_id to the frame_id_t to which frame_id points. After the loop is done, the frame_id_t instance (*frame_id) will hold the last value that was assigned to it. In the second loop, you will instead assign the address of it.frame_id to the frame_id_t* (frame_id). After the loop is done, frame_id will point at the last it.frame_id it was set to point at.
71,652,019
72,004,960
Auto-filling the HTML input field with a C++ QString value
I am finding the 'Sign in' text on the QWebEnginePage and then auto filling in the emailId in the input field if the correct page is displayed. The value of emailId is basically a QString. QString emailId = "abc@xyz.com"; What I have uptil now is the following, when the correct page is loaded, the input field is traced but the actual issue is setting the value = abc@xyz.com. Is there a way to set value of the input to be equal to the QString value. (I do not want to hardcode the value). ui->webEngineView->page()->findText(QStringLiteral("Sign in"), QWebEnginePage::FindFlags(), [this](bool found) { if (found) { QString code = QStringLiteral("document.querySelectorAll('input')[0].value = emailId"); ui->webEngineView->page()->runJavaScript(code); } });
According to @eyllanesc's comment the following worked for me: QString code = QString("document.querySelectorAll('input')[0].value = '%1'").arg(emailId);
71,652,143
71,652,450
do/while loop with cin.getline parsing to string doesn't compare values to break it
So I have this type of "menu" in a do/while loop do { cout << "Press 0 to export IDs, exit to exit, or any key to continue to menu:\n"; cin.getline(choice, sizeof(choice)); if (strcmp(choice, "0") == 0) { planesManager.exportIds(idsArray, arrSize); cout << "Would you like to Sort them?[y/n]\n"; cin >> choice; if (strcmp(choice, "y") == 0) { int low = 0; int high = arrSize - 1; quickSort(idsArray, low, high); } cout << "Would you like to print them?[y/n]\n"; cin >> choice; if (strcmp(choice, "y") == 0) { printArray(idsArray, arrSize); } } do { cout << ">Would you like to create, search, edit, or go back?\n"; cin >> choice; if (strcmp(choice, "create") == 0) { planesManager.createEntry(); } else if (strcmp(choice, "search") == 0) { planesManager.searchEntry(); } else if (strcmp(choice, "edit") == 0) { planesManager.editEntry(); } } while (strcmp(choice, "back") != 0); cin.ignore(); } while (strcmp(choice, "exit") != 0); However, when typing "exit" on the first input, it doesn't exit the loop and goes into the inner one. Where is the issue and what would be possible solutions? p.s. When running only the inner do/while loop it works correctly.
You are using the same choice buffer to manage both loops. The outer loop's while check is not reached until the inner loop is finished first, and the inner loop only breaks when choice is "back". So, by the time the outer loop's while check is reached, choice will never be "exit". Try this instead: do { cout << "Press 0 to export IDs, exit to exit, or any key to continue to menu:\n"; cin.getline(choice, sizeof(choice)); if (strcmp(choice, "exit") == 0) break; // <-- move this here! if (strcmp(choice, "0") == 0) { planesManager.exportIds(idsArray, arrSize); cout << "Would you like to Sort them?[y/n]\n"; cin >> choice; if (strcmp(choice, "y") == 0) { quickSort(idsArray, 0, arrSize - 1); } cout << "Would you like to print them?[y/n]\n"; cin >> choice; if (strcmp(choice, "y") == 0) { printArray(idsArray, arrSize); } } do { cout << ">Would you like to create, search, edit, or go back?\n"; cin >> choice; if (strcmp(choice, "create") == 0) { planesManager.createEntry(); } else if (strcmp(choice, "search") == 0) { planesManager.searchEntry(); } else if (strcmp(choice, "edit") == 0) { planesManager.editEntry(); } } while (strcmp(choice, "back") != 0); cin.ignore(); } while (true);
71,652,187
71,652,691
Can't understand the requirement of the problem. (ProjectEuler problem: 11)
I am trying to solve this problem: https://projecteuler.net/problem=11 However, this part confuses me: What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid? what does in the same direction and up, down, left, right or diagonally mean? Is it just me or is the language vague here? this is what I have tried so far: long int prod{0}, n{20}; for(int i{0}; i <= n; i++) { for(int j{0}; j <= n; j++) { long int a{grid[i][j]}, b{grid[i+1][j+1]}, c{grid[i+2][j+2]}, d{grid[i+3][j+3]}; if(prod < (a * b * c * d)) prod = a * b * c * d; } } return prod; With this function I satisfy the first demand but up down left right or diagonally? what does or mean there?
A direction in the context of a grid is the geometrical space whose all points are on the same line. If we take a point, then we can cross it with 4 different lines: \ | / \ | / \ | / \|/ ----*---- /|\ / | \ / | \ / | \ So, how could we define these directions? There is a very simple way to do so: you loop the rows you loop the columns at the current point, you try to get 4 values, including the current point downwards rightwards right-downwards right-upwards I say "try", which means that you will have to ignore quite a few possibilities due to the boundaries of your grid. Yet, it is a neat way to get all four directions: int bestProduct = -1; //Assuming you have positives for (int row = 0; row < n; row++) { for (int column = 0; column < n; column++) { int ignore = 0; int rowDir = 0; int colDir = 1; int product = grid[row][column]; for (int index = 0; (!ignore) && (index < 3); index++) { if ( (row + rowDir < 0) || (row + rowDir >= n) || (column + colDir < 0) || (column + colDir >= m) ) { ignore = 1; } else product *= grid[row + rowDir][column + colDir]; } if ((!ignore) && (bestProduct < product)) bestProduct = product; } } This is not a full implementation, since you also need to do some work. You will need to continue with: converting the inner part of the second loop into a function except the if conditional that checks whether the product is higher than the best product so far remove that inner code and replace it with the function call call the function three more times, once for each other direction the other directions are: 1: having a 1 colDir and 0 rowDir 2: having a 1 colDir and 1 rowDir 3: having a 1 colDir and -1 rowDir I know it is more difficult to consider this partial solution, but it will help you a lot in the long run if you do the rest for yourself, as the ideas are all laid down here.
71,652,425
72,105,759
How to access the files in the res folder in the imgui conan package?
I am using conan to handle dependencies, for those of you familiar with imgui, it provides a series of backends you can include. When you look at the conan package these are found in the res folder. I need to tell meson to include files in that directory, how do I instruct meson how to find these files?
I am new to conan so i dont know if there is a better solution, but i have the following in my conanfile.txt [imports] res, *glfw.* -> . which puts a bindings folder with the header and the source file in the build directory then i use them in my CMakeLists.txt with "${CMAKE_CURRENT_BINARY_DIR}/bindings/imgui_impl_glfw.cpp" In a .py script one would do somehting like the following: def imports(self): self.copy("*.cpp", dst="ext/imgui", src=self.deps_cpp_info["imgui"].resdirs[0]) self.copy("*.hpp", dst="ext/imgui", src=self.deps_cpp_info["imgui"].resdirs[0]) self.copy("*.h", dst="ext/imgui", src=self.deps_cpp_info["imgui"].resdirs[0])
71,652,807
71,653,176
Woes with std::shared_ptr<T>.use_counter()
ERROR: type should be string, got "https://en.cppreference.com/w/cpp/memory/shared_ptr/use_count states:\n\nIn multithreaded environment, the value returned by use_count is approximate (typical implementations use a memory_order_relaxed load)\n\nBut does this mean that use_count() is totally useless in a multi-threaded environment?\nConsider the following example, where the Circular class implements a circular buffer of std::shared_ptr<int>.\nOne method is supplied to users - get(), which checks whether the reference count of the next element in the std::array<std::shared_ptr<int>> is greater than 1 (which we don't want, since it means that it's being held by a user which previously called get()).\nIf it's <= 1, a copy of the std::shared_ptr<int> is returned to the user.\nIn this case, the users are two threads which do nothing at all except love to call get() on the circular buffer - that's their purpose in life.\nWhat happens in practice when I execute the program is that it runs for a few cycles (tested by adding a counter to the circular buffer class), after which it throws the exception, complaining that the reference counter for the next element is > 1.\nIs this a result of the statement that the value returned by use_count() is approximate in a multi-threaded environment?\nIs it possible to adjust the underlying mechanism to make it, uh, deterministic and behave as I would have liked it to behave?\nIf my thinking is correct - use_count() (or rather the real number of users) of the next element should never EVER increase above 1 when inside the get() function of Circular, since there are only two consumers, and every time a thread calls get(), it's already released its old (copied) std::shared_ptr<int> (which in turn means that the remaining std::shared_ptr<int> residing in Circular::ints_ should have a reference count of only 1).\n#include <mutex>\n#include <array>\n#include <memory>\n#include <exception>\n#include <thread>\n\nclass Circular {\n public:\n Circular() {\n for (auto& i : ints_) { i = std::make_shared<int>(0); }\n }\n\n std::shared_ptr<int> get() {\n std::lock_guard<std::mutex> lock_guard(guard_);\n index_ = index_ % 2; // Re-set the index pointer.\n\n if (ints_.at(index_).use_count() > 1) {\n // This shouldn't happen - right? (but it does)\n std::string excp = std::string(\"OOPSIE: \") + std::to_string(index_) + \" \" + std::to_string(ints_.at(index_).use_count());\n throw std::logic_error(excp);\n }\n\n return ints_.at(index_++);\n }\n\n private:\n std::mutex guard_;\n unsigned int index_{0};\n std::array<std::shared_ptr<int>, 2> ints_;\n};\n\nCircular circ;\nvoid func() {\n do {\n auto scoped_shared_int_pointer{circ.get()};\n }while(1);\n}\n\nint main() {\n std::thread t1(func), t2(func);\n\n t1.join(); t2.join();\n}\n\n"
use_count is for debugging only and shouldn't be used. If you want to know when nobody else has a reference to a pointer any more just let the shared pointer die and use a custom deleter to detect that and do whatever you need to do with the now unused pointer. This is an example of how you might implement this in your code: #include <mutex> #include <array> #include <memory> #include <exception> #include <thread> #include <vector> #include <iostream> class Circular { public: Circular() { size_t index = 0; for (auto& i : ints_) { i = 0; unused_.push_back(index++); } } std::shared_ptr<int> get() { std::lock_guard<std::mutex> lock_guard(guard_); if (unused_.empty()) { throw std::logic_error("OOPSIE: none left"); } size_t index = unused_.back(); unused_.pop_back(); return std::shared_ptr<int>(&ints_[index], [this, index](int*) { std::lock_guard<std::mutex> lock_guard(guard_); unused_.push_back(index); }); } private: std::mutex guard_; std::vector<size_t> unused_; std::array<int, 2> ints_; }; Circular circ; void func() { do { auto scoped_shared_int_pointer{ circ.get() }; } while (1); } int main() { std::thread t1(func), t2(func); t1.join(); t2.join(); } A list of unused indexes is kept, when the shared pointer is destroyed the custom deleter returns the index back to the list of unused indexes ready to be used in the next call to get.
71,652,995
71,653,530
How to get each digit of a template integral type in its native base?
I am working on an implementation of Radix sort for arrays of integral types. Using the numeric_limits functions provided by the standard library, I am able to learn about the native base representation of any given integral type using numeric_limits::radix, and the maximum amount of digits in that base that the type can hold using numeric_limits::digits. In order to implement radix sort optimally, I need to extract the value of each of those digits in turn for each of the elements of the array. Is there some standard, or at least common, way to do this? In case it matters, I am using C++20 and do not care about backwards compatibility with older revisions of the standard, only maximum interoperability with other C++20 code.
If you want to iterate through the digits of the number number expressed with radix radix, in order from least-to-greatest significant digits, then a loop like the following would work. This loop assumes that number is a type that supports division and modulus, and that these operations are purely integer operations (fractions are removed): auto curr_val = number; //Copy the number, since we're going to modify it. while(curr_val != 0) { auto curr_digit = curr_val % radix; curr_val = curr_val / radix; //Integer division. } Note that this works regardless of the representation of number in whatever internal representation the type uses. So even if numeric_limits<int>::radix is 2, this will work for iterating through the way number would be represented in base-10.
71,653,344
71,671,281
How to overcome Stack size warning?
I would like to know the best practice concerning the following type of warning: ptxas warning : Stack size for entry function '_Z11cuda_kernelv' cannot be statically determined It appears adding the virtual keyword to the destructor of Internal, i.e. moving from __device__ ~Internal(); to __device__ virtual ~Internal(); in the following programme: template<typename T> class Internal { T val; public: __device__ Internal(); __device__ virtual ~Internal(); __device__ const T& get() const; }; template<typename T> __device__ Internal<T>::Internal(): val() {} template<typename T> __device__ Internal<T>::~Internal() {} template<typename T> __device__ const T& Internal<T>::get() const { return val; } template<typename T> class Wrapper { Internal<T> *arr; public: __device__ Wrapper(size_t); __device__ virtual ~Wrapper(); }; template<typename T> __device__ Wrapper<T>::Wrapper(size_t len): arr(nullptr) { printf("%s\n", __PRETTY_FUNCTION__); arr = new Internal<T>[len]; } template<typename T> __device__ Wrapper<T>::~Wrapper() { delete[] arr; } __global__ void cuda_kernel() { Wrapper<double> *wp = new Wrapper<double>(10); delete wp; } int main() { cuda_kernel<<<1,1>>>(); cudaDeviceSynchronize(); return 0; } Having faced with the warning shown above, I wonder what I should do in this case?
The very short answer is that there is nothing you can do about this particular warning. In more detail: This warning is an assembler warning, not a compiler warning The NVIDIA toolchain relies on a lot of assembler level optimizations to produce performant SASS machine code that runs on the silicon. The NVIDIA compiler emits PTX virtual machine language which can undergo significant transformation when assembled. This includes resolution of single static assignment form compiler output into static register assignment (and register spilling to local memory), inline expansion of functions, and emission of a statically compiled stack reservation. All of these are potentially performance optimizing operations. This is an informational warning from the assembler, which is telling you that during a static code analysis, the assembler was unable to determine the stack size. The most normal scenario when the assembler emits this warning is when recursion is detected within kernel code. Your use case is clearly another. The warning comes from an assembler optimisation pass. The assembler is letting you know that there are potentially performance improvement opportunities being left on the table because the structure of the compiler output of your code can't allow it to statically determine the stack size The fallback the assembler will use will be more boilerplate SASS to set-up and tear-down the per thread stack which the kernel will require to run. The warning is letting you know that happened.
71,654,148
71,669,096
Variadic template parameter pack expansion looses qualifier
Let's say I have a variadic function template taking a function pointer to a function with said variadic arguments. The following code does not compile under gcc (11.2), but compiles under clang and msvc (https://godbolt.org/z/TWbEKWb9f). #include <type_traits> void dummyFunc(const int); template<typename... Args> void callFunc(void(*)(Args...), Args&&...); // <- this one is problematic // see https://stackoverflow.com/questions/67081700/variadic-template-qualifiers template<typename... Args> void callFunc2(void(*)(std::conditional_t<std::is_const_v<Args>, const Args, Args>...), Args&&...); // <- this one works int main() { // fails on gcc, works on clang and msvc callFunc<const int>(&dummyFunc, 2); // this works //callFunc(&dummyFunc, 2); // this works as well //callFunc2<const int>(&dummyFunc, 2); } Specifying the function arguments 'Args...' explicitly as 'const int' prevents gcc from compiling the code. Apparently the template parameter expansion looses the cv-qualifier under gcc, while it is kept under clang and msvc. The error message is: <source>: In function 'int main()': <source>:15:24: error: no matching function for call to 'callFunc<const int>(void (*)(int), int)' 15 | callFunc<const int>(&dummyFunc, 2); | ~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~ <source>:6:6: note: candidate: 'template<class ... Args> void callFunc(void (*)(Args ...), Args&& ...)' 6 | void callFunc(void(*)(Args...), Args&&...); | ^~~~~~~~ <source>:6:6: note: template argument deduction/substitution failed: <source>:15:24: note: types 'const int' and 'int' have incompatible cv-qualifiers 15 | callFunc<const int>(&dummyFunc, 2); | ~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~ I found the 'solution' by utilizing type traits to make it compile here (Variadic template qualifiers), but I either should have to use this method or not, independently of the compiler. I know I don't have to specify the template arguments explicitly, but I want to understand why gcc fails to compile the code. Which compiler is "right", i.e. should this code compile or not (that is, should the cv-qualifier be dropped)? As a side note, if I use a const reference instead, it compiles also under gcc, and the template argument is correctly recognized as 'const int&' (because the compiler absolutely has to do so). I am aware of the fact that, if the template argument is deduced by the compiler and not explicitly specified, that the cv-qualifier is dropped. But in my opinion gcc's behavior here is wrong because I explicitly stated the type to use. However, I don't know the standard well enough to tell whether gcc or the other two compilers are not following the standard. It seems to be related to variadic templates and not the template deduction itself, because the version without variadic templates works under gcc (https://godbolt.org/z/qn8a5bh5E): void dummyFunc(const int); template<typename Arg> void callFunc(void(*)(Arg), Arg&&); int main() { callFunc<const int>(dummyFunc, 2); } Also, why is automatic template type deduction even working in the first (problematic) case? 'Args...' should be deduced as both 'const int', because of the function pointer, as well as 'int' because of the second argument. My guess is that in this case, 'Args...' is deduced as 'const int' (otherwise it would not compile). Is my guess correct? It would be great if somebody could hint me to the relevant section in the standard.
The cv-qualifier should always be dropped (both in determining the type of dummyFunc and when substituting the deduced argument into the callFunc signature), and I'm pretty sure all compilers agree on this. It's not really what the question is about. Let's change the example a bit: template <class... Args> struct S { template <class... T> S(T...) {} }; template<typename... Args> void callFunc2(S<Args...>); int main() { callFunc2<const int>(S<int>{}); } Now GCC and Clang reject the code while MSVC accepts it. GCC and Clang both have issues with the mismatch between const int (explicitly specified) and int (deduced) whereas MSVC is evidently happy just to let Args = [const int] as specified. Who is right? As I see it the problem here is [temp.arg.explicit]/9, which states: Template argument deduction can extend the sequence of template arguments corresponding to a template parameter pack, even when the sequence contains explicitly specified template arguments. Thus, specifying an explicit template argument for the pack Args does not prevent deduction. The compiler still has to try to deduce Args in case it needs to be extended in order to match the function parameter types against the argument types. It has never been clearly explained what this paragraph of the standard really means. I guess MSVC's approach could possibly be something like "deduce the pack as if there were no explicitly specified template arguments, then throw out the result if the explicitly specified template arguments are not a prefix of the deduced template arguments" which seems like a sensible way to handle this code. GCC and Clang might be something like "deduce the pack as if there were no explicitly specified template arguments, and then fail if the explicitly specified template arguments are not a prefix of the deduced template arguments" which would lead to the code being ill-formed, but this seems like an unfortunate interpretation because it's inconsistent with how explicitly specified template arguments are treated in non-variadic cases. The example above is similar to a simplified version of the OP's example: void dummyFunc(int); template<typename... Args> void callFunc(void(*)(Args...)); int main() { callFunc<const int>(&dummyFunc); } Here, the trailing Args&&... has been removed, which doesn't change the result: as with OP's code, Clang and MSVC accept it while GCC doesn't.. Only Clang has changed its opinion: it accepts this one while rejecting the one with S. To be fair, these two snippets are not really analogous: the one with S involves an implicit conversion. But it's not clear why Clang treats them differently. From my point of view, GCC and Clang both have different bugs with variadic template deduction, while MSVC does the right thing in both cases. But it's hard to make an argument based on the standard text that this is unambiguously the case.
71,654,281
71,655,612
Can I set a default "Active Solution Platform" in Visual Studio?
The Question In Visual Studio, in the "Configuration Manager" under the Build tab, there is an option called the "Active Solution Platform." This causes problems with one of my commonly used libraries. Is there a way to set this to default to x64? Is there a way to have this setting set when I load a custom project template? Extra Details I recently installed mlpack on Windows 10 using vcpkg install mlpack:x64-windows I then wrote a sample mlpack project in Visual Studio and did the work to compile it. That required overcoming the error: fatal error LNK1112: module machine type 'x86' conflicts with target machine type 'x64' To do that, I followed step 1 and 2 from this question. After the project compiled, I exported it as a project template so I could build my next project faster. I started a new solution with the project template. I tried to compile the project, and I ran into error fatal error LNK1112: module machine type 'x86' conflicts with target machine type 'x64' The problem was that the Build Configuration settings weren't saved with the project template. (See step 2 in the link above.) The "Active Solution Platform" in the Build Configuration menu defaulted to x86, despite that the Project's "Target Machine" (and the machine I am building on) are x64. This leads me to the question above.
Try to create the project in Visual Studio 2022. C++ uses x64 as Active solution platform by default in VS2022.
71,654,572
71,655,258
C++ class templates with multiple arguments
I am just learning how to use templates in c++, and I am struggling a bit. I have an example below, with comments at the points where I'm getting hung up. #include <iostream> using namespace std; template<int arrayOneSize, int arrayTwoSize> class myClass{ public: myClass(){ for(int i = 0; i < arrayOneSize; i++){ arrayOne[i] = i; } for(int i = 0; i < arrayTwoSize; i++){ arrayTwo[i] = i; } } int arrayOne[arrayOneSize]; int arrayTwo[arrayTwoSize]; void printArrayElements(){ for(int i = 0; i < arrayOneSize; i++){ cout << arrayOne[i] << '\n'; } for(int i = 0; i < arrayTwoSize; i++){ cout << arrayTwo[i] << '\n'; } } void someOtherFunction(); }; // can't figure out how to define constructors or functions outside of class void myClass::someOtherFunction(){ } template <int numInstances> class myClassContainer{ public: myClassContainer(){ for(int i = 0; i < numInstances; i++){ myClassInstances[i] = NULL; } } // this doesn't work template<int, int> myClass<int, int> *myClassInstances[numInstances]; // also doesn't work void addClassInstance(myClass *instance){ for(int i = 0; i < numInstances; i++){ if(myClassInstances[i] == NULL){ myClassInstances[i] = instance; } } } void printAll(){ for(int i = 0; i < numInstances; i++){ myClassInstances[i]->printArrayElements(); } } }; int main() { myClass<5,6> myClass1; myClass<1,4> myClass2; myClassContainer<2> container; container.addClassInstance(&myClass1); container.addClassInstance(&myClass2); container.printArrayElements(); return 0; } I would like to be able to pass pointers to myClass instances into myClassContainer, but I can't figure out the template syntax. Thanks in advance for any advice.
can't figure out how to define constructors or functions outside of class void myClass::someOtherFunction(){} The problem here is that there is no class called myClass. Instead, there are only classes called myClass<someNumber, anotherNumber>. So, in order to define someOtherFunction, it must be written something like: void myClass<someNumber, anotherNumber>::someOtherFunction() { ... } However, neither someNumber nor anotherNumber are a concrete number, so you need to make them template parameters: template<int someNumber, int anotherNumber> void myClass<someNumber, anotherNumber>::someOtherFunction() { ... } Also note, it's more common and convenient to use the same template names as the ones used in the class declaration, so your definition would be: template<int arrayOneSize, int arrayTwoSize> void myClass<arrayOneSize, arrayTwoSize>::someOtherFunction() { ... } this doesn't worktemplate<int, int> myClass<int, int> *myClassInstances[numInstances]; The problem here is that the types of all class member must be known at the time the class was defined. So you can not have a member with a template class that cannot deduce its type at the time the outer class is defined. So you need to either: Assign both template parameters with some concrete value: template <int numInstances> class myClassContainer{ myClass<2, 3> *myClassInstances[numInstances]; }; You can use the template parameter of myClassContainer to calculate a value: myClass<numInstances, numInstances * 2> *myClassInstances[numInstances]; Or you can make both of them template parameter, and add them to the class template parameters: template <int numInstances, int A, int B> class myClassContainer{ myClass<A, B> *myClassInstances[numInstances]; }; Of course you can do any mixture of them Do note that whichever approach you decided on, you cannot add both myClass<5, 6> and myClass<1, 4> to the same array, since they are not the same type. also doesn't workvoid addClassInstance(myClass *instance) Once again, myClass is not a type, instead it must be myClass<someValue, anotherValue>. So you must add the template parameters to the function: template<int someValue, int anotherValue> void addClassInstance(myClass<someValue, anotherValue *instance){ ... } In case you want to define this outside of the class: template<int numInstances> template<int someValue, int anotherValue> void myClassContainer<numInstances>::addClassInstance(myClass<someValue, anotherValue> *instance) { ... }
71,654,650
71,654,684
Print statement after for loop generating an additional iteration
I am very much a beginner in C++ and was just delving into for loops when I ran into a problem that I solved by winging it and not by understanding. My script adds numbers from 1 to 10 and calculates the average. The thing is that I had to introduce a new variable "number", other than "sum" and "count", to not have the average be wrong. #include <iostream> int main () { float count, sum, avg, number; sum=avg=number=0.0; for (count=1.0;count<=10.0;count+=1.0) { sum=sum+count; avg=sum/count; number=count; } printf("\n\nThe number of iterations is %1.f",number); printf("\nThe sum of the numbers between 1 and 10 is = %.1f",sum); avg=sum/number; printf("\nThe average is %.1f",avg); } Produces the right result, but #include <iostream> int main () { float count, sum, avg; sum=avg=0.0; for (count=1.0;count<=10.0;count+=1.0) { sum=sum+count; avg=sum/count; } printf("\n\nThe number of iterations is %1.f",count); printf("\nThe sum of the numbers between 1 and 10 is = %.1f",sum); avg=sum/count; printf("\nThe average is %.1f",avg); } Gives one more iteration than I expected and causes the average to be wrong. I assume that maybe calling "count" to print adds up but have no certainty and would really like to know why. Sorry if the question but I couldn't figure it out.
In this loop for (count=1.0;count<=10.0;count+=1.0) { sum=sum+count; avg=sum/count; number=count; } number can not be greater than 10.0. But in this loop for (count=1.0;count<=10.0;count+=1.0) { sum=sum+count; avg=sum/count; } count is greater than 10.0 after exiting the loop due to the condition count<=10.0. So these statements avg=sum/number; and avg=sum/count; produce different results because number and count are unequal after the loops.
71,655,186
71,655,267
Code crashes when creating new thread c++
I'm new to C++ and I'm trying to make the console print "after 5 seconds" after 5000 ms. Then print "insta log" immediately after the new thread's declaration. But doing so crashes with the following error: "Debug Error! [PROGRAM PATH] abort() has been called " This is my code: #include <iostream> #include <thread> #include <Windows.h> #include <ctime> using namespace std; void f() { Sleep(5000); cout << "after 5 seconds" << endl; } int main() { cout << "starting" << endl; // Pass f and its parameters to thread // object constructor as thread t(&f); cout << "insta log" << endl; } I'm unsure why this is happening. I've searched around and I found a "fix" but it makes my code not behave as intended. This is the "fix" #include <iostream> #include <thread> #include <Windows.h> #include <ctime> using namespace std; void f() { Sleep(5000); cout << "after 5 seconds" << endl; } int main() { cout << "starting" << endl; // Pass f and its parameters to thread // object constructor as thread t(&f); t.join(); cout << "insta log" << endl; // doesn't print for 5 seconds } This removes the error message but yields the main thread for 5 seconds. Which makes my code not work as intended. Thanks in advance, any help is appreciated!
Functions are already passed around as pointers, use thread t(f) instead of thread t(&f). Moreover, since your main() neither lasts longer than the thread or calls a t.join(), the program will end before the thread finishes it's code, so that might be another reason for a crash. In fact it is probably the reason for the crash. If you want "insta log" to print instantly, then call t.join() at the end of main(). t.join() will wait for the thread t to end before continuing.
71,655,233
71,655,659
Linking LLVM getOrInsertFunction to a external c++ function in a LLVM pass
I have written a LLVM pass that inserts a call to a external function (foo) in a C(count.c) file. Later when I link C file's object that contains foo function with LLVM instrumented c++ file, it works fine. The C file which contains foo function, looks like this. #include <stdio.h> int count = 0; void foo(int id) { count++; printf("id = $d, count = %d\n", id, count); } I create a call from LLVM pass using this code snippet: ArrayRef<Type *> paramTypes = {Type::getInt8Ty(Ctx)}; Type *retType = Type::getVoidTy(Ctx); FunctionType *funcType = FunctionType::get(retType, paramTypes, false); FunctionCallee callee = M.getOrInsertFunction("foo", funcType); All this works fine as long as foo function is in a C file. But if foo is in a C++ file, ld returns undefined references to 'foo' Is there a way to link an external function in a C++ file to llvm getOrInsertFunction?
Yes, you need to make the C++ function as extern. foo.cpp can look like: extern "C" { void foo(int id) { count++; printf("id = $d, count = %d\n", id, count); } } extern C tells the compiler to not mangle the name of scoped functions. You can learn more about name mangling and extern C here
71,655,265
71,655,301
How can I implement a copy constructor to this program?
#include <iostream> using namespace std; class Point{ private: int x, y; public: Point(int x, int y) { this->x = x; this->y = y } Point(const Point &p) { x = p.x; y = p.y; } int getX(void) { return x; } int getY(void) { return y; } }; int main(){ Point myPt(1,2); Point myPt2 = myPt; cout << myPt.getX() << " " << myPt.getY() << endl; cout << myPt2.getX() << " " << myPt2.getY() << endl; return 0; } I want to set myPt2 to a different value while keeping myPt values the same, even after setting myPt2 equal to myPt (redefinition error when I do this). For example, Point myPt(1,2); Point myPt2 = myPt; ....print output, then set myPt2(5, 5) and print statements again: I want the output 1 2 \n5 5.
If I'm understanding you correctly, you are looking for a way to make below code work: int main(){ Point myPt(1,2); Point myPt2 = myPt; myPt2(5, 5); cout << myPt.getX() << " " << myPt.getY() << endl; // prints "1 2" cout << myPt2.getX() << " " << myPt2.getY() << endl; // prints "5 5" } To allow the syntaxmyPt2(5, 5), you must overload the call operator, operator(), to accept 2 integers: class Point { ⋮ public: void operator()(int x, int y) { this->x = x; this->y = y; } ⋮ }; However, I strongly suggest to not go this approach. Instead, when you want to reassign values to myPt2, you really should be calling the copy assignment operator using the following syntax: myPt2 = Point(5, 5); To write your own copy assignment operator, it would be something like: class Point { ⋮ public: Point& operator=(const Point &p) { x = p.x; y = p.y; return *this; } ⋮ }; In fact, based on what your class do, you really don't need to write either copy constructor or the copy assignment operator. This is all you need: class Point{ private: int x, y; public: Point(int x, int y) { this->x = x; this->y = y; } int getX(void) { return x; } int getY(void) { return y; } }; Any kind of copy construction will be done automatically. You really only need to define your own copy constructors if you either have non-copyable members, or if you are looking for some custom copy behavior, such as doing deep copying a pointer.
71,655,372
71,655,429
IDXGIOutput::GetDisplayModeList Finds No Display Modes
I am trying to get a list of all the possible resolutions for a IDXGI_OUTPUT*. To do this, I found the IDXGIOutput::GetDisplayModeList API. Unfortunately, there are almost no examples of usage that I could find online. I tried the one on MSDN, and it failed to find any display modes (num is 0) UINT num = 0; DXGI_FORMAT format = DXGI_FORMAT_R32G32B32A32_FLOAT; UINT flags = DXGI_ENUM_MODES_INTERLACED; pOutput->GetDisplayModeList( format, flags, &num, 0); DXGI_MODE_DESC * pDescs = new DXGI_MODE_DESC[num]; pOutput->GetDisplayModeList( format, flags, &num, pDescs); I noticed MSDN recommends to use GetDisplayModeList1() instead, so I tried that as well and num still is 0. I have also verified that the IDXGI_OUTPUT* is completely valid. I am at a loss what to do...
You are asking for all display modes that support the DXGI_FORMAT_R32G32B32A32_FLOAT format. This format is never supported (at least at the time of this answer posting) for "display scan-out". The only currently defined "display scan-out" DXGI formats are: DXGI_FORMAT_R16G16B16A16_FLOAT DXGI_FORMAT_R10G10B10A2_UNORM DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM DXGI_FORMAT_R8G8B8A8_UNORM DXGI_FORMAT_R8G8B8A8_UNORM_SRGB DXGI_FORMAT_B8G8R8A8_UNORM DXGI_FORMAT_B8G8R8A8_UNORM_SRGB See Microsoft Docs.
71,655,419
71,656,391
How to call function/classes in c++ .so files, generated by Bazel, in Python?
Let's say I have a simple class in hello.h #ifndef LIB_HELLO_GREET_H_ #define LIB_HELLO_GREET_H_ class A{ public: int a = 0; int b = 0; int add(){ return a+b; } }; #endif with bazel build file: load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") cc_library( name = "hello", hdrs = ["hello.h"], ) cc_binary( name = "hello.so", deps = [ ":hello", ], linkshared=True, linkstatic=False ) After I run bazel build hello.so, there is a shared object file generated in bazel-bin/main and bazel-bin/main/hello.so.runfiles/__main__/main/hello.so. Using those files, I want call class A with a python script. Ideally, I'd want to use cppyy or something similar. I've tried with simple python scripts import cppyy cppyy.load_reflection_info('hello') print(dir(cppyy.gbl)) or import cppyy cppyy.load_library('hello') print(dir(cppyy.gbl)) with both .so files, but cppyy can't seem to detect class A - it is never inside cppyy.gbl I'm wondering the best way to solve this problem, any help appreciated!
With cppyy, you also need to give it the header file, that is: cppyy.include("hello.h") and optionally use cppyy.add_include_path() to add the directory where hello.h resides, so that it can be found. An alternative is to use so-called "dictionaries." These package (customizable) directory locations, names of necessary headers files and (through linking) the shared library with the implementation into a single, new, shared library (named "dictionary" because of history). There can be a so-called "rootmap" file on the side that allows a class loader to find A automatically on first use. See the example in the documentation.
71,655,829
71,655,866
Convert templated type into ID
I have a project where I need to have the ability to convert a given type into an ID. This code doesn't compile, but I hope it shows the functionality I am trying to achieve. class TypeIDManager { public: template <typename Type> void setTypeID(std::size_t ID) { m_data.insert({ typeid(Type), ID }); } template <typename Type> std::size_t getTypeID() { return m_data[typeid(Type)]; } private: std::unordered_map<std::type_info, std::size_t> m_data; };
That's what std::type_index is meant for: std::unordered_map<std::type_index, std::size_t> m_data; std::type_info is implicitly convertible to std::type_index via its converting constructor, so you don't need to change the way you insert into the map. However std::type_index doesn't have a default constructor which is required for std::unordered_map's operator[]. So you will need to use the find/at methods instead to retrieve values, e.g. return m_data.at(typeid(Type)); which will throw an exception if the key isn't found.
71,655,871
71,655,904
QuickSort for vector<string>
I'm new to recursion and get kind of confused by it this is my first time coding Quick Sort for a string I keep getting an error. Does anyone know where I messed up? #include <iostream> #include <string> #include <fstream> #include <vector> using namespace std; void SwapValue(string &a, string &b) { string t = a; a = b; b = t; } void quicksort(vector<string> &list, int first, int end) { int l = first; int r = end; int pivot = ((first + end) / 2); while (l <= r) { while (list[l] <= (list[pivot])) ++l; while (list[r] >= (list[pivot])) --r; if (l <= r) { swap(list[l], list[r]); ++l; --r; } } if (first <= r) quicksort(list, first, r); if (end >= l) quicksort(list, l, end); } void print(vector <string> const &a) { cout << "[ "; for(int i=0; i < a.size(); i++) { cout << a[i] << ' '; } cout << ']'; } int main() { vector<string> test = {"Bob", "Andrew", "Joe"}; quicksort(test, 0, test.size()-1); print(test); return 0; } I thought about getting the ASCII values of the first char within the string but I would have to use a nested forloop to retrieve the character and wouldn't that make QuickSort slower?
This statement: while (list[l] <= (pivot)) How does that even compile? Comparing a string to an integer? I suspect you mean: while (list[l] <= list[pivot]) Similar treatment is also needed for the while (list[r] >= (pivot)) statement. And I don't think you want to use >= on the right side. while (i <= r) That won't compile either since i is not defined. I suspect you meant l, not 'i'.
71,656,015
71,656,066
Will C++ function with mixed constant value and variable enable copy elision too?
In the following code std::string OtherFunc(); std::string MyFunc() { if (condition1) return "result 1"; if (condition2) return "result 2"; return OtherFunc(); } Will MyFunc() enable copy elision (for the return string from OtherFunc())? I know I can write std::string MyFunc() { std::string ret; if (condition1) { ret = "result 1"; return ret; } if (condition2) { ret = "result 2"; return ret; } ret = OtherFunc(); return ret; } to 100% sure copy elision enable. But I think the 2nd code is very cumbersome.
There are no std::string copies/moves made in the first example you are showing. (since C++17) In the second variant the move from ret to the return value of the function (or whatever object is initialized from it) may be elided (named return value optimization (NRVO)), but that is not guaranteed, even in C++17. Furthermore in the second example, even if NRVO is applied, there will need to be a move assignment operator call for the line ret = OtherFunc(); that isn't required in the first version. So, the first version is definitively better in terms of the required copy/move operations. (A std::string move can still be cheap, so the difference may not be significant enough that other factors won't determine the overall performance.)
71,656,290
71,666,122
All possible combinations and permutations of size n algorithm
I'm trying to figure out an algorithm to have all possible combinations and permutations of size k from an array of size n. Let's have an example: Input: n = 3 => [1, 2, 3] Output should be: k = 1 => [[1], [2], [3]] k = 2 => [[1, 2], [1, 3], [2, 3], [2, 1], [3, 1], [3, 2]] k = 3 => [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1 ,2], [3, 2, 1]] I started by looking at the QuickPerm Algorithm but it gives all possible permutations for the size of the array: If we go back to our example, the QuickPerm algorithm gives this output: [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1 ,2], [3, 2, 1]].
Your task (all permutations of all combinations) can be easily solved using regular recursive function (as I did below) without any fancy algorithm. Try it online! #include <vector> #include <functional> #include <iostream> void GenCombPerm(size_t n, size_t k, auto const & outf) { std::vector<bool> used(n); std::vector<size_t> path; std::function<void()> Rec = [&]{ if (path.size() >= k) { outf(path); return; } for (size_t i = 0; i < used.size(); ++i) { if (used[i]) continue; used[i] = true; path.push_back(i); Rec(); path.pop_back(); used[i] = false; } }; Rec(); } int main() { std::vector<size_t> a = {1, 2, 3}; GenCombPerm(a.size(), 2, [&](auto const & v){ std::cout << "["; for (auto i: v) std::cout << a[i] << ", "; std::cout << "], "; }); } Output: [1, 2, ], [1, 3, ], [2, 1, ], [2, 3, ], [3, 1, ], [3, 2, ],
71,658,418
71,659,326
std::fstream / std::filesystem create file with duplicate number
I want to create a file with a number at the end of the file : filename ( number goes here ).txt. The number will tell me if there were duplicates of the file in the directory the file was created : filename.txt . Example : helloworld (1).txt Windows also has this functionality when trying to create a file duplicate. Is there way I could do this in C++ 17 ?
Since no one is giving me any answers, I decided to spend some time on this function that does what I want , and answer my own question , its in C++ 17 for anyone who thinks this is useful : #include <filesystem> #include <regex> #include <fstream> #include <string> namespace fs = std::filesystem; // Just file "std::ostream::open()" except it handles duplicates too void create_file_dup(std::string path) { // Check if file doesnt have duplicates if (!fs::exists(path)) { std::ofstream(path); return; } // Get filename without path std::string filename = (fs::path(path).filename()).string(); // Since its already a duplicate add "(1)" inbetween the basename and extension filename = (fs::path(filename).stem()).string() + " (1)" + (fs::path(filename).extension()).string(); // Get file's parent directory std::string parent = (fs::path(path).parent_path()).string(); // Loops to check for more duplicates for (int dup_count = 2;!fs::exists(parent + filename);dup_count++) { std::string dup_c = "(" + std::to_string(dup_count); // old number dup_c + ")"; std::string dup_cn = "(" + std::to_string(dup_count + 1); // new number dup_cn + ")"; filename = std::regex_replace(filename, std::regex(dup_c), dup_cn); // increments : '(1)' -> '(2)' } // We have found the how many duplicates there are , so create the file with the duplicate number std::ofstream(parent + filename); return; }
71,658,440
71,658,518
C++17 create directories automatically given a file path
#include <iostream> #include <fstream> using namespace std; int main() { ofstream fo("output/folder1/data/today/log.txt"); fo << "Hello world\n"; fo.close(); return 0; } I need to output some log data to some files with variable names. However, ofstream does not create directories along the way, if the path to the file doesn't exist, ofstream writes to nowhere! What can I do to automatically create folders along a file path? The system is Ubuntu only.
You can use this function: bool CreateDirectoryRecuresive(const std::string & dirName) { std::error_code err; if (!std::experimental::filesystem::create_directories(dirName, err)) { if (std::experimental::filesystem::exists(dirName)) { return true; // the folder probably already existed } printf("CreateDirectoryRecuresive: FAILED to create [%s], err:%s\n", dirName.c_str(), err.message().c_str()); return false; } return true; } (you can remove the experimental part if you have new enough standard library). Documnetation for the methods used in the code: std::filesystem::create_directories. std::filesystem::exists.
71,658,733
71,659,293
How do I avoid the "multiple definition of ..." Error in this case
Boardcomputer.h: #ifndef BOARDCOMPUTER_H #define BOARDCOMPUTER_H #include <Arduino.h> #include <TFT_eSPI.h> TFT_eSPI disp = TFT_eSPI(); ... #endif Boardcomputer.cpp: #include <Boardcomputer.h> ^^use disp functions^^ ... Error: .pio\build\EmmaChip\lib782\libBoardcomputer.a(Boardcomputer.cpp.o):(.bss.disp+0x0): multiple definition of `disp' .pio\build\EmmaChip\src\main.cpp.o:(.bss.disp+0x0): first defined here collect2.exe: error: ld returned 1 exit status *** [.pio\build\EmmaChip\firmware.elf] Error 1 Here is what I tried: make an extra Header-File and add #pragma once at the top make an extra Lib and add the typical #ifndef; #define; #endif lines Do you have some ideas to fix this problem? I don't define 'disp' multiple times. Just in one Header.
The problem is here: #ifndef BOARDCOMPUTER_H #define BOARDCOMPUTER_H #include <Arduino.h> #include <TFT_eSPI.h> TFT_eSPI disp = TFT_eSPI(); ... #endif You define disp in a header file. Defining variables in header files is plain wrong, it cannot work (except if you include the .h file in a single .c file, but then the .h file is pretty pointless anyway) and it leads to these "multiple definition" issues at link time. This happens here: you include Boardcomputer.h in foo.c, therefore foo.o will contain a variable disp. The code compile fine. you include Boardcomputer.h in bar.c, therefore bar.o will contain a variable disp. The code compile fine. you link foo.o and bar.o in order to produce an executable, and the linker sees two variables disp, one in bar.o and one in foo.o, hence the multiple definition error You want this: Boardcomputer.h #ifndef BOARDCOMPUTER_H #define BOARDCOMPUTER_H #include <Arduino.h> #include <TFT_eSPI.h> extern TFT_eSPI disp; // declare it here #endif Boardcomputer.c #include "Boardcomputer.h" ... TFT_eSPI disp = TFT_eSPI(); // define it here ...
71,658,794
71,658,954
Can std::string_view created in function body be returned?
Suppose you have this code #include <iostream> using namespace std; std::string_view foo(){ char arr[3]; arr[0]='0'; arr[1]='1'; arr[2]='\0'; std::string_view sv = arr; return sv; } int main(){ cout<<foo()<<endl; return 0; } Since arr is in the stack, during the creation of sv, sv should point to a location in the stack, therefore, since string_view doesn't copy the content of the internal char array (contrary on what happens on std::string), I would expect an error here, yet it prints correctly 01.
At least it's meaningless to return one. You could do so, but a std::string_view relies on the underlying string representation it provides a view on. If that one has gone out of scope, any member access to the view that results in trying to access the underlying data (so nearly all – maybe size is stored separately, but it could be calculated from two iterators as well) invokes undefined behaviour and in consequence renders your programme invalid. Undefined behaviour, though, can mean anything – sometimes you get away with, observing expected behaviour, sometimes you end up in a crash, sometimes you end up in heavy to debug and locate errors because of the error getting into effect much later at a seemingly totally unrelated place...
71,660,090
71,660,219
Understanding relationship between arrays and pointers
I was recently reading about difference between T* and T[size], T being the type, and it make me curious so I was playing around with it. int main() { int a[10]; using int10arrayPtr_t = int(*)[10]; int10arrayPtr_t acopy = a; } In the above code, int10array_t acopy = a; is an error with message error C2440: 'initializing': cannot convert from 'int [10]' to 'int10array_t' And this compiles: int main() { int a[10]; using int10arrayPtr_t = int*; int10arrayPtr_t acopy = a; } Isnt the type int(*)[10] closer the the type of int a[10]; than int*? So why does it not allow the first case?
Array designators used in expressions with rare exceptions are implicitly converted to pointers to their first elements. So if you have for example an array T a[N]; then you may write T *p = a; because due to the implicit conversion the above declaration is equivalent to T *p = &a[0]; If you apply the address of operator & to an array then you get a pointer dereferencing which you will get the original object. For example T a[N]; T ( *p )[N] = &a; std::cout << sizeof( *p ) << '\n'; the output statement will give the size of the array a. Here is a demonstration program. #include <iostream> #include <iomanip> #include <type_traits> int main() { const size_t N = 10; using T = int; T a[N]; T *p = a; std::cout << "std::is_same_v<T &, decltype( *p )> is " << std::boolalpha << std::is_same_v<T &, decltype( *p )> << '\n'; std::cout << "sizeof( *p ) = " << sizeof( *p ) << '\n'; T( *q )[N] = &a; std::cout << "std::is_same_v<T ( & )[N], decltype( *q )> is " << std::boolalpha << std::is_same_v<T ( & )[N], decltype( *q )> << '\n'; std::cout << "sizeof( *q ) = " << sizeof( *q ) << '\n'; } The program output is std::is_same_v<T &, decltype( *p )> is true sizeof( *p ) = 4 std::is_same_v<T ( & )[N], decltype( *q )> is true sizeof( *q ) = 40
71,660,143
71,660,341
Where can I find a reference to the function write?
I have the following code for the definition of a streambuf class. I have to adapt it to my needs. Before that, I have to understand how the code actually works. Can anyone tell me where I can find a reference to the write function in flushBuffer. It takes 3 parameters and returns an int. std::streambuf does not have such a member... //code taken from: The C++ Standard Library Second Edition, Nicolai M. Josuttis, p. 837 class Outbuf_buffered_orig : public std::streambuf { protected: static const int bufferSize = 10; // size of data buffer char buffer[bufferSize]; // data buffer public: // constructor // - initialize data buffer // - one character less to let the bufferSizeth character cause a call of overflow() Outbuf_buffered_orig() { setp (buffer, buffer+(bufferSize-1)); } // destructor // - flush data buffer virtual ~Outbuf_buffered_orig() { sync(); } protected: // flush the characters in the buffer int flushBuffer () { int num = pptr()-pbase(); if (write (1, buffer, num) != num) { return EOF; } pbump (-num); // reset put pointer accordingly return num; } // buffer full // - write c and all previous characters virtual int_type overflow (int_type c) { if (c != EOF) { // insert character into the buffer *pptr() = c; pbump(1); } // flush the buffer if (flushBuffer() == EOF) { // ERROR return EOF; } return c; } // synchronize data with file/destination // - flush the data in the buffer virtual int sync () { if (flushBuffer() == EOF) { // ERROR return -1; } return 0; } }; //Outbuf_buffered
Can anyone tell me where I can find a reference to the write function This is Linux' ssize_t write(int fd, const void *buf, size_t count), defined in <unistd.h>. See man 2 write for more information. Note: write(1, ...) writes to file descriptor #1: standard output.
71,660,975
71,689,916
How to send ffmpeg AVPacket through WebRTC (using libdatachannel)
I'm encoding a video frame with the ffmpeg libraries, generating an AVPacket with compressed data. Thanks to some recent advice here on S/O, I am trying to send that frame over a network using the WebRTC library libdatachannel, specifically by adapting the example here: https://github.com/paullouisageneau/libdatachannel/tree/master/examples/streamer I am seeing problems inside h264rtppacketizer.cpp (part of the library, not the example) which are almost certainly to do with how I'm providing the sample data. (I don't think that this is anything to do with libdatachannel specifically, it will be an issue with what I'm sending) The example code reads each encoded frame from a file, and populates a sample by setting the content of the file to the contents of the file: sample = *reinterpret_cast<vector<byte> *>(&fileContents); sample is just a std::vector<byte>; I have naively copied the contents of an AVPacket->data pointer into the sample vector: sample.resize(pkt->size); memcpy(sample.data(), pkt->data, pkt->size * sizeof(std::byte)); but the packetizer is falling over when trying to get length values out of that data. Specifically, in the following code, the first iteration gets a length of 1, but the second, looking up index 5, gives 1119887324. This is way too big for my data, which is only 3526 bytes (the whole frame is a single colour so likely to be small once encoded): while (index < message->size()) { assert(index + 4 < message->size()); auto lengthPtr = (uint32_t *)(message->data() + index); uint32_t length = ntohl(*lengthPtr); auto naluStartIndex = index + 4; auto naluEndIndex = naluStartIndex + length; assert(naluEndIndex <= message->size()); auto begin = message->begin() + naluStartIndex; auto end = message->begin() + naluEndIndex; nalus->push_back(std::make_shared<NalUnit>(begin, end)); index = naluEndIndex; } Here is a dump of uint32_t length = ntohl(*lengthPtr); for the first few elements of the message (*lengthPtr in parentheses): [2022-03-29 15:12:01.182] [info] index 0: 1 (16777216) [2022-03-29 15:12:01.183] [info] index 1: 359 (1728118784) [2022-03-29 15:12:01.184] [info] index 2: 91970 (1114046720) [2022-03-29 15:12:01.186] [info] index 3: 23544512 (3225577217) [2022-03-29 15:12:01.186] [info] index 4: 1732427807 (532693607) [2022-03-29 15:12:01.187] [info] index 5: 1119887324 (3693068354) [2022-03-29 15:12:01.188] [info] index 6: 3223313413 (98312128) [2022-03-29 15:12:01.188] [info] index 7: 534512896 (384031) [2022-03-29 15:12:01.188] [info] index 8: 3691315291 (1526728156) [2022-03-29 15:12:01.189] [info] index 9: 83909537 (2707095557) [2022-03-29 15:12:01.189] [info] index 10: 6004992 (10574592) [2022-03-29 15:12:01.190] [info] index 11: 1537277952 (41307) [2022-03-29 15:12:01.190] [info] index 12: 2701131779 (50331809) [2022-03-29 15:12:01.192] [info] index 13: 768 (196608) (I know I should post a complete sample, I am working on it) I am fairly sure I am just missing something basic. E.g. am I supposed to do something with the AVPacket side_data, does AVPacket have or miss some header info? If I just fwrite the pkt->data for a single frame to disk, I can read the codec information with ffprobe: Input #0, h264, from 'encodedOut.h264': Duration: N/A, bitrate: N/A Stream #0:0: Video: h264 (Constrained Baseline), yuv420p(progressive), 1280x720, 30 tbr, 1200k tbn Update: This issue is solved by changing the H264RtpPacketizer separator setting from H264RtpPacketizer::Separator::Length to H264RtpPacketizer::Separator::LongStartSequence, many thanks to author of libdatachannel paullouisageneau (see answer below) I have issues related to settings for the libx264 encoder, but can happily encode with h264_nvenc and h264_mf
The input files of the streamer example for libdatachannel use 32-bit length as NAL unit separator. Therefore, the H264RtpPacketizer instance is created with H264RtpPacketizer::Separator::Length. If I'm not mistaken the ffmpeg output will have 4-byte start sequences as NAL unit prefix instead (which is actually more common), so if you change the packetizer setting to H264RtpPacketizer::Separator::LongStartSequence it should accept your sample.
71,661,263
71,688,947
What's consistency mapping in SLAM?
I always see "consistent mapping" or "map consistency" in SLAM papers and articles, but I have no idea about what consistent map is. I have found enter link description here, but it did not solve my problem. Furthermore, what is local consistentcy and global consistency?
During the mapping, the robot sequentially tries to locate landmarks or objects around it with precise coordinates, both locally and globally. The local consistency of the landmarks in each sequential operation means that their positions relative to the robot and the positions among themselves correspond to reality. The map fragments created at each step are combined to form a meaningful global map. In the meantime, the landmarks determined in the previous step can also take place in the next step. During this merge, if the locations of the landmarks are very different from each other on both local maps, local maps cannot be combined and mapping cannot be made because there will be no consistency. Consistency of both the local and global map is critical, especially in loop closure studies. If the map you created is not consistent, you cannot detect loop closure. In summary, the consistency of your map means that the locations of the same landmarks that you detect at different stages are consistent with each other.
71,661,462
71,661,721
Iterating over types in a variadic template
I have a member function that is templated with a variadic template. The member function wants to push to a container somewhere some information about the types in the variadic template, such as typeid(T) and sizeof(T). The member function should also take in a variable amount of parameters, with each parameter's type being what is specified in the variadic template. Any parameter not explicitly defined should default to a default construction of the type. Basically this, but bar is somehow a variadic template and that code repeats for all of the types in the variadic template. class foo { private: std::unordered_map<std::type_index, std::size_t> typeinfo; public: template<typename T> void bar(T myType = T()) { typeinfo.insert({ typeid(T), sizeof(T) }); // do stuff with myType ... } }; foo myfoo; myfoo.bar<int, double>(); // myType<int> = 0, myType<double> = 0.0; myfoo.bar<char, float>('a'); // myType<char> = 'a', myType<float> = 0.0f; myfoo.bar<double, char>(32.4, 'b'); // myType<double> = 32.4, myType<char> = 'b'
Parameter pack cannot have default argument so template<typename... Ts> void bar(Ts... = Ts()...) // ill-formed What you can do is using 2 parameter-packs class foo { private: std::unordered_map<std::type_index, std::size_t> typeinfo; public: // Us... is non deducible template<typename... Us, typename... Ts> void bar(Ts... /*args*/) { (typeinfo.insert({ typeid(Us), sizeof(Us) }), ...); // You might have to check that Ts... start Us... // use end of Us... for args... } }; void test() { foo myfoo; myfoo.bar<int, double>(); // Us=[int, double], Ts=[] myfoo.bar<char, float>('a'); // Us =[char, float], Ts = [char]; myfoo.bar<double, char>(32.4, 'b'); // Us=[double, char], Ts=[double, int] myfoo.bar<char>(4.2f); // Us =[char], Ts = [float] !!! } Demo To create a tuple with initial part from Us, and remaining defaulted, you might do template <typename T, std::size_t I, typename Tuple> T get_or_default(Tuple&& tuple) { if constexpr (I < std::tuple_size_v<std::decay_t<Tuple>>) { return std::get<I>(std::forward<Tuple>(tuple)); } else { return T{}; } } template<typename... Ts, std::size_t... Is, typename Tuple> std::tuple<Ts...> make_partial_tuple_impl(std::index_sequence<Is...>, Tuple&& tuple) { return {get_or_default<Ts, Is>(std::forward<Tuple>(tuple))...}; } template<typename... Ts, typename... Us> std::tuple<Ts...> make_partial_tuple(Us&&... args) { return make_partial_tuple_impl<Ts...>( std::make_index_sequence<sizeof...(Ts)>{}, std::forward_as_tuple(std::forward<Us>(args)...)); } Demo
71,661,744
71,661,954
How to use openmp reduction with two dimensional vector
I want to parallelised this for loop in c++ with openmp: #pragma omp parallel for reduction(+:A) for (uint k = 0; k < nInd; ++k) { for (uint l = k; l < nInd; ++l) { A.at(k).at(l) = A.at(k).at(l) + frq.at(l); A.at(l).at(k) = A.at(k).at(l); } } But openmp does not know how to add the A which is std::vector<std::vector<float>>. How can I solve this issue? The error is: user defined reduction not found for ‘A’
I can't tell you much about the error, I can tell you that what you're doing is not what you should be doing: Using the bounds-checking A.at(i).at(j) instead of the raw A[i][j] is a bad idea here: you know the length stay constant at the entry of this loop, so just check the lengths once, and then use the faster []. It's especially bad because with at, openmp potentially has to take precautions otherwise unnecessary (exceptions in multi-threaded code are always a bit ... special), and you've got concurrent read access to the vector lengths all the time instead of independent access to the raw memory. Most importantly, however: the inner loop changes the l. row. This means the order of rows being processed by the inner loop matters! That means you cannot accept parallelization. If openmp was allowed to fully parallelize the operations on the rows, this will invariably lead to situations where other threads access memory the individual thread is still read-accessing. I don't see a good solution for this loop. Maybe you want to make two loops out of it: One that just adds the frq values, and one that transposes your matrix. Or, write to a separate matrix instead of doing this in-place in A (whether that works is a question of memory sizes). My general recommendation is that you never actually transpose matrices (unless you really need to ensure a memory access pattern); that's just a waste of CPU. Whatever uses the transposed matrix could also swap its row and column indices at no extra computational cost and you get the transposition "for free". Another recommendation: there's good C++ libraries for linear algebra. Use them. You get well-parallelized (-able) functions, and often, also things like views on data, where transposing does nothing but just change the way addressing works (i.e., is free, basically). std::vector<std::vector<float>> implies you're doing two memory indirections per element access, which is comparably expensive. Your CPU needs much much less time to multiply two floating point numbers than it needs to fetch an address from memory that's not already in cache – hence, you'd really want your complete matrix to be in one continous piece of memory, not distributed around. If you have a use case for openmp, you're investing a lot of effort into making your code run faster. Instead of doing the hard thing (parallelizing) first, you should start by using a better way of representing matrices through std::vector<std::vector<float>>, and accessing them with .at(i).at(j).
71,662,035
71,662,148
Creating a matrix with unique pointers and 'empty'cells
I'm quite new to coding and am running into a problem. I'm working with matrices and previously I had only integers inside them representing the state of a cell. I initiliazed my grid in the following way: const int N = 50; // Grid size // 3 vectors for 3 different antibiotics std::vector<std::vector<int> > gridAB1(N, std::vector<int>(N)); std::vector<std::vector<int> > gridAB2(N, std::vector<int>(N)); std::vector<std::vector<int> > gridAB3(N, std::vector<int>(N)); After which I would change the 0's in these grids at random positions to a certain value. Now I'm moving into a more complex setting where cell state can't be defined as easily as just an integer. I will create a class or struct to represent the cells. I was now recommended to have a grid with at positions (unique) pointers pointing to this struct or class. However I'm very unsure of how to initialize this and how to define between empty places in the grid and places with a cell cause only at a few places in the grid should there actually be a pointer pointing to the struct or class, the rest of the grid would just be "empty". If anyone has any tips or ways of achieving something like this that would be great.
If your data is a class/struct named Cell then the analog to your first example would be #include <memory> #include <vector> std::vector<std::vector<std::unique_ptr<Cell>>> grid(N, std::vector<std::unique_ptr<Cell>>(N)); In this case you can "initialize" a Cell by constructing it such as grid[i][j] = std::make_unique<Cell>(args); or modify a cell similarly grid[i][j]->some_method(); Though if your Cell is "simple" (small, POD, trivially copyable and moveable, etc) I would just store by value std::vector<std::vector<Cell>> grid(N, std::vector<Cell>(N)); Then you'd need some way to determine if the Cell was "filled" yet, like keeping a bool member on the Cell like initialized or something. But the matrix access would look the same grid[i][j] = Cell(args); grid[i][j].some_method();
71,662,126
71,662,309
Force stl container size and declare it as a type
I want to define a std::vector with 2 elements as a type, and export it. Something looking like: template <class T> using Vec2 = std::vector<T>(2); Is it possible to force the size of a container ? If it is, how can I declare it as a type and export it in the whole code when I include its declaration file? Edit: A lot of interesting responses. Thanks to everyone, I will use a typedef struct because I don't really need to access container's member functions.
No. This is not possible because a std::vector<int> of size 2 has the same type as a std::vector<int> of size 42. Vectors are resizable, thats basically what makes them vectors and distinguishes them from std::array. For a container of fixed size 2 you can use arrays: template <class T> using Vec2 = std::array<T,2>;
71,662,814
71,662,860
Can we watch a read/write of/to a variable in C++
I have started learning about templates in C++ and am wondering if there is a way to say print out all the read and write to a particular variable just like we can do in CMake. For example, CMake has variable_watch() which is used to log all attempts to read or modify a variable. So my question is that is there a way to do this in C++. If there is no built-in way(provided by the standard C++), then will it be possible to implement it somehow(if so, how?). I mean, if CMake can have this feature then maybe C++ too. Maybe we can make use of template metaprogramming or something else.
No, you cannot do it in C++ without wrapping your variable in something else that logs for you. But it is possible to do what you need when you are debugging your code written in C++ using hardware breakpoints. You can use watch in gdb to check accesses to your variable. You can check it here or here. These types of breakpoints are available in Visual Studio too.
71,663,050
71,663,480
Brace initialising an inherited struct in VS2019
I have this code fragment; struct x { int thing; }; struct y : x {}; //works, but I need to use struct y struct x test1 { 1 }; //Error //"Only one level of braces is allowed on an initializer for an object of type "y" //no suitable constructor exists to convert from "int" to "y" struct y test { {1} }; //Error //no suitable constructor exists to convert from "int" to "y" struct y test2 { 1 }; //Error // no suitable user-defined conversion from "x" to "y" exists struct y test3 {test1}; //Error // no suitable user-defined conversion from "x" to "y" exists struct y test4 = (struct y)test1; There are many questions on here regarding such code. From them, I discovered that the way I'm trying to initialise struct y test is valid from C++17, and works in later versions of Visual Studio 2017. I've tried to use this in Visual Studio 2019 and I get the results described in the comments. Does anyone know how I can get VS2019 to handle initialisation of an inherited struct? I can't add a constructor to the struct because this is an abstraction of existing code I can't arbitrarily change.
As per the comments on the OP, VS2019 defaults to C++14. To set a project to use different language standard (C++17 in this case) you have to go to project properties->C/C++->Language->C++Language Standard. The same setting is present in VS2017. Thanks to the commenters who helped with this.
71,663,246
71,664,212
Exporting Eigen csr_matrix to python via Pybind11 without converting to scipy.sparse.csc/csr matrix
I would like to export the eigen csr sparse matrix to python in order to perform benchmarks. I'm well aware that the scipy.sparse csr matrix is following the canonical format of a csr matrix, while eigen has a different representation, and that's specifically what I would like to play with. However, when exporting the eigen csr matrix, pybind11 exports it as a scipy.sparse type, which I actually wanted to avoid. I tried the following: typedef Eigen::SparseMatrix< double > TpSpMatrix_csr; py::class_<TpSpMatrix_csr> csr_matrix_eigen(m, "csr_matrix_eigen"); csr_matrix_eigen .def(py::init<>() , "Default constructor" ) .def(py::init<TpSpMatrix_csr>() , "Init with csr matrix" , py::arg("A") ) ; m.def("csr_test", []( TpSpMatrix_csr& A) { std::cout << "csr!"<< std::endl; } , "csr test" , py::arg("A").noconvert() ); After importing it into ipython I get the following: In [2]: A = csr_matrix_eigen() In [3]: csr_test(A) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-3-77568ef56cf5> in <module> ----> 1 csr_test(A) TypeError: csr_test(): incompatible function arguments. The following argument types are supported: 1. (A: scipy.sparse.csc_matrix[numpy.float64]) -> None Invoked with: <eigen_test.csr_matrix_eigen object at 0x7f9e78265af0> Is there a simpler way to achieve this compared to encapsulating the eigen sparse matrix in yet another class? In short, I would like to expose the eigen sparse matrix without scipy.sparse being involved.
o.k., posting questions seems to help. Although I struggled with this problem for some time now, only after posting the question I found a solution, namely, I have to include a PYBIND11_MAKE_OPAQUE(TpSpMatrix_csr); at the top of my pybind interface file. I can now call my test function as desired. I hope that this may help someone else in a similar pronlem.
71,663,765
71,664,421
What exactly is Synchronize-With relationship?
I've been reading this post of Jeff Preshing about The Synchronizes-With Relation, and also the "Release-Acquire Ordering" section in the std::memory_order page from cpp reference, and I don't really understand: It seems that there is some kind of promise by the standard that I don't understand why it's necessary. Let's take the example from the CPP reference: #include <thread> #include <atomic> #include <cassert> #include <string> std::atomic<std::string*> ptr; int data; void producer() { std::string* p = new std::string("Hello"); data = 42; ptr.store(p, std::memory_order_release); } void consumer() { std::string* p2; while (!(p2 = ptr.load(std::memory_order_acquire))) ; assert(*p2 == "Hello"); // never fires assert(data == 42); // never fires } int main() { std::thread t1(producer); std::thread t2(consumer); t1.join(); t2.join(); } The reference explains that: If an atomic store in thread A is tagged memory_order_release and an atomic load in thread B from the same variable is tagged memory_order_acquire, all memory writes (non-atomic and relaxed atomic) that happened-before the atomic store from the point of view of thread A, become visible side-effects in thread B. That is, once the atomic load is completed, thread B is guaranteed to see everything thread A wrote to memory. This promise only holds if B actually returns the value that A stored, or a value from later in the release sequence. as far as I understand, when we ptr.store(p, std::memory_order_release) What we're actually doing is telling both the compiler and the CPU that when running, make it so there will be no way that data and the memory pointed to by std::string* p will be visible AFTER the new value of ptr will be visible to thread t2. And same, when we ptr.load(std::memory_order_acquire) We are telling the compiler and CPU: make it so the loading of ptr will be no later than then loading of *p2 and data. So I don't understand what further promise we have here?
This ptr.store(p, std::memory_order_release) (L1) guarantees that anything done prior to this line in this particular thread (T1) will be visible to other threads as long as those other threads are reading ptr in a correct fashion (in this case, using std::memory_order_acquire). This guarantee works only with this pair, alone this line guarantees nothing. Now you have ptr.load(std::memory_order_acquire) (L2) on the other thread (T2) which, working with its pair from another thread, guarantees that as long as it read the value written in T1 you can see other values written prior to that line (in your case it is data). So because L1 synchronizes with L2, data = 42; happens before assert(data == 42). Also there is a guarantee that ptr is written and read atomically, because, well, it is atomic. No other guarantees or promises are in that code.
71,664,281
71,664,937
How to concatenate two dynamic char arrays?
I have two char arrays defined like this: char* str = new char[size]; How can I concatenate these two without creating an additional array? I wrote the code below but it doesn't work: void append(char* str1, int size1, char* str2, int size2) { char* temp = str1; str1 = new char[size1+size2]; for (int i = 0; i < size1; i++) { *(str1+i) = *(temp+i); } int j = 0; for (int i = size1; i < size1+size2; i++) { *(str1+i) = *(str2+j); j++; } delete[] temp; } I forgot to mention that this is a homework and I MUST do it this way despite the fact that std::string and etc. exist. :(
The problem of my code was not passing the str1 pointer by reference. Here is the corrected code: void append(char*& str1, int size1, char* str2, int size2) { char* temp = str1; str1 = new char[size1+size2]; for (int i = 0; i < size1; i++) { *(str1+i) = *(temp+i); } int j = 0; for (int i = size1; i < size1+size2; i++) { *(str1+i) = *(str2+j); j++; } delete[] temp; }
71,664,385
71,665,926
Directory structure for a C++ template library
I am creating a C++ template library which I intend to use as a vital component in a number of future projects. Due to the size of the library, I am dividing the code between a number of files, some of which are forward declarations and prototypes and some of which are "implementations." Some classes in the library are strictly internal and are not intended to be directly accessed by users (i.e. future me). There seems to (more or less) be an accepted standard directory structure for compiled C++ libraries (decent thread on the topic: Directory structure for a C++ library) but in the case of a template library, all files are technically headers. Is there an accepted directory structure for template libraries? Should I put the public header in /include and private headers and "implementations" in /src ? P.S. I'm sorry if this is common knowledge. If there is a resource I have missed that addresses this topic, feel free to link it and this thread can be promptly closed.
There are a few examples of header only libraries which put everything in the include directory. When it comes to private implementations, there may be a sub-directory or namespace which makes this intent clear to the consumer (something like internal, details, or impl). Adding an accompanying namespace should help separate these implementation details out from the templates the user is expected to consume. One example I can immediately think of is Cereal. As a user, when consuming a header only library, I'd expect to just have to add YourProject/include to my include path to be able to consume your templates.
71,664,439
71,676,754
how to share common resource amongst objects in c++
In C++, I frequently run into this problem and always left confused. Suppose there are multiple levels of classes. Each level is instantiating the class which is a level below. E.g. below level1 instantiates level2_a and b(there are more in real case). Now some operation the leaf level object needs to perform. Simple example, say the leaf level object needs to dump some information onto a status console. And all the leaf level objects need to do this. What is the best way to share this "status console" pointer amongst the objects (there could be 100s of these objects)? Do they all need to store a pointer to it? Or pass the "status console" pointer to some member function call which it can then use to dump a log. Another such example they all need to share a stack onto which they convey some info when they are destroyed? How to share the stack pointer amongst all these leaf level objects Example: class level2_a { <properties here differ from level2_b> public: ~level2_a() { // dump some info into a common stack here } void dump_change_to_value(int newval) { // need a console pointer here // but can't be singleton because there's 1 per window } }; class level2_b { <properties here differ from level2_a> public: ~level2_b() { // dump some info into a common stack here } void dump_change_to_value(int newval) { // need a console pointer here // but can't be singleton because there's 1 per window } }; class level1 { private: level2_a* ml2_a; level2_b* ml2_b; public: <func members..> }; How to accomplish sharing of the stack/console amongst level2_a and b
Usually, I set up the logger in the base class, through a co-class that is often a singleton. I obviously always define some basic loggers: Null logger (don't print anything), Console logger (standard output / error), File logger (merged stdout/stderr or not). It's obvious that, in fact, it's the same class but instanciated with different file handles. The internal singleton instances are stored in a map, where the key part is the tuple of values passed to the getInstance method. Then, once the instance is known, each class using it stores it in a shared_ptr. Default is to set up your logger in the base class, through static attributes that will be used as "default logger" when a new derivated instance is created. But each instance can also set its own, "private" logger, for debug purpose... For example, you can set the "NullLogger" to base class, and set the "FileLogger" to your currently debugged derivated class. And, obviously, the rest of your program can still use a "SysLogger" to continue the normal logs in a centralized place, like rsyslog or anything like this. All this rely only on static members that hold the default values, normal attributes (set in constructor and/or in logger's setter) that are the ones really used, and obviously virtual methods. Note that "default" means "logger connected at instanciation", so changing the default logger isn't propagated to all child instances... Unless you constantly use a ternary operator when accessing logger (with a line similar to (mThisLogger?mThisLogger:sDefLogger)->log(...) that can be put in an inline private, inherited function). The nice part is that you don't have to care about the logger after its initial connection, and it's even propagated automatically if needed (simply needs mutexes/signals to change it without messing up everything). But you can still change the logger for a particular instance, so that you can set a different verbosity level just for this instance, or send the log to a more convenient destination (like a clean console, standalone file, ...) without changing anything else in the code, with something like this: #ifdef _DEBUG // or a "if (isDebug())" if you have such a function... annoyingInstance->setLog(allLoggersNamespace::DebugLogger); annoyingInstance->setLogLevel(Logger::FullTrace); #endif
71,664,795
71,665,063
Does syntax exist to call an unconstrained function that is hidden by a constrained function?
I understand that with concepts, a constrained function (regardless how "loose" the constraint actually is) is always a better match than an unconstrained function. But is there any syntax to selectively call the unconstrained version of f() as in the sample code below? If not, would it be a good idea for compilers to warn about uncallable functions? #include <iostream> template <typename T> requires(true) void f() { std::cout << "Constrained\n"; } template <typename T> void f() { std::cout << "NOT Constrained\n"; } int main() { f<int>(); } https://godbolt.org/z/n164aTvd3
Different overloads of a function are meant to all do the same thing. They may do it in different ways or on different kinds of objects, but at a conceptual level, all overloads of a function are supposed to do the same thing. This includes constrained functions. By putting a constrained overload in a function overload set, you are declaring that this is a valid alternative method for doing what that overload set does. As such, if the constraint matches, then that's the function that should be called. Just like for parameters of different types in regular function overloading. If you want to explicitly call an overload hidden by a constraint, you have already done something wrong in your design. Or more specifically, if some overload is completely hidden by one or more constrained overloads, you clearly have one more overload than you actually needed. If the constraints match, the caller should be 100% fine with getting the constrained overload. And if this isn't the case, your design has a problem. So no, there is no mechanism to do this. Just as there's no mechanism to bypass an explicitly specialized template and use the original version if your template arguments match the specialization.
71,665,474
71,677,814
Sanitize strings expected to be in UTF-8, but which sometimes are not, in C++
We are loading SQLite DBs, into PostgreSQL. SQLite expects UTF-8 strings, but is rather lenient, not enforcing UTF-8-ness. While PostgreSQL is strict, and will fail the transaction with such strings. During tests, once in a while, invalid strings do actually happen, so we must do something. I'd like to detect such strings, and replace the invalid sequences with U+FFFD, in C++. I've looked a little into std::codecvt, but all examples are from one encoding to another, not sanitizing within a single (UTF-8) encoding, and the cppreference.com doc isn't crystal clear to me either... Do note that the plan is to record those anomalies, so that data-managers can go back, after-the-fact, and manually review the strings. In case they do recognize the native (non-UTF-8) encoding of the original strings, to update the automatically sanitize strings (that contains U+FFFD replacement characters). Thus, solutions that are pure SQLite or PostgreSQL are probably not possible (although I'd be happy to read about those too, if any). I've found code that does it manually, but before I go too far into that rabbit hole, is there std-C++17 code that could achieve the above? Portable solution needed (MSVC and GCC). PS: I can detect a non-UTF-8 strings, since std::wstring_convert<std::codecvt_utf8<wchar_t>>::from_bytes throws in that case, but that does not give me the sanitized string, nor does it tell me where the bad sequences are.
I ended up using https://github.com/nemtrif/utfcpp, as suggested by Alan Birtles, since UTFCPP is well documented, and appears stable. That library is header-only, and I wrapped it as shown below. bool isUtf8(std::string_view text, size_t* p_invalid_offset) { size_t local_invalid = 0; size_t& invalid = p_invalid_offset? *p_invalid_offset: local_invalid; invalid = ::utf8::find_invalid(text); return invalid == std::string_view::npos; } std::string sanitizeUtf8(std::string_view text) { return ::utf8::replace_invalid(text); } Also, since invalid UTF-8 text is rather rare in my case, instead of using sanitizeUtf8() systematically, I instead do: size_t invalid = 0; if (!isUtf8(sv, &invalid)) { std::string sanitized{ sv.substr(0, invalid) }; sanitized += sanitizeUtf8(sv.substr(invalid)); // use sanitized } else { // use sv directly } Which speeds things up, since isUtf8() is faster than sanitizeUtf8(), and again the frequency of non-UTF-8 is very low in my case. Performance-wise, I get around 270 and 140 MB/s on Win10 MSVC2019 (for isUtf8() and sanitizeUtf8() respectively); 1'100 and 250 MB/s on RedHat7 GCC9 (older machine though) PS: For completeness, the PostgreSQL error on non-UTF-8 is character_not_in_repertoire "22021".
71,665,487
71,665,905
Disabling PlaySound() that is included by LibCURL
I've been developing with raylib for quite a while now. I've gotten libcurl to work, but it doesn't work with windows.h, because of the functions names overriding others. However, there is a workaround, by mentioning these defines (in curl.h): #define NOGDICAPMASKS - this disables CC_, LC_, PC_, CP_ TC_ RC_ #define NOVIRTUALKEYCODES - this disables VK_ #define NOWINMESSAGES - this disables WM_ EM_ LB_ #define NOWINSTYLES - this disables WS_, CS_, ES_, LBS_, SBS_, CBS_ #define NOSYSMETRICS - this disables SM_ the list goes on an on... Keep in mind that I don't need these, I won't use any of these since I'm trying to make it as cross-platform as I can, only libcurl includes these BUT it doesn't use them in any way. What I am asking is, where could I find a full list of these, and if not a define that STOPS the including of PlaySound(), PlaySoundA(), etc.. and other functions related to sound, since they are interferring with PlaySound() from raylib.
The #defines you mention are Win32 SDK defines. They instruct windows.h (more accurately, various other Win32 headers that windows.h itself #includes) to not define/declare various symbols. The #define you are looking for to omit a declaration of PlaySound(A|W) (in mmsystem.h) is: #define MMNOSOUND Here is the full table of defines in mmsystem.h: * Define: Prevent inclusion of: * -------------- -------------------------------------------------------- * MMNODRV Installable driver support * MMNOSOUND Sound support * MMNOWAVE Waveform support * MMNOMIDI MIDI support * MMNOAUX Auxiliary audio support * MMNOMIXER Mixer support * MMNOTIMER Timer support * MMNOJOY Joystick support * MMNOMCI MCI support * MMNOMMIO Multimedia file I/O support * MMNOMMSYSTEM General MMSYSTEM functions Alternatively: #define WIN32_LEAN_AND_MEAN Which will prevent windows.h from #include'ing a bunch of headers, including mmsystem.h. Where did WIN32_LEAN_AND_MEAN come from?
71,665,563
71,665,779
how to use hDevMode from PRINTDLGA
how to cast HGLOBAL to DEVMODE? I tried like this: PRINTDLG pd; pd.hDevMode = NULL; if(PrintDlg(&pd)){ DEVMODE* test=(DEVMODE*)pd.hDevMode;
Per the PRINTDLGA documentation: hDevMode Type: HGLOBAL A handle to a movable global memory object that contains a DEVMODE structure. So, use GlobalLock() to access the DEVMODE, eg: PRINTDLG pd = {}; pd.lStructSize = sizeof(pd); ... if (PrintDlg(&pd)){ DEVMODE* test = (DEVMODE*) GlobalLock(pd.hDevMode); // use test as needed... GlobalUnlock(pd.hDevMode); GlobalFree(pd.hDevMode); }
71,666,177
71,666,326
Replacing random_shuffle with shuffle: How to make a random number generator with a given distribution
I am moving from C++11 to C++17 and I have to replace random_shuffle with shuffle. But I am facing the following issue: I need to shuffle the contents of a vector using a random number generator with a particular distribution. In my case this is a std::piecewise_linear_distribution. But I don't know how to create a UniformRandomBitGenerator with a given distribution. I tried (link to code) std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; std::mt19937 gen(std::random_device()); std::vector<double> i{0.0, 0.1, 1.0}; std::vector<double> w{0.0, 0.9, 1.0}; std::piecewise_linear_distribution distr(i.begin(), i.end(), w.begin()); shuffle(v.begin(), v.end(), distr(gen)); // error: 'distr' is not a UniformRandomBitGenerator But shuffle requires a generator as a 3rd argument. How can I make this generator have the distribution I want? Most examples over the net, like this one, in cppreference.com present a generator, which feeds a random number into a distribution. With random_shuffle I had to make a function object with the following operator(): // random function with desired PDF (and corresponding CDF) // struct MyRandomFunc { size_t operator() (size_t n) { double rand_num = rand()/RAND_MAX; // 0 <= rand_num <= 1 double num = CDF(rand_num); // where 'CDF' = desired cumulative distribution function return num * n; // 'num' is a random number with the desired PDF } }; std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; std::random_shuffle(v.begin(), v.end(), MyRandomFunc()); // random func with desired pdf
How can I make this generator have the distribution I want? You don't. std::shuffle requires a uniform random bit generator because it is defined as follows: Permutes the elements in the range [first, last) such that each possible permutation of those elements has equal probability of appearance. Emphasis added. What you want is to control the possibility of certain permutations. That's not what shuffle is for, so you're going to have to write the shuffling code yourself. Even if you gave it a class that implemented the interface of URBG, the fact that the bits it generates are non-uniform means that the result of calling the function will be undefined. It might do what you want, or it could do something entirely different.
71,666,268
71,666,660
Stopping multiple threads at once
What do I miss in the program below with threads waiting for a condition_variable_any to determine when to stop ? In the program listed below, the threads stop in an impredictable way; some before the call to notify_all and some don't stop at all. The condition variable used is defined as below: static std::mutex interrupt_mutex; static std::condition_variable_any interrupt_cv; The threads check if it is time to stop as below: std::unique_lock<std::mutex> lock(interrupt_mutex); const auto cv_status = interrupt_cv.wait_for(lock, std::chrono::milliseconds(1000)); const auto timeout_expired = cv_status == std::cv_status::timeout; if (!timeout_expired) { quit = true; } The main thread signals the threads to stop as below: std::unique_lock<std::mutex> lock(interrupt_mutex); interrupt_cv.notify_all(); A possible output looks like: Thread 1> Received interrupt signal at iteration 2 Thread 1> Terminate Thread 2> Received interrupt signal at iteration 2 Thread 2> Terminate Thread 4> Received interrupt signal at iteration 2 Thread 4> Terminate **** Requesting all threads to stop **** Waiting for all threads to complete... Below the complete code that reproduces the problem: #include <thread> #include <vector> #include <mutex> #include <condition_variable> static std::mutex interrupt_mutex; static std::condition_variable_any interrupt_cv; int main() { std::vector<std::thread> thread_handles; for (int thread_idx = 0; thread_idx < 4; ++thread_idx) { thread_handles.emplace_back(std::thread([thread_idx](const int thread_id) { int num_iterations = 0; auto quit = false; while (!quit) { // Fake processing time during the lock for testing purpose std::this_thread::sleep_for(std::chrono::milliseconds(200)); ++num_iterations; // Check if need to stop with a timeout of 200ms { std::unique_lock<std::mutex> lock(interrupt_mutex); const auto cv_status = interrupt_cv.wait_for(lock, std::chrono::milliseconds(1000)); if (const auto timeout_expired = cv_status == std::cv_status::timeout; !timeout_expired) { printf("Thread %2d> Received interrupt signal at iteration %d\n", thread_id, num_iterations); quit = true; } } } printf("Thread %2d> Terminate\n", thread_id); }, thread_idx + 1)); } std::this_thread::sleep_for(std::chrono::seconds(5)); // Signals all threads to stop { printf("**** Requesting all threads to stop ****\n"); std::unique_lock<std::mutex> lock(interrupt_mutex); interrupt_cv.notify_all(); } // Wait until all threads stop printf("Waiting for all threads to complete...\n"); std::ranges::for_each(thread_handles, [](std::thread& thread_handle) { thread_handle.join(); }); printf("Program ends\n"); return 0; }
A condition_variable is meant to signal threads when a condition changes (ie, such as when a shared variable changes value). But your code has no condition. You are trying to use the condition_variable itself as a quit signal, and that is not what it is meant for. notify_all() will only wake up threads that are actively waiting on the condition_variable at that exact moment. Threads that are not waiting on it, because they are busy doing something else, will not receive that signal to terminate. But those threads will need to detect the condition once they are ready to wait. So the condition needs to be something more persistent. That is why your code is not working correctly. In this case, you can simply move your quit variable to global scope, next to the condition_variable and mutex. Setting that quit variable will act as your condition that you can signal waiting threads about. You can then use the overloaded version of wait_for() that will let you check the current state of quit (to ignore spurious awakenings). Try something more like this: #include <thread> #include <vector> #include <mutex> #include <condition_variable> static std::mutex interrupt_mutex; static std::condition_variable_any interrupt_cv; static bool quit = false; int main() { std::vector<std::thread> thread_handles; for (int thread_idx = 0; thread_idx < 4; ++thread_idx) { thread_handles.emplace_back(std::thread([thread_idx](const int thread_id) { int num_iterations = 0; while (true) { // Fake processing time outside the lock for testing purpose std::this_thread::sleep_for(std::chrono::milliseconds(200)); ++num_iterations; // Check if need to stop with a timeout of 1s { std::unique_lock<std::mutex> lock(interrupt_mutex); const bool signaled = interrupt_cv.wait_for(lock, std::chrono::seconds(1), [](){ return quit; }); if (signaled) break; } } printf("Thread %2d> Received interrupt signal at iteration %d\n", thread_id, num_iterations); printf("Thread %2d> Terminate\n", thread_id); }, thread_idx + 1)); } std::this_thread::sleep_for(std::chrono::seconds(5)); // Signals all threads to stop printf("**** Requesting all threads to stop ****\n"); { std::lock_guard<std::mutex> lock(interrupt_mutex); quit = true; } interrupt_cv.notify_all(); // Wait until all threads stop printf("Waiting for all threads to complete...\n"); std::ranges::for_each(thread_handles, [](std::thread& thread_handle) { thread_handle.join(); }); printf("Program ends\n"); return 0; }
71,666,420
71,687,655
what is raylib required libraries in arch linux instead of mesa and
How to install raylib required libraries in the arch. All required libraries are for Debian. what are raylib required libraries for arch? I installed raylib and created a CMakeLists.txt file for creating an executable file after running cmake and making the executable file created, but when I ran it, I got this error INFO: Initializing raylib 4.0 WARNING: GLFW: Error: 65544 Description: Wayland: Failed to connect to display WARNING: GLFW: Failed to initialize GLFW FATAL: Failed to initialize Graphic Device CMakeLists.txt codes cmake_minimum_required(VERSION 3.0.0) project(gamedev) find_package(raylib REQUIRED) add_executable(gamefight main.cpp) target_include_directories(gamefight PRIVATE ${raylib_INCLUDE_DIRS}) target_link_libraries(gamefight PRIVATE ${raylib_LIBRARIES})
I solved the problem with remove glfw-wayland and installing glfw-x11 sudo pacman -S glfw-x11
71,666,712
71,798,486
How to use glClearTexImage for packed depth/stencil textures?
Is it possible to use glClearTexImage to clear a packed depth/stencil texture in OpenGL? And if so, how? I'm using a multisample texture with pixel format GL_FLOAT_32_UNSIGNED_INT_24_8_REV. Attempting to clear the texture with glClearTexImage(textureId, 0, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, GL_FLOAT, nullptr); yields the error GL_INVALID_OPERATION error generated. <format> must be GL_DEPTH_STENCIL for depth-stencil textures. The fact that depth/stencil textures are considered in this error message lets me believe it should be possible somehow. If I change the format parameter to GL_DEPTH_STENCIL, I get the error GL_INVALID_OPERATION error generated. Texture type and format combination is not valid. Am I mixing up the parameters? Or did I miss that clearing of packed textures was not within specs? Using a simple GL_DEPTH_COMPONENT32F instead of the packed format works flawlessly. I also tried creating a texture view with only the depth component and provide its id as first parameter to glClearTexImage, which however yields the same error. I am testing this in an OpenGL 4.6 context on an Nvidia Titan RTX in Windows 10.
I have mixed up the internal format and the data type, which is why I used the wrong parameters. The packed depth/stencil texture can be cleared with glClearTexImage(textureId, 0, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, nullptr);
71,666,733
71,667,207
Initializing a c++ array with another one
struct AType { const byte data[4]; AType(const byte d[]):data{d[0],d[1],d[2],d[3]} {} ... }; const byte SERIALNR[4] = {0,0,9,0xFF}; AType SNr {SERIALNR}; This works, but I consider it a bit ugly. Is there a syntax with a shorter initializer list? And: How to do it, if that magic 4 were a template parameter? The initialization of SERIALNR is just to make the sample complete, my goal is to implement something nice, allowing AType SNr {SERIALNR}; or similar And yes, that thing should be able to be constructed as const, if possible
I think you can do this using a combination std::array and std::initializer_list. Also you can have the size of the array to be a template parameter: using byte = unsigned char; template <int S> struct AType { std::array<byte, S> data; AType(const std::array<byte, S> &d) : data(d) {} AType(const std::initializer_list<byte> &d) { std::copy(d.begin(), d.end(), data.begin()); } }; int main(){ AType<4> SNr1 {0,0,9,0xFF}; // Uses the constructor with initializer_list as parameter AType<4> SNr2 {{0,0,9,0xFF}}; // Uses the constructor with std::array as parameter return 0; } Live example: https://godbolt.org/z/vjKbbr67G
71,666,989
71,667,252
how to call a function when an asynchronous task is already done?
I have a set of classes look like this: class A { public: std::unique_ptr<B> b; void triggerAsynchronously() { // this work is submitted to a queue. b->getC()->signalAsync(); } }; class B { public: std::shared_ptr<C> c; std::shared_ptr<C> getC() const { return c; } void doSomethingWithSignalFromClassC() {} }; class C { public: void signalAsync() { // This function is submitted to a queue, and wait until its turn to be executed. // I want to trigger A::b::doSomethingWithSignalFromC() once this function is done (aka end of this block) } } C::signalAsync() is triggered by A::triggerSignalCAsynchronously(). Note that A::triggerSignalCAsynchronously() returns immediately after submitting works to the queue, but C::signalAsync() is not executed immediately. Once C::signalAsync() is executed and done with its work, it should notify A::b::doSomethingWithSignalFromClassC(). My question is: how to notify B when C::signalAsync() has already finished? From A, we can get a shared_pointer<C>. Therefore, natural approach is to store weak_ptr<B> inside C. However, this does not work as b is a unique pointer. I also think about storing a raw pointer of B inside C, but that seems to go against the unique_ptr design. Also, storing a raw pointer to A in C seems to be bad: class A { void setA() { b->getC()->setA(this); } } I have the feeling that something is wrong with my design. If it were you to solve this problem, which directions would you try?
You need to be very precise with what you are asking for. You say Once C::signalAsync() is executed and done with its work, it should notify A::b::doSomethingWithSignalFromClassC() 'Notify' implies that a thread is waiting somewhere to be woken up to do something - this is complex But you could also mean, I want singalAsync to call a method on an instance of B. This is simple. Not knowing the constraints on these calls (do you wont then all or are some in libraries that you cant change etc) makes it harder. Here is what I would do for the callback case class C { std::shared_ptr<B> callback_; public: C(std::shared_ptr<B> &cb){ callback_ = cb; } void signalAsync() { // noodle noodle noodle callback_->doSomethingWithSignalFromClassC(); } } ie when I construct a C object tell it the obbject to call back on. Alternatively you could pass that as an arg to signalAsync but maybe thats not possible Another idea would be to pass a std::function in the constructor so you dont have to hard code whcih method gets called at the end of signalAsync
71,667,367
71,667,418
Converting German Letters to Uppercase won't work
What is wrong with this code? It does not make them to uppercase, as I want to, if there is a letter in a string such as å, ä or ö. Is there something I'm missing? Is there any way in C++ to make German letters to uppercase in some way with the library? string makeUpperCase(string c) { transform(c.begin(), c.end(), c.begin(), ::toupper); while(c.find("Ä") != string::npos) { c.replace(c.find("Ä"), 2, "ä"); } while(c.find("Å") != string::npos) { c.replace(c.find("Å"), 2, "å"); } while(c.find("Ö") != string::npos) { c.replace(c.find("Ö"), 2, "ö"); } return c; }
You are searching for uppercase letters and replacing them with lowercase letters. If you want to make the letters to uppercase, you have to do the opposite. string makeUpperCase(string c) { transform(c.begin(), c.end(), c.begin(), ::toupper); while(c.find("ä") != string::npos) { c.replace(c.find("ä"), 2, "Ä"); } while(c.find("å") != string::npos) { c.replace(c.find("å"), 2, "Å"); } while(c.find("ö") != string::npos) { c.replace(c.find("ö"), 2, "Ö"); } return c; }
71,667,709
71,669,226
Addition of Matrix in C++ using OOP
the following code is not giving the correct output. Matrix data is displaying perfectly, but after the addition of two objects M1 and M2, it did not display the correct output. If I use setData to input data in the matrix, data is stored perfectly, but the addition is not performing correctly. kindly suggest to me how can I correct this logical error? #include <iostream> #include <string.h> using namespace std; class Matrix{ private: void Allocate(); int noOfRows; int noOfColumns; int **data; public: Matrix(int noOfRows, int noOfColumns); void setData(); void displayData(); ~Matrix(); Matrix (const Matrix &ref); Matrix operator + (const Matrix &m); void operator = (const Matrix &M ); Matrix& operator = (int x); }; Matrix::Matrix(int inr=0, int inc=0){ noOfRows=inr; noOfColumns=inc; Allocate(); } Matrix::Matrix (const Matrix &ref){ Allocate(); for(int r=0;r<ref.noOfRows;r++) for(int c=0;c<ref.noOfColumns;c++) data[r][c]=ref.data[r][c]; } void Matrix :: operator = (const Matrix &M ) { Allocate(); noOfRows = M.noOfRows; noOfColumns = M.noOfColumns; data=M.data; } Matrix& Matrix :: operator = (int x){ Allocate(); for(int r=0;r<noOfRows;r++) for(int c=0;c<noOfColumns;c++) data[r][c]=x; return *this; } void Matrix::Allocate(){ data=new int*[noOfRows]; for(int i=0;i<noOfRows;i++) data[i]=new int[noOfColumns](); } void Matrix::setData(){ for(int r=0;r<noOfRows;r++){ for(int c=0;c<noOfColumns;c++){ cout<<"Enter ...";cin>>data[r][c]; } cout<<endl; } } Matrix Matrix::operator + (const Matrix &m){ Matrix ms(m.noOfRows,m.noOfColumns); for (int i=0; i<m.noOfRows; i++) for (int j=0; j<m.noOfColumns; j++) ms.data[i][j] = data[i][j]+m.data[i][j]; return ms; } void Matrix::displayData(){ for(int r=0;r<noOfRows;r++){ for(int c=0;c<noOfColumns;c++) cout<<data[r][c]<<"\t"; cout<<endl; } } Matrix::~Matrix(){ for (int i = 0; i < noOfRows; ++i) delete[] data[i]; delete [] data; } int main(){ Matrix M3(2,2);M3=0; Matrix M1(2,2);M1=1; Matrix M2(2,2);M2=2; //M1.setData();M2.setData();M3.setData(); cout<<"\n Matrix A = "<<endl; M1.displayData(); cout<<"\n Matrix B = "<<endl; M2.displayData(); cout<<"\n Matrix C = "<<endl; M3 = M1; M3.displayData(); cout<<"\n Sum of Matrix = "<<endl; M3 = M1 + M2; M3.displayData(); return 0; } Output is here for detail
Copy constructor and assignment operator were both broken. Let's take a quick stroll to see what went wrong Matrix::Matrix (const Matrix &ref){ // noOfRows and noOfColumns have not been initialized. Their values are unknown so // the rest of this function is a crapshoot. Could do anything. Allocate(); for(int r=0;r<ref.noOfRows;r++) for(int c=0;c<ref.noOfColumns;c++) data[r][c]=ref.data[r][c]; } // An assignment operator is expected to return Matrix & void Matrix :: operator = (const Matrix &M ) { // noOfRows and noOfColumns have not been updated. Could be wrong, resulting in // allocate allocating the wrong amount of storage. Moot point since this // allocation is never used. See below. Allocate(); noOfRows = M.noOfRows; noOfColumns = M.noOfColumns; data=M.data; // both instances share M's data. This will fail sooner or later // If the program lives long enough, both instances will go out // of scope and double delete the allocation. // Also leaks allocation pointed at by `data`. } I was in a hurry so I didn't put much thought into fixing the assignment operator and just used the Copy and Swap Idiom. It's very possible that there is a more efficient solution, but copy and swap is usually fast enough and almost impossible to get wrong. Makes a great starting point and benchmarking will tell you if it's a problem. Matrix::Matrix(const Matrix &ref): noOfRows(ref.noOfRows), noOfColumns(ref.noOfColumns) // initialize row and columns { Allocate(); // now safe to use for (int r = 0; r < ref.noOfRows; r++) for (int c = 0; c < ref.noOfColumns; c++) data[r][c] = ref.data[r][c]; } Matrix& Matrix::operator =(Matrix M) // correct return type, and does the heavy // lifting with the copy constructor { std::swap(noOfRows, M.noOfRows); std::swap(noOfColumns, M.noOfColumns); std::swap(data, M.data); return *this; }
71,668,756
71,670,478
Convert spatstat functions to C++ to circumvent memory-limitation
I am using spatstat to estimate the risk of pest introduction and spread from roads, highways, and other roadways. However, I believe I am running into memory-limitation issues; my data is at a continental scale and my computer only has 16 GB of memory. The warning message I receive when running spatstat's as.owin() and density.psp() functions is: Error: cannot allocate vector of size X.X. Gb Some colleagues of mine have suggested I might be able to lessen the memory-burden by converting the spatstat functions as.owin() and density.psp() to execute via C++ with the rcpp package. This technique is well outside of my comfort zone and I was hoping to get a sense from StackOverflow on whether or not it's even feasible before I dedicate many hours to it. Specifically, my questions are: Has anyone converted spatstat functions to C++? How have other spatstat users worked around memory-limitation issues? Any help and guidance would be greatly appreciated. Many thanks, Josh
Firstly I strongly agree with the poster who said that the quick fix is not to edit the code but to throw more computing resources at the existing code. It can be fiddly to use a cloud computing service, but it will take much more time to re-implement, test, and validate a completely new source code. But anyway: The first thing to check is whether the pixel images that you want to create are too big to store in R memory at all. Try just creating Z <- as.im(R, dimyx=d) where R is a rectangle containing your spatial domain and d is the dimensions (rows, columns) of the desired image. If that fails with a message about memory limits, then you're going to need a bigger boat -- I mean, computer. The function density.psp has options method="FFT" (the default) and method="C". Have you tried both of these? The FFT method uses more memory because it does the whole calculation in one enormous Fourier transform (after expanding the domain to several times its original size). The C method is a loop over all pixels and all segments; it is slower, but requires relatively little memory, apart from the storage for the output raster data. If method="C" fails because of insufficient memory, this would again suggest that the raster images you're trying to create are too large to store in R memory. The function as.owin is generic, with 28 methods. Which method is giving you trouble? What data are you converting to an owin? spatstat is already written in a mix of R, C and C++. We are constantly looking for ways to accelerate the code and reduce the memory demand. If you have identified a particular case where the code is slow, we would like to know the details. If you do spot a way to fix or accelerate some of the code, please share it.
71,669,328
71,669,558
Unpacking a container of variant into a variant of containers, combined with the inner variant types
Some code will help making sense: #include <variant> #include <vector> #include <string> using MyType = std::variant<int, float, string>; using ContainerOfMyType = std::vector<MyType>; using MySuperType = std::variant<MyType, ContainerOfMyType>; Instead of having MySuperType being a std::variant of another std::variant and a std::vector of std::variant, I would like to have all types unpacked into a single std::variant deriving from MyType. So the expected result in that case would be (written manually): using MySuperType = std::variant<int, float, string, std::vector<int>, std::vector<float>, std::vector<string>>; Is it possible? How can I achieve this?
I would like to declare a new variant type that contains all these base types, plus vector of each of these base types. Template partial specialization should be enough #include <variant> #include <vector> template<class Var> struct MySuper; template<class... Args> struct MySuper<std::variant<Args...>> { using type = std::variant<Args..., std::vector<Args>...>; }; Demo
71,669,426
71,669,456
Why don't I have access to the private values of a class through a friend function?
I create a class, and in the class I declare a friend function so that I can later change a private value with an if..else statement, though I can't even change it without the if..else. #include <iostream> using namespace std; class A { private: float money; friend void _setMoney(A a, float i); public: void setMoney(float i) { money = i; }; float getMoney() { return money; }; A(float i) { i = money; }; }; void _setMoney(A a, float i) { a.setMoney(i); }; int main(){ A a(0); cout << a.getMoney() << endl; a.setMoney(10); cout << a.getMoney() << endl; _setMoney(a, 20); cout << a.getMoney() << endl; } After executing this in VS Code, I get 0, 10, 10 instead of 0, 10, 20.
The problem is not with _setMoney() being a friend or not. If that were the issue, your code would not even compile. The real issue is that you are passing the a object in main() by value to _setmoney(), so you are passing in a copy of the object, and are then modifying the copy rather than the original object. Simply pass the object by reference instead: void _setMoney(A& a, float i) { a.setMoney(i); }; That being said, A::setMoney() is public, so _setMoney() does not need to be a friend of A in order to call it. Only if _setMoney() wanted to access A::money directly, eg: void _setMoney(A& a, float i) { a.setMoney(i); // <-- friend not required for this a.money = i; // <-- friend required for this };
71,669,791
71,684,475
Android Asset FileNotFound Exception Using Kotlin and Android NDK C++
I am trying to read .obj files in the assets/ folder by passing the AssetManager object from my Kotlin script to the JNI interface, where I can use C++ to parse the .obj files and add it to my OpenGL scene. But the app is not finding any files in my assets folder. I grab the AssetManager and attempt to pass it to my JNI inside of my renderer class, under the OnSurfaceCreated callback: Kotlin File: private external fun loadModels(assetManager: AssetManager): Void //Loaded correctly from companion object private lateinit var manager: AssetManager override fun onSurfaceCreated(unused: GL10, config: EGLConfig?) { manager = Resources.getSystem().assets //Gets the asset manager (poorly documented) loadModels(manager) manager.open("hello.txt") //Throws FileNotFoundException } C++ file: #include <jni.h> #include <android/log.h> #include <android/asset_manager.h> #include <android/asset_manager_jni.h> extern "C" JNIEXPORT jobject JNICALL Java_com_example_mypackage_glRenderer_loadModels(JNIEnv *env, jobject thiz, jobject asset_manager) { AAssetManager* pAssetManager = AAssetManager_fromJava(env, asset_manager); if (pAssetManager == nullptr) { __android_log_print(ANDROID_LOG_ERROR, "GL_JNIConnector.cpp", "Failed to load asset manager"); //Break exit(1); } //Loop through all files in Models folder AAssetDir* pModelsDirectory = AAssetManager_openDir(pAssetManager, "Models/"); //AAssetDir_rewind(pModelsDirectory); const char* filename = AAssetDir_getNextFileName(pModelsDirectory); //Incorrectly returns NULL __android_log_print(ANDROID_LOG_DEBUG, "GL_JNIConnector.cpp", "%s", filename); } But my AAssetDir_getNextFileName(pModelsDirectory) keeps returning NULL, when the files are present in my assets folder, AND unzipping the .apk file also shows they were added to the app correctly. I tested it within the Kotlin by making up a hello.txt file and trying to access it in Kotlin using manager.open("hello.txt") and this also throws a FileNotFoundException This is my directory: Even hovering over the filename in my code points to the file in my assets folder, why can't the app find it in runtime? Pulling apart the APK with Android Studio shows my assets folder intact in the .apk file
The issue was I grabbed my asset manager using manager = Resources.getSystem().assets which only gets me access to system resources, not application resources. Instead, I should have passed my context from my surface view class to the renderer class //Surface View Class class glSurfaceView(context: Context, attrs: AttributeSet) : GLSurfaceView(context, attrs) //Renderer Class class glRenderer(private val context: Context) : GLSurfaceView.Renderer so that I could get my asset manager simply using manager = context.assets Thanks to @Michael for pointing that out
71,670,476
71,675,622
How do I cast a typename variable parameter as a string
The problem: I am trying to create a function capable of finding the largest number if the array is an integer, double, float, etc. If the array given is a string it returns the string in the string with the most letters. However, I don't know how to cast list [0] and list[i] as strings. #include <isostream> #include <algorithm> using namespace std; unsigned int strlength(string word) { char *ch = &word[0]; unsigned int count = 0; while (*ch != '\0') { count++; ch++; } return *count; } template<typename U> U maxNumber(U list[], int size) { unsigned int i; if (typeid(list) == typeid(string*)) { unsigned int i; for (i = 0; i < size; i++) { if (strlength(list[0]) < strlength(list[i])) { list[0] = list[i]; } else { list[0] = list[0]; } } return list[0]; } else { for (i = 0; i < size; i++) { if (list[0] < list[i]) { list[0] = list[i]; } else { continue; } } return list[0]; } }
if (typeid(list) == typeid(string*)) is the wrong tool. You need compile time branch, either with if constexpr template<typename U> U maxNumber(U list[], int size) { if constexpr (std::is_same_v<U, std::string>) { auto less_by_size = [](const auto& lhs, const auto rhs){ return lhs.size() < rhs.size(); }; return *std::max_element(list, list + size, less_by_size); } else { return *std::max_element(list, list + size); } } or via overload/tag dispatching std::string maxNumber(std::string list[], int size) { auto less_by_size = [](const auto& lhs, const auto rhs){ return lhs.size() < rhs.size(); }; return *std::max_element(list, list + size, less_by_size); } template<typename U> U maxNumber(U list[], int size) { return *std::max_element(list, list + size); }
71,670,859
71,671,030
Is it OK to share a QLineEdit between Layouts?
I'm debugging some code that uses the same QLineEdit between two layout boxes. Is this legal? It looks like the 2nd layout box is grabbing control, and they don't render in the first layout. But I can't find any documentation to say whether this is a valid use-case, and (perhaps) something else is wrong. Pseudocode: QLineEdit *valueEdit = new QLineEdit(); [...] QGridLayout *layout1 = new QGridLayout(); QGridLayout *layout2 = new QGridLayout(); [...] layout1->addWidget( valueEdit, 0, 0, Qt::AlignLeft ); layout2->addWidget( valueEdit, 0, 0, Qt::AlignLeft ); // same edit, 2x layouts, possible? I suspect the code is trying to re-use the edit field, so it only needs to read update values from one set of widgets. (But I'm only guessing.) During execution, only ever one of the layouts is visible at a time.
It's safe to do, but it won't result in the QLineEdit appearing in both locations. If you look in the QLayout::addChildWidget(QWidget * w) method of qlayout.cpp, you'll see this code: void QLayout::addChildWidget(QWidget *w) { QWidget *mw = parentWidget(); QWidget *pw = w->parentWidget(); if (pw && w->testAttribute(Qt::WA_LaidOut)) { QLayout *l = pw->layout(); if (l && removeWidgetRecursively(l, w)) { #ifdef QT_DEBUG if (Q_UNLIKELY(layoutDebug())) qWarning("QLayout::addChildWidget: %s \"%ls\" is already in a layout; moved to new layout", w->metaObject()->className(), qUtf16Printable(w->objectName())); #endif } } if (pw && mw && pw != mw) { #ifdef QT_DEBUG if (Q_UNLIKELY(layoutDebug())) qWarning("QLayout::addChildWidget: %s \"%ls\" in wrong parent; moved to correct parent", w->metaObject()->className(), qUtf16Printable(w->objectName())); #endif pw = nullptr; } As the debug messages indicate, on the second call to addWidget(), the widget will be moved out of its old parent-widget and layout and into the new one.
71,670,869
71,671,085
Why does left justification not work in the first iteration of a loop?
#include <iostream> int main(){ using namespace std; string s1("Hello1"); string s2("Hello2"); for(int i = 0; i < 3; i++){ cout.width(20); cout<<"Some String:"<<left<<s1<<endl; cout.width(20); cout<<"Another String:"<<left<<s2<<endl; cout<<endl; } return 0; } Here is my code. It, to my knowledge, should print s1 and s2 20 characters from the very left of the screen. However, it prints Some String:Hello1 Another String: Hello2 Some String: Hello1 Another String: Hello2 Some String: Hello1 Another String: Hello2 I am using onlineGDB to compile, as per instruction of my teacher. What error am I making?
std::left is a "sticky" manipulator, meaning you just set it once. By default, padded strings will be right-justified, which is what happens when you output "Some String:" before ever applying the std::left manipulator. See the documentation which states: The initial default for standard streams is equivalent to right. Fixing your code, and tidying it up a bit: #include <iostream> #include <iomanip> int main() { using namespace std; string s1("Hello1"); string s2("Hello2"); cout << left; for(int i = 0; i < 3; i++) { cout << setw(20) << "Some String:" << s1 << endl; cout << setw(20) << "Another String:" << s2 << endl; cout << endl; } return 0; } Output: Some String: Hello1 Another String: Hello2 Some String: Hello1 Another String: Hello2 Some String: Hello1 Another String: Hello2 Note that I used std::setw I/O manipulator from <iomanip> instead of the call to cout.width(). This makes the code easier to read and follow. See the documentation for std::setw
71,671,194
71,671,208
Error while using auto as the function return type
I am learning C++ using the resources listed here. In particular, i read that we can use the auto type specifier as the return type of a function. So to get clarity over the concept, i tried the following example: header.h #pragma once struct S { auto f(); }; source.cpp #include "header.h" auto S::f() { return 4; } main.cpp #include <iostream> #include "header.h" int main() { S s; s.f(); return 0; } But this gives me error saying: main.cpp:7:9: error: use of ‘auto S::f()’ before deduction of ‘auto’ 7 | s.f(); | ^ My question is why am i getting this error and how to solve this.
The problem is that the function definition must be visible at any point where the function(with auto return type as in your case) is used. Since you've defined(implemented) that member function inside a source file(.cpp), it is not visible when the call expression s.f() is encountered. To solve this you can put the implementation of the member function inside the header and make use of inline keyword as shown below: header.h #pragma once struct S { auto f(); }; inline auto S::f() //note the use of inline to avoid multiple definition error { return 4; } Note that we've used inline because we've implemented the member function in a header file which will be included in many other source files. That is, to avoid multiple definition error.
71,671,400
71,671,469
Print a #define macro using std::cout
I am trying to do this #define _TEST_ test #include <iostream> int main() { std::cout << "_TEST_" << std::endl; } As far as my understanding, I expect this output. test However, the output I get is _TEST_ Why am I doing wrong here?
"_TEST_" is a string literal and not a macro. So no macro replacement will be done due to "_TEST_". To achieve your expected output you need to remove the surrounding double quotes and also change the macro to as shown below //-------------vvvvvv--->double quotes added here #define _TEST_ "test" #include <iostream> int main() { //-------------------vvvvvv---------------> not withing quotes std::cout << _TEST_ << std::endl; } The output of the above modified program is: test Demo Explanation In the modified program, the macro _TEST_ stands for the string literal "test". And thus when we use that macro in the statement std::cout << _TEST_ << std::endl;, it will be replaced by the string literal, producing the expected output.
71,671,604
71,671,702
Selection Sort Implementation with C++ incorrect
really new to C++, trying to instantiate some basic algorithms with it. Having trouble returning the correct result for selection sort. Here is my code #include <iostream> #include <array> #include <vector> using namespace std; // Selection Sort : int findMin(vector<int> &arr, int a) { int m = a; for (int i = a + 1; i < arr.size(); i++) { if (arr[i] < arr[m]) { m = i; } return m; } } void swap(int &a, int &b) { int temp = a; a = b; b = temp; } void selectionSort(vector<int> &arr) { if (!arr.empty()) { for (int i = 0; i < arr.size(); ++i) { int min = findMin(arr, i); swap(arr[i], arr[min]); // Assume a correct swap function } } } void print(vector<int> &arr) { if (!arr.empty()) { for (int i = 0; i < arr.size(); i++) { cout << arr[i] << ""; cout << endl; } } } int main() { vector<int> sort; sort.push_back(2); sort.push_back(1); sort.push_back(7); sort.push_back(4); sort.push_back(5); sort.push_back(3); print(sort); cout << "this was unsorted array"; cout << endl; cout << findMin(sort, 0); cout << "this was minimum"; cout << endl; selectionSort(sort); print(sort); } I am getting the following results: comparison_sort.cpp:20:1: warning: non-void function does not return a value in all control paths [-Wreturn-type] } ^ 1 warning generated. 2 1 7 4 5 3 this was unsorted array 1 this was minimum 1 2 4 5 3 0 My question is: What is causing this control path error? Why is the "7" here being replaced with a "0"? Thanks in advance! Sorry for the noob question. I have reviewed all my current functions and nothing seems to explain why the 7 is replaced with a 0. I have tried multiple integers and it looks like the maximum number is always replaced.
The warning is very real, and it alludes to the problem that's breaking your sort as well. You are currently returning m inside your loop body. What that means is that if the loop is entered, then the function will return m on the very first time around the loop. It only has a chance to check the first element. And of course, if a is the last index of the array, then the loop will never execute, and you will never explicitly return a value. This is the "control path" which does not return a value. It's quite clear that you've accidentally put return m; in the wrong place, and even though you have good code indentation, some inexplicable force is preventing you from seeing this. To fix both the warning and the sorting issue, move return m; outside the loop: int findMin(vector<int> &arr, int a) { int m = a; for (int i = a + 1; i < arr.size(); i++) { if (arr[i] < arr[m]) { m = i; } } return m; }
71,671,923
71,673,426
Why is the trailing return type necessary in this lambda expression?
Consider the following code: #include <iostream> #include <type_traits> #include <functional> #include <utility> template <class F> constexpr decltype(auto) curry(F&& f) { if constexpr (std::is_invocable_v<decltype(f)>) { return std::invoke(f); } else { return [f = std::forward<std::decay_t<F>>(f)]<typename Arg>(Arg&& arg) mutable -> decltype(auto) { return curry( [f = std::forward<std::decay_t<F>>(f), arg = std::forward<Arg>(arg)](auto&& ...args) mutable -> std::invoke_result_t<decltype(f), decltype(arg), decltype(args)...> // #1 { return std::invoke(f, arg, args...); }); }; } } constexpr int add(int a, int b, int c) { return a + b + c; } constexpr int nullary() { return 1; } void mod(int& a, int& b, int& c) { a = 1; b = 2; c = 3; } int main() { constexpr int u = curry(add)(1)(2)(3); constexpr int v = curry(nullary); std::cout << u << '\n' << v << std::endl; int i{}, j{}, k{}; curry(mod)(std::ref(i))(std::ref(j))(std::ref(k)); std::cout << i << ' ' << j << ' ' << k << std::endl; } With the trailing return type, the code can compile and outputs: (godbolt) 6 1 1 2 3 If you remove the seemingly redundant trailing return type (line #1 in the above code) and let the compiler to deduce the return type, however, the compiler starts compilaning that error C2672: 'invoke': no matching overloaded function found (godbolt), which surprise me. So, why is the trailing return type necessary in this lambda expression?
If you explicitly give the return type and std::is_invocable_v<decltype(f), decltype(arg), decltype(args)...> is false SFINAE applies and a test for whether or not the lambda is callable will simply result in false. However without explicit return type, the return type will need to be deduced (in this case because of std::is_invocable_v<decltype(f)> being applied to the lambda) and in order to deduce the return type the body of the lambda needs to be instantiated. However, this also instantiates the expression return std::invoke(f, arg, args...); which is ill-formed if std::is_invocable_v<decltype(f), decltype(arg), decltype(args)...> is false. Since this substitution error appears in the definition rather than the declaration, it is not in the immediate context and therefore a hard error.
71,671,963
71,672,233
Array reference binding vs. array-to-pointer conversion with templates
This code sample fails to compile due to ambiguous overload resolution void g(char (&t)[4]) {} void g(char *t) {} int main() { char a[] = "123"; g(a); } and careful reading of overload resolution rules makes it clear why it fails. No problems here. If we formally transform it into a template version template <typename T> void g(T (&t)[4]) {} template <typename T> void g(T *t) {} int main() { char a[] = "123"; g(a); } it will continue to behave "as expected" and fail with an ambiguity of the same nature. So far so good. However, the version below compiles without any issues and choses the second overload template <typename T> void g(T &t) {} template <typename T> void g(T *t) {} int main() { char a[] = "123"; g(a); } If we comment out the second overload, the first one will be used successfully with T deduced as char [4], i.e. template argument deduction works as expected for the first version, effectively making it equivalent to void g(char (&t)[4]). So, on the first naive sight this third example should behave the same as the previous two. Yet, it compiles. What [template] overload resolution rule kicks in in this third case to save the day and direct the compiler to choose the second overload? Why does it prefer array-to-pointer conversion over direct reference binding? P.S. I find quite a few questions on SO that target very similar issues, but they all seem to differ in some important nuances.
The second overload is more specialized than the first one during partial ordering of function templates. According to [temp.deduct.partial]/5 the reference on T &t of the first overload is ignored during template argument deduction performed for partial ordering. The following paragraphs distinguish based on reference/value category only if both parameters are reference types. Then T of the first overload can always deduce against a type A* invented from the parameter of the second overload, but T* of the second overload can't deduce against a type A invented from the parameter of the first overload. Therefore the second overload is more specialized and is chosen. With T (&t)[4] argument deduction in both directions will fail because deduction of T[4] against A* will fail and so will deduction of T* against A[4]. Array-to-pointer decay of the array type is specified for template argument deduction for a function call but not for template argument deduction for partial ordering. See also active CWG issue 402. So neither template will be more specialized in this case and the partial ordering tiebreaker does not apply. The array-to-pointer conversion is not relevant. It is not considered any worse than the identity conversion sequence (see [over.ics.rank]/3.2.1 excluding lvalue transformations which array-to-pointer conversions are).
71,672,091
71,675,220
How to implement a get<T>() similar to that in nlohmann/json?
I'm writing a json library that has the same usage as nlohmann/json. But I'm having trouble understanding nlohmann's get() function. So I implemented a get() myself, but I think that my method is not very good, do you have any good solutions or suggest? #include <vector> #include <iostream> #include <vector> #include <string> #include <map> using namespace std; bool func(bool) { return 1; } int func(int) { return 2; } double func(double) { return 3; } string func(string&) { return string("4"); } vector<int> func(vector<int>&) { return { 5 }; } map<int, int> func(map<int, int>&) { map<int, int>a; a.emplace(6, 6); return a; } template <typename T> T get() { static T t; return func(t); } int main() { cout << get<bool>(); cout << get<int>(); cout << get<double>(); cout << get<string>(); cout << get<vector<int>>()[0]; cout << get<map<int, int>>()[6]; }
Your way works, but requires default constructible types (so no void, reference, ...), types which do "nothing" (a RAII object using global mutex would be problematic for example). Even a log might be strange. You should care about conversion/promotion with overloading resolution (get<char> is ambiguous from your types, get<void(*)()> would call func(bool), but fortunately would fail to compile too because of return type) As alternative: as your set of types seems limited and no extensible, you might used if constexpr: template <typename T> T get() { if constexpr (std::is_same_v<T, bool>) { return true; } else if constexpr (std::is_same_v<T, int>) { return 42; } else if constexpr (std::is_same_v<T, double>) { return 4.2; } else if constexpr (std::is_same_v<T, std::string>) { return "Hello world"; } else if constexpr (std::is_same_v<T, std::vector<int>>) { return {4, 8, 15, 16, 23, 42}; } else if constexpr (std::is_same_v<T, std::map<int, int>>) { return {{1, 2}, {3, 4}}; } else { static_assert(always_false<T>::value); } } or (full) specialization: template <typename T> T get(); // No impl, to specialize template <> bool get() { return true; } template <> int get() { return 42; } template <> double get() { return 4.2; } template <> std::string get() { return "Hello world"; } template <> std::vector<int> get() { return {4, 8, 15, 16, 23, 42}; } template <> std::map<int, int> get() { return {{1, 2}, {3, 4}}; } Reusing your idea of dispatching but with a tag. (that allows extensible set of types, and template implementation) template <typename T> struct tag {}; bool func(tag<bool>) { return true; } int func(tag<int>) { return 42; } double func(tag<double>) { return 4.2; } std::string func(tag<std::string>) { return string("Hello world"); } std::vector<int> func(tag<std::vector<int>>) { return {4, 8, 15, 16, 23, 42}; } std::map<int, int> func(tag<std::map<int, int>>) { return {{1, 2}, {3, 4}}; } #if 0 // Allow extension and template template <typename T> UserTemplateType<T> func(tag<UserTemplateType<T>>) { return {}; } #endif template <typename T> T get() { return func(tag<T>{}); }
71,672,597
71,672,773
Can't find where this std::logic_error is coming from
My application works just fine when I have defined the CAMERA_NAME environment variable, but as soon as I remove that variable from my docker-compose file, the container will return a very useless error message that doesn't give me information such as what variable/line the error is occurring on: basler-hd | terminate called after throwing an instance of 'std::logic_error' basler-hd | what(): basic_string::_M_construct null not valid Here is the relevant code: try { char const* camera_name_ = std::getenv("CAMERA_NAME"); if (!camera_name_) camera_name_ = generate_uuid_v4().c_str(); init_loggers(camera_name_); SPDLOG_INFO("Camera name (found in environment or was generated): {}", camera_name_); SPDLOG_INFO("Starting Application."); PylonInitialize(); mqtt::async_client client(DEFAULT_SERVER_ADDRESS, CLIENT_ID, PERSIST_DIRECTORY); auto willMessage = mqtt::message("nssams/camera", "Camera Disconnected", 1, true); auto connectionOptions = mqtt::connect_options_builder() .clean_session() .will(willMessage) .finalize(); std::string ip_address = std::getenv("IP_ADDRESS") != NULL ? std::string(std::getenv("IP_ADDRESS")) : "192.168.0.1"; if (ip_address.compare("192.168.0.1") == 0) SPDLOG_WARN("No IP address was found in environment, setting to '192.168.0.1'"); std::string camera_name(camera_name_); // Instantiate Camera instance and connect. Camera::MqttBaslerCamera camera( client, camera_name ); try { camera.discover_and_create_device(ip_address); } catch (Camera::MqttBaslerCamera::DeviceNotFoundException & ex){ SPDLOG_CRITICAL("No device found matching IP [{}] from environment", ip_address); PylonTerminate(); return 1; } camera.connect(); // Assign the Camera instance as the mqtt callback handler. client.set_callback(camera); I am just struggling to see what the issue is. I am checking for NULL after I attempt to get a value from the CAMERA_NAME environment variable. If it's NULL, I am setting it to a value before I move on. I just can't tell where it's crashing because the error message is so vague, and if I add any log/cout statements, they won't even run due to this error so I can't tell at what point it's crashing
To see where the error is from you could use a debugger to step through the code line by line to find where something unexpected is happening. If it's NULL, I am setting it to a value before I move on. camera_name_ is a pointer. It is not a string. It can point to a c-string. Here: camera_name_ = generate_uuid_v4().c_str(); You make it point to the internal buffer of the string returned by generate_uuid_v4(). If the function returns the string by value then this string is temporary and ceases to exist at the end of the line. The pointer you stored in camera_name_ is then dangling. If the function would return a reference to a string that is stored elsewhere, keeping a pointer to it would be fine. Don't use a pointer to a string when you actually want to store a string: #include <string> #include <iostream> const char* getenv() { return nullptr; } std::string generate_uid() { return "asd"; } int main() { std::string name; if (auto env = getenv(); env == nullptr){ name = generate_uid(); } else { name = std::string(env); } std::cout << name; }
71,672,731
71,673,172
Screen capture via WinAPI (security)
Is it possible to determine that now my screen (or window of my C++ program) is being captured by any of the running programs on the PC?
It seems there is no way to detect a screen capture until now But you can use SetWindowDisplayAffinity to protect the window content from being captured or copied only when the Desktop Window Manager(DWM) is composing the desktop.
71,673,569
71,674,748
How to call the base class method in C++?
I am working on a C++ program. For one of the use case, I have a class which is derived from its template class. So, I'm wondering how we can call the base class method inside the derived class method? Example: template <typename base> struct derived : public base { void aFunction() { // need to call a base function() here } }; One of the way could be something like base::aBaseFunction(), but I am not sure? I am new to OOP programming, so looking forward to learning a new concept through this problem statement.
If you want to explicitly use the base's member, make the type explicit like you found: template <typename base> struct derived : public base { void aFunction() { base::function(); } }; If you would rather have the usual unqualified-lookup behaviour, make this explicit instead: template <typename base> struct derived : public base { void aFunction() { this->function(); } }; Both of these behave exactly like they do in non-templates.
71,673,918
71,673,954
how to find the ways of handling pointer difference between ptr and ->
what is the difference of pointers between and which is better in terms of memory management void Loo(){ Song* pSong = new Song(…); //… string s = pSong->duration; } and void Hoo(){ unique_ptr<Song> song2(new Song(…)); //… string s = song2->duration; }
In the first case you need to call delete yourself and make sure it happens on all program control paths. That is easier said than done. It's tempting to write delete pSong; just before the closing brace of the function and be done with it. But what happens, say, if string s = song2->duration throws an exception? (Yes it's possible; for example if song2->duration is a type that has a conversion operator defined so it can be assigned to a string.) With std::unique_ptr, delete will be called for you when it goes out of scope. Although in this particular case Song song(...); may be more appropriate.
71,673,959
71,674,296
icpc error in compiling over-aligned dynamic allocated variables
I am trying to compile a code in C++, that uses over-aligned variables. If I try to compile the following code (a MWE) #include <new> #include <iostream> int main() { alignas(32) double *r = new (std::align_val_t{32}) double[3]; std::cout << "alignof(r) is " << alignof(r) << '\n'; return 0; } everything runs smoothly if I use icpx or g++ (in all the cases, the flag -std=c++17 is given to the compiler). However, when compiling using Intel icpc, I got the following error mwe.cpp(6): error: no instance of overloaded "operator new[]" matches the argument list argument types are: (unsigned long, std::align_val_t) alignas(32) double *r = new (std::align_val_t{32}) double[3]; ^ /usr/include/c++/9/new(175): note: this candidate was rejected because arguments do not match _GLIBCXX_NODISCARD inline void* operator new[](std::size_t, void* __p) _GLIBCXX_USE_NOEXCEPT ^ /usr/include/c++/9/new(141): note: this candidate was rejected because arguments do not match _GLIBCXX_NODISCARD void* operator new[](std::size_t, const std::nothrow_t&) _GLIBCXX_USE_NOEXCEPT ^ /usr/include/c++/9/new(127): note: this candidate was rejected because mismatch in count of arguments _GLIBCXX_NODISCARD void* operator new[](std::size_t) _GLIBCXX_THROW (std::bad_alloc) ^ mwe.cpp(7): warning #3464: the standard "alignof" operator does not accept an expression argument (use a type instead) std::cout << "alignof(r) is " << alignof(r) << '\n'; ^ compilation aborted for mwe.cpp (code 2) and I do not understand what the error can be. How can I solve this issue?
It seems that icpc fails to conform with the standard with aligned allocations. Quoting from the documentations for version 2021.5: In this release of the compiler, all that is necessary in order to get correct dynamic allocation for aligned data is to include a new header: #include <aligned_new> After this header is included, a new-expression for any aligned type will automatically allocate memory with the alignment of that type. Link: https://www.intel.com/content/www/us/en/develop/documentation/cpp-compiler-developer-guide-and-reference/top/optimization-and-programming-guide/automatically-aligned-dynamic-allocation/automatically-aligned-dynamic-allocation-1.html Live demo: https://godbolt.org/z/5xMqKGrTG This section is missing in the documentation of icpx: https://www.intel.com/content/www/us/en/develop/documentation/oneapi-dpcpp-cpp-compiler-dev-guide-and-reference/top.html.
71,674,624
71,675,039
OpenSSL how to request client certificate, but don't verify it
I want to setup openssl c/c++ server request certificate from client but don't verify it. I already use this piece of code to query certificate from client: /** Force the client-side have a certificate **/ SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr); SSL_CTX_set_verify_depth(ctx, 4); Can anybody give me example of such server code?
You should read the manual. It states: void SSL_CTX_set_verify(SSL_CTX *ctx, int mode, SSL_verify_cb verify_callback); [...] The return value of verify_callback controls the strategy of the further verification process. If verify_callback returns 0, the verification process is immediately stopped with "verification failed" state. [...] If verify_callback always returns 1, the TLS/SSL handshake will not be terminated with respect to verification failures and the connection will be established. [...] Writing a function that always returns 1 and passing it as verify_callback should help you solve the problem.
71,674,793
71,675,874
Automatic generate member functions depending on inherited class template
I am just thinking about a way to check an object to be valid in a automated way. I have a couple of hardware related objects (like class A), which can be deleted by external (physical) events. To detect this I have used shared/weak pointer. But now I am struggling with the checking of the weak pointer. Since this is done in the same way for each member function for many objects, I am currently searching for a way to do this with less redundant code. In addition I am writing a library and do not want the user to handle this (simply return the weak pointer to the user to handle it by himself is therefor no option) My best guess is shown below. My problem is, I could not find a way to generate the member functions (func1, and many more ...) automatically within the template. Doing it by myself would result in lot of redundant code for every member function to be validated (and there are a lot) Each member function of A (and many more other objects) shall be wrapped by a function doing the validation shown below. This is same for all member functions and done for many classes which can be used as type for the Validator. Does anyone has an idea how to solve this? Maybe there are other (better) ways to solve this. Many thanks for your help. Some constraints: Only C++11 possible, No exceptions class A { public: void func1() {} //many more functions }; template<typename T> class Validator { //has to be done for all functions of A void func1() { if (!wptr.expired()) { wptr.lock()->func1(); } else errorHandling(); } private: std::weak_ptr<T> wptr; void errorHandling() {} };
I would protect the full user function call: class A { public: void func1() {} //many more functions }; template <typename T> class Validator { public: #if 1 // template way, but no-expressive signature template <typename F> void do_job(F f) #else // type-erasure way, expressive, but with some overhead void do_job(std::function<void (T&)> f) #endif { auto t = wptr.lock(); if (t) { f(*t); } else { errorHandling(); } } private: void errorHandling(); private: std::weak_ptr<T> wptr; }; So user might chain call: Validator<A> val; val.do_job([](A& a) { a.func1(); a.func2(); });
71,675,005
71,675,068
Default arguments for member function of templated class
Let's say I have something like this bit of (duplicated) code that I'd like to refactor using a template: #include <iostream> #include <algorithm> #include <set> struct IntFoo { auto f(int arg, std::set<int> s = {1, 2, 3}) { return std::find(s.begin(), s.end(), arg) != s.end(); } }; struct FloatFoo { auto f(float arg, std::set<float> s = {4.0f, 5.0f, 6.0f}) { return std::find(s.begin(), s.end(), arg) != s.end(); } }; int main() { std::cout << IntFoo().f(3) << std::endl; std::cout << FloatFoo().f(4.0f) << std::endl; } As you can see, beyond the variance in type there is also the change in the default arguments given to f()'s second parameter. Best I could come up with was this: #include <iostream> #include <algorithm> #include <set> template<typename T, typename Def> struct Foo { auto f(T arg, std::set<T> s = Def::defaults){ return std::find(s.begin(), s.end(), arg) != s.end(); } }; struct FooIntDefaults { static constexpr std::initializer_list<int> defaults{1, 2, 3}; }; struct FooFloatDefaults { static constexpr std::initializer_list<float> defaults{4.0f, 5.0f, 6.0f}; }; using IntFoo = Foo<int, FooIntDefaults>; using FloatFoo = Foo<float, FooFloatDefaults>; This works, but is a bit verbose. I don't fancy these helper structs much. Ideally I'd like to pass the default arguments in the using line somehow. Is there some better way?
You can use parameter pack for specifying default arguments, e.g. template<typename T, T... defaults> struct Foo { auto f(T arg, std::set<T> s = {defaults...}){ return std::find(s.begin(), s.end(), arg) != s.end(); } }; using IntFoo = Foo<int, 1, 2, 3>; // specify default arguments when defining type using FloatFoo = Foo<float, 4.0f, 5.0f, 6.0f>; // specify default arguments when defining type LIVE BTW: Note that float can't be used as non-type template parameter before C++20.
71,675,063
71,675,372
C++ What is the behavior of a try-catch statement if an exception is thrown, and that exception does not match the type of exception caught?
I'm interested to know more about how the following code logic behaves: try { // might, or might not do this: throw ExceptionTypeA; function_which_might_throw_exception_type_a(); do_A(); // do we do A? } catch(ExceptionTypeB) { // B will never be done do_not_do_B(); } // C is always done (Edit: should always be done, but actually isn't) do_C(); In short, this question can simply be stated as: Will the function do_A be called?* *[If function_which_might_throw_exception_type_a() does throw ExceptionTypeA;... It is of course clear that do_A() will be called if function_which_might_throw_exception_type_a() does not throw an exception.] The pseduocode above is supposed to express throwing an exception of a type which is different to the type of exception caught in the catch clause. In other words, while there is a catch clause, the exception will not be caught here, because it is not of the correct type. In such cases, does the compiler produce an output which skips the calling of do_A() entirely or does the compiler produce an output in which do_A() is called`? I am fairly confident that if any exception is thrown in the try block, then the execution path is to leave the try block immediately. In other words, I think that do_A() is not called in the above pseudocode. (Assuming that the function function_which_might_throw_exception_type_a() does throw ExceptionTypeA.) However I wanted to check this, because I was starting to have doubts. FYI: I am looking at a block of code which would more sensibly be written as: try { // might, or might not do this: throw ExceptionTypeA; function_which_might_throw_exception_type_a(); do_A(); // do we do A? // C **should** always be done do_C() } catch(ExceptionTypeB) { // B will never be done do_not_do_B(); } return something; however, I think that this would not be equivalent to the first pseudocode. Since C++ does not have a try-catch-finally type statement, the logic cannot be expressed in this way. (But I think it would be better if it could have been.)
Will the function do_A be called? In short – no. When an exception is thrown inside a try block, that block will be exited immediately. If the type of exception thrown is not handled by a corresponding catch block, then it will be treated much like an exception thrown outside a try block would be (possibly causing a stack unwind but, ultimately, program termination). If you want your do_C() function to be called 'always', whatever type of exception is thrown, then you should add a catch(...) (known as a "catch-all clause") block after your other, specific catch block(s). This can be an empty statement/block; if so, the thrown exception is still caught (i.e. is not propagated further) but no specific action is taken. A possible way to implement what you appear to want is as follows: try { // might, or might not do this: throw ExceptionTypeA; function_which_might_throw_exception_type_a(); do_A(); // If the above throws, this WILL NOT be executed } catch(ExceptionTypeB) { // B will never be done do_not_do_B(); } catch(...) {} // This will catch "ExceptionTypeA" but do nothing about it ... do_C(); // Will 'always' execute (unless an earlier catch re-throws) return something;
71,675,252
71,675,755
Cannot increment value-initialized map/set iterator
I'm trying to increment key of nodes after the index j in a map, but I got some error while incrementing the iterator to the next node, here's my code : typedef map<int, string> My_map; My_map my_map; my_map[0] = "la base"; my_map[1] = "le premier"; int j = 1; My_map::reverse_iterator first_it(my_map.rbegin()); first_it++; My_map::reverse_iterator last_it(make_reverse_iterator(next(my_map.begin(), j - 1))); for (My_map::reverse_iterator it = first_it ; it != last_it ; it++) { auto handle = my_map.extract(it.base()); handle.key()++; my_map.insert(move(handle)); } I know that a map cannot have duplicate keys, so I started incrementing from the last one to the j-th one. But the it++ does not work. Is it different from when I used first_it++; ?
In the documentation for std::map::extract it mentions the side-effects: Extracting a node invalidates only the iterators to the extracted element. Pointers and references to the extracted element remain valid, but cannot be used while element is owned by a node handle: they become usable if the element is inserted into a container. As you can see, all the iterators are find except for the ones you care about. Because it is an iterator to the extracted element, it is now invalid. Subsequent attempts to use it (with it++ to advance the loop iteration) leads to undefined behavior. What you can do is use the iterator returned by std::map::insert: auto result = my_map.insert(move(handle)); it = make_reverse_iterator(result.position);
71,676,830
71,677,107
I can see only one USB string when I try to print all the USB devices (WinAPI)
I try to print a message whenever a new USB device is connected to my PC, but I don't want to create an application which just catches and treats the events triggered by the windows' kernel. So I used some specific functions in order to print the active USB devices and then, whenever a new device is plugged in, a signal produces something (a pop-up or something like that). Thus, firstly, I tried to enumerate all the USB devices, but I had no success as long as I receive only one line of text which represents a specific USB device, not all the USB devices connected. Here is the code #pragma comment(lib, "Cfgmgr32") #include <iostream> #include <Windows.h> #include <cfgmgr32.h> #include <initguid.h> #include <Usbiodef.h> #define MAX 1024 int main() { ULONG length; auto eroare1 = CM_Get_Device_Interface_List_SizeA( &length, (LPGUID)&GUID_DEVINTERFACE_USB_DEVICE, NULL, CM_GET_DEVICE_INTERFACE_LIST_PRESENT ); if (eroare1 != CR_SUCCESS) { std::cout << "eroare 1"; } PSZ buffer; buffer = new char[MAX]; auto eroare2 = CM_Get_Device_Interface_ListA( (LPGUID)&GUID_DEVINTERFACE_USB_DEVICE, NULL, buffer length, CM_GET_DEVICE_INTERFACE_LIST_PRESENT ); if (eroare2 != CR_SUCCESS) { std::cout << "eroare"; } std::cout << buffer << std::endl; }
The format used by CM_Get_Device_Interface_ListA to return a list of items is a double-null-terminated list (see also Why double-null-terminated strings instead of an array of pointers to strings? for rationale). This isn't explicitly spelled out in the documentation, but can be inferred from the argument type of Buffer: PZZSTR. It is declared in winnt.h like this: typedef _NullNull_terminated_ CHAR *PZZSTR; This is really just a char* but with the _NullNull_terminated_ SAL annotation. It allows static code analyzers to know about the additional semantics of PZZSTR, and serves as a hint to developers. The code in question only prints characters up to the first NUL character, i.e. it displays at most one item from the list. To display all items, you'll have to iterate over the strings until you find an empty string: char const* current{ buffer }; while (*current != '\0') { std::cout << current << std::endl; current += strlen(current) + 1; } That fixes the immediate issue. To make the code actually work, you'll have to fix the potential memory corruption bug. In the call to CM_Get_Device_Interface_ListA you're telling the API that buffer is pointing to length bytes of memory, but you allocated MAX bytes. The arguments of Buffer and BufferLen must match the actual allocation. Speaking of which, you never actually clean up that memory. Using a std::vector solves both issues: std::vector<char> buffer(length); auto eroare2 = CM_Get_Device_Interface_ListA( (LPGUID)&GUID_DEVINTERFACE_USB_DEVICE, NULL, buffer.data(), buffer.size(), CM_GET_DEVICE_INTERFACE_LIST_PRESENT ); // ... char const* current{ buffer.data() }; // ...
71,676,854
71,808,528
Thread protected variables from inside a threaded function
I writing a simple raytracer plugin for a software that generates the pixels from a multithreaded function. the pseudo code is Scene* scene; void engine_(int y, int, x, pixel& out){ // this function is threaded for each orizontal line y Buffer* line; my_render_engine(y, scene, buffered_line); // here is where I'm accessing a lot of shared data, incurring into data racing out = *buffered_line; // here I have just a line of pixels } My Scene* contains many shared variables (camera, samplers, shaders, etc) and the renderer only need read access to them. These have been generated before the engine_ is called. Accessing them concurrently creates undefined behaviours. I have grabbed a thread_pool template trying to protect my threads like this void engine\_(int y, int, x, pixel& out){ // this function is threaded for each orizontal line y m.lock() Buffer\* line(width); auto render_line = \[this\](int y, int x, Buffer\* buffer) { Scene thread_scene = Scene(); ... creating scene ... } thread_world.camera_ptr->my_render_engine(y, x, r, thread_scene , buffer_image_ptr); }; //for (int j = 0; j < height; j++) m_threadPool.AddTask(render_line, j, x, r, buffer_image_ptr); // running render function for each //thread safely m.unlock() out = *buffered_image; // here I have my entire image } this kinda works or at least I'm able to protect my variables. it's very inefficient in many ways and needs improvements, like generating just the right amount of scene as my number of cores. The big problem is that I cannot visualize what I'm doing unless I wait to generate the entire image, which I cannot do. The engine_ function let me visualize each row of pixels as soon as it is generated, but I have to let it do it. Using my thread pool as it is doesn't work obviously, because I'm overriding engine_ in easy words. A temporary solution is to create a brand new scene everytime I run the renderer like this void engine_(int y, int, x, pixel& out){ // this function is threaded for each orizontal line y Scene* thread_scene; .....creating scene..... Buffer* line(width); my_render_engine(y, 3dscene, buffered_line); // here is where I'm accessing a lot of shared data, incurring into data racing out = *buffered_line; // here I have just a line of pixels } it is similar to the thread_pool but it let me visualize the image I'm generating line by line. The problem is that is not well thread protected. inside the scene, there are shaders and 3dsamplers that are shared between many 3d objects like cameras, lights and geometries. So here is where I need help: I 'think' that when I'm creating my scene, the pointers of the variables inside it are shared between the threads and when the threads access them concurrently the program crashes: class Scene{ Camera* cam; Sampler* sampler; Object_list<object*> objs; Tracer* tracer_ptr; Shader_list<shader*> shaders }; // these pointers refer to the same stuff My questions are: ->Am I right? even though I'm creating several copies of the scenes I'm not protecting their variables? -> if that's the case, how can I make these variables protected? hopefully I don't need to copy them (especially the mesh_ptr which are quite heavy.
I've managed to solve the issue by creating a map containing the needed data for each thread and a thread::id. the data is the World class which contains pointers for the shared read-access data and a copy for what is not (hopefully is thread safe, but I'm not entirely sure). const std::thread::id tID = std::this_thread::get_id(); m_lock.lock(); std::map<const std::thread::id, World*>::iterator thread_it = worlds_map.find(tID); if (thread_it == worlds_map.end()) { //creating new scene for thread map World* thread_world = new World(); thread_world->set_bg_texture(input_texture_ptr); thread_world->build(); ......... // adding to thread map worlds_map[tID] = thread_world; } thread_it = worlds_map.find(tID); m_lock.unlock(); thread_it->second->camera_ptr->render_scene(y, x, r, buffer_image_ptr, *thread_it->second); }``` this way I only need to create an instance for each thread my cpu has and not for each row
71,676,871
71,677,508
How to build a 32 bit linux module remotely from visual studio?
I have been trying to create a cross-platform project. Both 32 bit and 64 bit binaries (dlls) need to be built. I am using Visual Studio and selecting x86-Release or x64-Release solves the problem for windows. But for linux it is always building 64 bit binaries. After searching, i found that g++ multilib needs to be installed and -m32 flag needs to be passed to both the compiler and linker. I found that set_target_properties(PROJECT_NAME PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32") will solve the problem. So to build a 32 bit linux binary (MODULE with .so ending), i added the above code. I also have this code beneath the above code if(WIN32) if(CMAKE_SIZEOF_VOID_P EQUAL 8) message("WIN32 x64") else() message("WIN32 x32") endif() else(WIN32) if(CMAKE_SIZEOF_VOID_P EQUAL 8) message("LINUX x64") else() message("LINUX x32") endif() endif(WIN32) However, it outputs 1> [CMake] LINUX x64 So it is still building 32 bit build. I have both g++ and g++ multilib installed, but not sure visual studio is calling which one. could that be the problem?
As mentioned in comments, it was found that CMAKE_SIZEOF_VOID_P is not able to detect if m32 flag is passed. So i modified the code like this if(CMAKE_SIZEOF_VOID_P EQUAL 8) set(OUTPUT_BITNESS 64) else() set(OUTPUT_BITNESS 32) endif() if(FORCE_32) set_target_properties(PROJECT_NAME PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32") set(OUTPUT_BITNESS 32) endif() if(WIN32) if(OUTPUT_BITNESS EQUAL 64) message("WIN32 x64") else() message("WIN32 x32") endif() else(WIN32) if(OUTPUT_BITNESS EQUAL 64) message("LINUX x64") else() message("LINUX x32") endif() endif(WIN32 So to compile for 32 bit, FORCE_32 variable must be set to 1.
71,677,049
71,677,211
Flatten a multidimensional vector in c++
I want to write a generic function in c++ to flatten any multidimensional vector provided. The signature of the method is as follows: template <class U, class T> void flatten(U* out, T& inp, int* dims, int n){ // out is the flattened output // inp is some multidimensional vector<vector...<U>> // dims is an array of the dimensions of inp // n is the number of dimensions of inp int ticker[n]; int prodLimit = 1; int prod = 0; // calculate prodLimit as product of elements in dims and initialize ticker for (int i=0; i<n; i++){ ticker[i] = 0; prodLimit *= dims[i]; } while (prod < prodLimit){ // access the current element in inp {...} // update ticker for (int i=n-1; i>0; i++){ if (ticker[i] == dims[i]){ ticker[i] == 0; ticker[i-1] += 1; } } prod += 1; out[prod] = correctElementIn_inp; } } Most of the operations are straight forward except accessing the specific component of multi-dimensional vector inp. As the dimensions are unknown a-priori I create an array of size n in a while loop to handle the counter for each dimension and update it properly. Now the only problem remaining is using the ticker to access the correct element in the vector. As an example lets say the following holds: #include <vector> typedef std::vector<std::vector<double>> vec2; typedef std::vector<std::vector<std::vector<double>>> vec3; int main(){ vec2 inp1 = {...}; vec3 inp2 = {...}; int s1[2] = {2,3}; int s2[3] = {2,3,4}; ... } Now this method should be able to handle both of inp1 and inp2. Is there a way of recursively accessing the vector elements without explicitly using the vector element access operator for each case.
Your code is unecessarily complicated due to manually managing the memory and manually passing sizes around. Both is obsolete when you use std::vector. Even if you do want a raw C-array as result you can nevertheless use a std::vector and later copy its contents to properly allocated C-array. I would use a recursive approach: #include <vector> #include <iostream> template <typename E,typename X> void unroll(const std::vector<E>& v,std::vector<X>& out){ std::cout << "unroll vector\n"; out.insert(out.end(), v.begin(), v.end()); } template <typename V,typename X> void unroll(const std::vector<std::vector<V>>& v,std::vector<X>& out) { std::cout << "unroll vector of vectors\n"; for (const auto& e : v) unroll(e,out); } int main() { std::vector<std::vector<std::vector<int>>> x; std::vector<int> y; x.push_back({{1,2,3},{4,5,6}}); x.push_back({{7,8,9}}); unroll(x,y); for (const auto& e : y) std::cout << e << " "; } Output: unroll vector of vectors unroll vector of vectors unroll vector unroll vector unroll vector of vectors unroll vector 1 2 3 4 5 6 7 8 9 Is there a way of recursively accessing the vector elements without explicitly using the vector element access operator for each case. A vectors elements are stored in contiguous memory, hence you can use pointer arithmetics via its data(). However, a std::vector<std::vector<int>> does not store the ints in contiguous memory. Only the inner vectors elements are stored contiguously while each inner vector allocates the elements on the heap "somewhere". There is no short cut to access x[0][0][0] without accessing x[0][0]. Actually I would suggest to reconsider if you want to use nested vectors in the first place. PS: I was cheating a little ;). I would expect it to be more performant to first calculate the total size of out before pushing elements to it as you are doing in your code. For brevity it was left out from the above. It can be done with similar recursion as the above code. Instead of pusing to out you would accumulate some size until you reach the first non-vector element type. Then reserve enough space for out upfront and only then run the actual recursion that populates out.
71,677,242
71,696,216
how to mirror a HBITMAP
how to flip a HBITMAP horizontally?As an option, I thought to get an array of colors from BITMAP and write them to another BITMAP, but somehow it's too busy. Are there built-in functions or other options to do this?
You can use StretchBlt with a negative dimension as below: HBITMAP FlipBitmapHorizontally(HBITMAP hbm) { BITMAP bm; GetObject(hbm, sizeof(BITMAP), &bm); int wd = bm.bmWidth; int hgt = bm.bmHeight; HDC hdcScr = GetDC(NULL); HDC hdcFlipped = CreateCompatibleDC(hdcScr); HBITMAP hbmFlipped = CreateCompatibleBitmap(hdcScr, wd, hgt); HGDIOBJ oldFlipped = SelectObject(hdcFlipped, hbmFlipped); HDC hdcSrc = CreateCompatibleDC(hdcScr); HGDIOBJ oldSrc = SelectObject(hdcSrc, hbm); StretchBlt(hdcFlipped, wd, 0, -wd, hgt, hdcSrc, 0, 0, wd, hgt, SRCCOPY); SelectObject(hdcSrc, oldSrc); DeleteDC(hdcSrc); SelectObject(hdcFlipped, oldFlipped); DeleteDC(hdcFlipped); ReleaseDC(NULL, hdcScr); return hbmFlipped; }