question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
74,175,833
74,256,157
How to replace deprecated RSA low level OpenSSL 3.0 APIs with equivalent EVP functions?
This working RSA OpenSSL code void SwapBytes( unsigned char *pv, size_t n ) { unsigned char *p = pv; size_t lo, hi; for ( lo = 0, hi = n - 1; hi > lo; lo++, hi-- ) { char tmp = p[lo]; p[lo] = p[hi]; p[hi] = tmp; } } void RSA(unsigned char *plaintext, unsigned char *ciphertext) { BIGNUM *bnN = NULL; BIGNUM *bnE = NULL; RSA *keys = RSA_new(); BN_hex2bn(&bnN, modulus); BN_hex2bn(&bnE, public_exp); RSA_set0_key(keys, bnN, bnE, NULL); int modulus_size = RSA_size(keys); SwapBytes(plaintext, modulus_size); int cipher_len = RSA_public_encrypt(modulus_size, plaintext, ciphertext, keys, RSA_NO_PADDING); RSA_free(keys); SwapBytes(ciphertext, modulus_size); } when compiled produces deprecated warnings such as /mnt/c/Projects/src/rsa.cpp:37:102: warning: ‘int RSA_public_encrypt(int, const unsigned char*, unsigned char*, RSA*, int)’ is deprecated: Since OpenSSL 3.0 [-Wdeprecated-declarations] 37 | int cipher_len = RSA_public_encrypt(modulus_size, plaintext, ciphertext, keys, RSA_NO_PADDING); which can be suppressed using this compiler option -Wno-deprecated-declarations However, the OpenSSL dev team notes: Use of the low level APIs has been informally discouraged by the OpenSSL dev team for a long time. However in OpenSSL 3.0 this is made more formal. All such low level APIs have been deprecated. You may still use them in your applications, but you may start to see deprecation warnings during compilation (dependent on compiler support for this). Deprecated APIs may be removed from future versions of OpenSSL so you are strongly encouraged to update your code to use the high level APIs instead. Question It's suggested to replace the above low level API's with EVP. Is there an RSA example to replace the above code with OpenSSL EVP functions?
I'm no openssl expert, but going through the hard to read DOC's I figured out the below conversation which from my testing generates the same output as as your function (assuming no SwapBytes is called as you don't provide that). It can be broken down into three parts I think. setting up PARAMS array with the key parameters using OSSL_PARAM_BLD_xx functions creating the RSA key from the PARAMS array using using EVP_PKEY_fromdata function encrypting the data using EVP_PKEY_xxx functions Sample: #include <cassert> #include <openssl/evp.h> #include <openssl/rsa.h> #include <openssl/param_build.h> template<typename T, typename D> std::unique_ptr<T, D> make_handle(T* handle, D deleter) { return std::unique_ptr<T, D>{handle, deleter}; } void newRSA(unsigned char *plaintext, unsigned char *ciphertext, int length, char const* modulus, char const* public_exp) { // build BIGNUM values BIGNUM* num{ nullptr }; BN_hex2bn(&num, modulus); assert(num != nullptr); auto bnN = make_handle(num, BN_free); num = nullptr; BN_hex2bn(&num, public_exp); assert(num != nullptr); auto bnE = make_handle(num, BN_free); // Build params to create PARAM array auto params_build = make_handle(OSSL_PARAM_BLD_new(), OSSL_PARAM_BLD_free); assert(params_build.get() != nullptr); auto result = OSSL_PARAM_BLD_push_BN(params_build.get(), "n", bnN.get()); assert(result == 1); result = OSSL_PARAM_BLD_push_BN(params_build.get(), "e", bnE.get()); assert(result == 1); result = OSSL_PARAM_BLD_push_BN(params_build.get(), "d", nullptr); assert(result == 1); // create PARAMS array auto params = make_handle(OSSL_PARAM_BLD_to_param(params_build.get()), OSSL_PARAM_free); // cleanup params build up params_build.reset(); bnN.reset(); bnE.reset(); // Create RSA key from params auto ctx = make_handle(EVP_PKEY_CTX_new_from_name(nullptr, "RSA", nullptr), EVP_PKEY_CTX_free); assert(ctx.get() != nullptr); result = EVP_PKEY_fromdata_init(ctx.get()); assert(result == 1); EVP_PKEY *key = nullptr; result = EVP_PKEY_fromdata(ctx.get(), &key, EVP_PKEY_KEYPAIR, params.get()); assert(result == 1); auto keys = make_handle(key, EVP_PKEY_free); // cleanup params params.reset(); // RSA_size equivalent int modulus_size = (EVP_PKEY_get_bits(keys.get()) + 7) / 8; assert(length == modulus_size); // setup encryption from the key generated above auto enc_ctx = make_handle(EVP_PKEY_CTX_new(keys.get(), nullptr), EVP_PKEY_CTX_free); assert(enc_ctx.get() != nullptr); result = EVP_PKEY_encrypt_init(enc_ctx.get()); assert(result == 1); // encrypt using RSA_NO_PADDING result = EVP_PKEY_CTX_set_rsa_padding(enc_ctx.get(), RSA_NO_PADDING); assert(result == 1); // encrypt size_t outlen = length; result = EVP_PKEY_encrypt(enc_ctx.get(), ciphertext, &outlen, plaintext, length); assert(result == 1); assert(outlen == length); }
74,175,992
74,176,039
shared_from_this() crashes in specific case
Option 1 crashes the app on shared_from_this() with bad_weak_ptr, while option 2 works fine, why? the only difference i see is where the clone is being created - in the Clone() function or in line with creating shared_ptr for the clone, in both cases the shared_from_this requirement of already having shared_ptr with ownership of this when using shared_from_this() is met class Base { public: virtual Base* Clone() = 0; }; class Derived : public Base, public std::enable_shared_from_this<Derived> { public: Base* Clone() override { return new Derived(*this); } void test() { std::shared_ptr<Derived> ptr = shared_from_this(); } }; int main() { std::shared_ptr<Base> obj = std::make_shared<Derived>(); //std::shared_ptr<Base> clone = std::shared_ptr<Base>(obj->Clone()); // option 1 std::shared_ptr<Base> clone = std::shared_ptr<Base>(new Derived(*std::static_pointer_cast<Derived>(obj))); // option 2 std::shared_ptr<Derived> derived = std::static_pointer_cast<Derived>(clone); derived->test(); return 0; }
You can't new an object that derives from enable_shared_from_this and for it to safely work since the new object doesn't actually have a shared_ptr container. Instead of this: Base* Clone() override { return new Derived(*this); } This: shared_ptr<Base> Clone() override { return make_shared<Derived>(*this); } Similar adjustment in the base class declaration: virtual shared_ptr<Base> Clone() = 0;
74,176,542
74,179,444
Boost log - include object id into logs
I'm currently getting started with boost.log and have a question about how to incorporate object id into the logs. So for instance: class Sample { size_t id() const; // ... void someMethod() { // log here, see id() in a message } }; So, each object has it's own id and I want to see it in the logs. Here are the approaches I came up with: create logger object per instance. Each logger will have a constant attribute id. While it should work, I don't think it's a good approach from performance perspective. one logger per class, write a logger feature that will add and remove id at every call (sth similar to this: https://www.boost.org/doc/libs/1_80_0/libs/log/doc/html/log/extension/sources.html). Here my concern is locking (I am not sure whether the logs will not block when mutliple instances are in different threads) include id as a part of log message. While being the most straightforward, it does not offer formatting capabilities. So each of the 3 approaches is not perfect. Perhaps I'm missing something? Thank Your for Your time! P.S. I don't understand why I cannot provide an attribute when doing logger.open_record call, for me it's not intuitive at all.
If your object id doesn't change throughout the object lifetime, you do not need to add and remove the id on every log record. You can just add it to the logger once in the logger constructor. You don't even need a new logger feature to do this as every logger supports a set of logger-specific attributes. // Define an attribute keyword for use in filters and formatters BOOST_LOG_ATTRIBUTE_KEYWORD(a_object_id, "ObjectId", size_t) class Sample { private: boost::log::sources::logger m_log; public: Sample() { m_log.add_attribute(tag::a_object_id::get_name(), boost::log::attributes::make_constant(id())); } size_t id() const; void someMethod() { // Every log record made through m_log will have ObjectId attached BOOST_LOG(m_log) << "someMethod() called"; } }; Remember that in order to actually see the attribute value in the output you need to set the formatter that will produce that attribute value in the formatted message. sink->set_formatter(boost::log::expressions::stream << "[" << a_object_id << "] " << boost::log::expressions::smessage);
74,176,592
74,176,608
Return a smart pointer dereference as a reference type
const string& show_string(){ std::shared_ptr<std::string> p = std::make_shared<std::string>("test"); return *p; } A novice question:Will this usage cause dangling reference?
Yes std::shared_ptr will delete the object it owns when the last std::shared_ptr sharing ownership of that object is destroyed. In this case, p is the only std::shared_ptr pointing to your string, and it is local to show_string, so that string will be destroyed as soon as show_string returns, leaving the returned reference dangling.
74,176,863
74,176,888
C++ reference to a variable on its initialization
Consider this example: #include <iostream> std::string& fn(std::string& str) { str = "oh no!"; return str; } int main() { std::string str = fn(str); std::cout << str << std::endl; return 0; } I have two questions Why does this compile/why doesn't the compiler warn against it? It seems obvious that str shouldn't be referenced (in the fn function call) before its initialization. Does the C++ standard not prevent this? And if so what's the purpose of referencing a variable before it's initialized? This code compiles fine on all compilers I tried (GCC, Clang, and MSVC, as shown here https://godbolt.org/z/jExWYW6b9), and segfaults on all of them on Godbolt. However, I can compile this code and execute it without segfault with Apple clang version 13.1.6 (clang-1316.0.21.2.5) on a M1 mac (tested under arm64 and x86_64 with Rosetta 2, and it prints oh no! to stdout). Why does this work with Apple Clang and doesn't segfault? I can't seem to reproduce this on Godbolt.
Why does this compile/why doesn't the compiler warn against it? It seems obvious that str shouldn't be referenced (in the fn function call) before its initialization. Does the C++ standard not prevent this? And if so what's the purpose of referencing a variable before it's initialized? It doesn't warn on std::string str = fn(str); because that is a legitimate and well-defined use. You could for example write this and have fn store a pointer or reference to str somewhere for later use. Compilers are not generally performing any deep analysis for the purpose of warnings. Therefore I wouldn't expect them to check whether the function fn is actually using the reference in a valid manner with regards to lifetime of str. If you want such an analysis use a static analyzer or similar tool, e.g. clang-tidy, clang-analyzer or GCC's -fanalyzer (although that seems to be buggy with C++ at the moment). This code compiles fine on all compilers I tried (GCC, Clang, and MSVC, as shown here https://godbolt.org/z/jExWYW6b9), and segfaults on all of them on Godbolt. However, I can compile this code and execute it without segfault with Apple clang version 13.1.6 (clang-1316.0.21.2.5) on a M1 mac (tested under arm64 and x86_64 with Rosetta 2, and it prints oh no! to stdout). Why does this work with Apple Clang and doesn't segfault? I can't seem to reproduce this on Godbolt. While forming a reference or pointer to str outside its lifetime is allowed, calling a member function on or accessing a member of a class type object before its lifetime begins, meaning before its initialization is complete, as you are doing with str = "oh no!"; causes undefined behavior. (Exceptions apply if the call/access happens through a constructor this pointer during construction.) One possible outcome of undefined behavior is that it seems to work and another is that it segfaults, as well as many other possibilities. Even if you remove that line, you are still calling the copy constructor for str with a reference to itself as argument. I am not actually sure at the moment whether the standard implicitly or explicitly disallows such a use for the standard library types. I guess implicitly the specification of the std::string constructor does forbid it. In any case I expect that it is intended to not be allowed, in which case this would still be a library precondition violation and undefined behavior.
74,179,196
74,181,644
Use of undefined type as a class after adding forward declarations
I'm having an issue compiling that code. I know the code dose nothing, but it gave me an error saying " use of undefined type Humans, how can I make it work? how can I make classes that can access other classes instances in cpp ? Thank you :) #include <iostream> class Humans; class Animals { public: Animals() :health(1) { } int health; void Attack(Humans a) { a.health = 10; } }; class Animals; class Humans { public: Humans() :health(0) { } int health; void Attack(Animals s) { s.health = 5; } }; int main() { Humans max; Animals lion; lion.Attack(max); }
A forward declaration only states that a thing with a particular name exists somewhere; you can't use an instance of it for anything until the definition is also known. Separate the class definitions and the member function definitions. (This is the "default" way of writing C++, with class definitions and function definitions in separate files.) class Human; class Animal { public: Animal(); // A forward declaration is enough since we don't // try to use 'a' here. void Attack(Human a); int health; }; class Human { public: Human(); void Attack(Animal s); int health; }; Animal::Animal() : health(1) {} void Animal::Attack(Human a) { a.health = 10; } Human::Human() : health(0) {} void Human::Attack(Animal s) { s.health = 5; } (And don't use plural names for singular things. A lion is an animal, not an "animals".)
74,179,685
74,180,482
How many times are arguments calculated in multithreaded function-scope static variable initialization?
Suppose we have a following function, which is executed by multiple threads at the same time: void foo() { static SomeClass s{get_first_arg(), get_second_arg()}; } My question is how many times will get_first_arg and get_second_arg be executed -- exactly once, or ThreadCount times, or is it unspecified/implementation-defined behavior?
The local static variable s initialized only once and the first time control passes through the declaration of that variable. This can be seen from static local variable's documentation: Variables declared at block scope with the specifier static have static storage duration but are initialized the first time control passes through their declaration (unless their initialization is zero- or constant-initialization, which can be performed before the block is first entered). On all further calls, the declaration is skipped. (emphasis mine) This in turn means that the arguments get_first_arg() and get_second_arg() will be evaluated only once.
74,180,013
74,180,117
How to assign from one to another related class, custom assignment or cast in c++?
I have a class templated on a floating point type, template <typename fl_t> class generic { fl_t a,b; /// a bunch of getters and setters, etc... } and instantiate with float and double typedef generic<double> dmatrix; typedef generic<float> fmatrix; Later, when I want to assign an fmatrix to a dmatrix, I get error: no viable conversion from 'const generic<float>' to 'generic<double>' note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'const fmatrix' (aka 'const generic<float>') to 'const generic<double> &' for 1st argument template <typename fl_t> class generic { I wrote an overloaded assignment: template <typename f> generic<f>& operator= ( const generic& g){ aSET(g.aGET(); // etc return *this; } This compiles but does not solve the problem. Why? Must I write a cast and with what signature? EDIT: I accepted an answer but for practical work, it seems a cast will also be often needed. One can see how to do it: template <typename fl_t> class generic { public: fl_t a; double aGET() const {return double(a);} void aSET(double x) { a=fl_t(x);} template <typename f> generic& operator=(const generic<f>& g){ // assignment aSET( g.aGET() ); return *this; } template <typename f> operator generic<f>() { // constructor generic<f> m; m.aSET( aGET() ); return m; } }; typedef generic<double> dmatrix; typedef generic<float> fmatrix; dmatrix fn(fmatrix m){ dmatrix d=m; // uses constructor, operator() d=m; // uses assignment, operator= return d; }
Your assignment operator takes the current type as parameter: template <typename fl_t> class generic { // ... template <typename f> generic<f>& operator=(const generic& g) // this is generic<fl_t> ^^^^^^^ // ... }; If you want to assign from another type, you need to swap the return type and the parameter type: template <typename f> generic& operator=(const generic<f>& g) The type of the parameter is the type of the variable you want to assign from. The return type can be whatever you want, but for an assignment operator it's typically a reference to the type of the variable you want to assign to (that's the current class) so that you can do something else directly with the result, for example chain assignments (a = b = c). If you don't want the conversion to be implicit (in other words, if you want the assignment to require a cast), you can mark the operator explicit: template <typename f> explicit generic& operator=(const generic<f>& g)
74,180,278
74,181,285
Is there a way to handle exeption without try catch block?
Sorry for all mistakes, English is not my native language. I have code that contains following lines: tf::TransformListener listener; tf::StampedTransform transform; while(ros.ok()) { try { listener.lookupTransform("/map", "/base_link", ros::Time(0), transform); } catch(tf::TransformException ex) { //ROS_ERROR("Transform problem -> %s", ex.what()); } The problem is I should achieve same effect without try catch block. I need to use this code on arduino, and I have hard times understanding is it possible to achieve same result with if else statements? Appreciate any help.
As Sam Varshavchik put it, If an exception gets thrown in a C++ program, there only way to catch it and resume execution, at some point, is a try/catch block. This is the only way to do it, there are no workarounds or exceptions. As this answer said, the only way for a global error handler is to put the entire program into a try/catch statement, or at least the part that would cause an error. Even better, you can make sure your program just doesn't throw an error in the first place, by checking values and asserting. But all in all, no, there is no way to do this.
74,180,443
74,180,508
sort vector of Coordinates(x,y,z) by vector of z value
I have a vector of 3D coordinates: vector<float64>contourdata; contourdata={x0,y0,z0,x1,y1,z1,x2,y2,z2,...} And I want to sort them by the vector of the z value. How can I do it in c++?
Like this : #include <algorithm> #include <iostream> #include <vector> #include <format> // 3d points have 3 coordinates and // we need to move those 3 values together when sorting // It is also good to use "concepts" from real world as // names in code : so define a struct representing a 3d coordinate. // (Or use a 3d coordinate type from an existing library) struct vec_3d_t { double x; double y; double z; }; // helper function for outputing the values of one 3d point // not essential for your problem. std::ostream& operator<<(std::ostream& os, const vec_3d_t& data_point) { os << std::format("({0},{1},{2})", data_point.x, data_point.y, data_point.z); return os; } int main() { // std::vector is a (resizable) array // in this case to hold 3d coordinates // then initialize the data with some values // (you will probably get them from somewhere else, e.g. a file) std::vector<vec_3d_t> contour_data { {3.0,4.0,5.0}, // first coordinate {1.0,2.0,3.0}, // second etc ... {7.0,8.0,9.0} }; // this calls the sort algorithm // using a function to compare two 3d points // to sort on z only compare z. std::sort(contour_data.begin(), contour_data.end(), [](const vec_3d_t& lhs, const vec_3d_t& rhs) { return lhs.z < rhs.z; }); // range based for loop over data points for (const auto& data_point : contour_data) { std::cout << data_point << "\n"; } return 0; }
74,181,289
74,181,339
Cant Delete File Unless I Close My Program
I have this code CreateFileA(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); It works perfectly but the only problem is that I cant read, write, or delete the file unless I exit my program. Any Ideas?
You should store the return value of CreateFileA in a variable of type HANDLE: HANDLE hFile = CreateFileA(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); Then, when you're done with it, call: CloseHandle(hFile); After which you should be able to delete the file.
74,181,335
74,194,218
Cannot use LineSegmentDetector from OpenCV in C++
I am trying to perform line detection, using OpenCV, in order to select rows of vegetation in satellite imagery. I decided to use OpenCV LineSegmentDetector since it seemed to provide just what I need in a single code line, as opposed to using Hough Transform or other more complex methods that require some additional work and preprocessing. However, I am unable to make it work even in the simplest example. My code: Mat coco = imread("C:/Users/XX/Images/cococo.png", IMREAD_GRAYSCALE); cv::LineSegmentDetector* lsd = cv::createLineSegmentDetector(); std::vector<cv::Vec4f> lines_std; lsd->detect(coco, lines_std); lsd->drawSegments(coco, lines_std); in the 4th line: lsd->detect(coco, lines_std) I get either an AccessViolationException or a NullPointerException no matter what i try (different types in the OutputArray, using a cv::Mat as output, etc). The code is almost exactly the same as here: https://docs.opencv.org/4.6.0/df/dfa/tutorial_line_descriptor_main.html (probably with an older version since I do not have the "KeyLine" type defined) I am aware this feature was removed in prior OpenCV versions due to licensing issues, as can be seen in the official docs: Implementation has been removed from OpenCV version 3.4.6 to 3.4.15 and version 4.1.0 to 4.5.3 due original code license conflict. restored again after Computation of a NFA code published under the MIT license. ...but since I am using OpenCV 4.6.0 i suspect that is not the issue. I have configured a fresh project in Visual Studio 2022 for this test, and I am familiar with the usual OpenCV things (add include folders, static and dynamic libs in linker, etc.). Other operations on Mats work just fine. What am I missing?
Thanks to Micka accurate suggestion, I was able to trace the problem. Seems that cv::Ptr was a requirement and standard C++ pointers do not work, even in a fairly simple setup like this one. I was not aware of that. I am providing the fixed code just in case it can be helpful to someone: #include "stdafx.h" #include "opencv2/opencv.hpp" using namespace cv; using namespace std; int main() { Mat img = imread("C:/Users/XX/Images/test.png", IMREAD_GRAYSCALE); Mat resizedimg, resizedimgRGB; resize(img, resizedimg, cv::Size(img.rows/16, img.cols/16)); cv::cvtColor(resizedimg, resizedimgRGB, COLOR_GRAY2BGR); cv::Ptr<cv::LineSegmentDetector> lsd = cv::createLineSegmentDetector(0); std::vector<cv::Vec4i> lines_std; lsd->detect(resizedimg, lines_std); lsd->drawSegments(resizedimgRGB, lines_std); // For some reason this does not work when lines_std coordinates are stored as doubles /* for (cv::Vec4d lin : lines_std) { cv::line(resizedimgRGB, cv::Point(lin[0], lin[1]), cv::Point(lin[2], lin[3]), Scalar(255, 0, 0), 1); } */ imshow("IMAGE", resizedimgRGB); waitKey(0); return 0; } Some variable names were changed to a bit more self-explanatory ones, also, the image was resized in order to save some time between tests. edit: There was an error when drawing the lines using LineSegmentDetector::drawSegments(...), caused by decimals on the line coordinates. It was fixed by using cv::Vec4i (integer type) instead of cv::Vec4d to store the coordinates. The commented-out loop is no longer needed with this change.
74,181,763
74,182,538
What optimization allows Functors to be inlined?
At compile-time, I want to pass a (stateless) function as efficiently as possible. I see two options: template<typename Functor> bool PassAsArgument(int arg1, int arg2, Functor functor); and template<bool (*Function)(int, int)> bool PassAsTemplateParameter(int arg1, int arg2); The second option seemed like the obvious choice for compile-time computation, however, Effective STL #39, the C++ standard library (std::sort, std::make_heap), the C++ Core Guidelines (T.40), and this stackoverflow answer disagree. I tested the both versions on godbolt and found that the optimizations I wanted were applied (i.e., std:less<int> was inlined). #include <functional> template<typename Functor> bool PassAsArgument(int arg1, int arg2, Functor functor){ return functor(arg1, arg2); } template bool PassAsArgument(int, int, std::less<int>); results in bool PassAsArgument<std::less<int> >(int, int, std::less<int>): cmp edi, esi setl al ret and inline bool LessThan(int a, int b){ return a < b; } template<bool (*Function)(int, int)> bool PassAsTemplateParameter(int arg1, int arg2){ return Function(arg1, arg2); } template bool PassAsTemplateParameter<LessThan>(int, int); results in bool PassAsTemplateParameter<&(LessThan(int, int))>(int, int): cmp edi, esi setl al ret I want to follow the guidelines, but I'm worried that in more complicated code, I may make a mistake that disables some optimizations. For example, What if Functor is not the last argument? What if I call PassAsArgument with a stateful Functor? What if I need to pass multiple Functors? What if I need to pass Functor to func2 in the body of PassAsArgument? What if I save a copy of Functor as a data member of a class? As a starting point, I need to know what optimizations the compiler is using. The question is: What optimization allows Functors passed-by-value to be inlined?
Constant propagation is the key optimization. When the lambda or functor is called, the compiler still knows which code runs, and thus it's as straightforward as inlining a function by name. If not, it's like a runtime-variable function pointer; the compiler can't inline1. After inlining PassAsArgument(1, 2, LessThan) into the caller that passed functor = LessThan, the functor(arg1, arg2); can be seen to be calling LessThan. So the compiler can inline your LessThan as well. The T.40 rule you linked (In general, passing function objects gives better performance than passing pointers to functions), about using lambdas instead of raw function pointers, is only true when things inline. They do inline just as easily as function pointers when visible at compile time. But if they don't inline, a bare function pointer may be cheapest. It doesn't need any special permission from the ISO C++ standard beyond the as-if rule since there's no change in observable behaviour. What if I save a copy of Functor as a data member of a class? That's likely to defeat constant-propagation, unless the compiler can prove that every member of that class could only ever had the same value assigned (this lambda, not some other in a different compilation unit it can't see). Footnote 1: If a compiler doesn't know the value of a function pointer for sure, but it has a good guess, it might compare/branch on the function pointer having that value. If it matches, it can run an inlined version of that function, with constant propagation and whatnot. Otherwise just call through the function pointer. You could call this speculative inlining. When the function pointer in question is in a vtable, this is called "speculative devirtualization". AFAIK, that's the only time real compilers will actually attempt this, since that's when it's common to have function pointers that only ever have one value. (Constant propagation into the function being inlined can be great if it turns runtime branches into if(false), or otherwise greatly simplifies way beyond just avoiding the call/ret and calling convention overhead.) Related: What does the compiler optimization "constant propagation" mean? (for numeric variables) Are lambdas inlined like functions in C++? C++ Lambda Overhead - Jérôme Richard says at least some compilers might fail to inline if you wrap a lambda in a std::function. I'd assume that's based on practical experience looking at the asm, although I'm surprised; I'd expect GCC and clang at least to not have a problem inlining. But I'd easily believe MSVC did a worse job. Still looking for a better duplicate about constprop and inlining.
74,182,587
74,183,277
Can I form a C++ reference from a pointer of the wrong type?
If I have a pointer T* t and I use reinterpret_cast<T*>(&u) to point to some object u (which is not a T), I know that I cannot access u via t. Therefore, I think that I cannot form T& rt from t, even if I don't perform any access through rt because: To form rt I would need to express *t in some way, which is an "access", and I am prohibited from doing this. I would be initializing a reference with something other than "a valid object". Is this understanding correct? (Edited to clarify that I am asking about whether rt can be formed from t.)
To form rt I would need to express *t in some way, which is an "access", and I am prohibited from doing this. No, dereferencing itself is not an access. An access would require reading from or writing to a scalar object. I would be initializing a reference with something other than "a valid object". If t points to an object (whether with the correct type or not), there is nothing prohibiting binding a reference to the lvalue *t. However, you must assure that t does actually point to an object. Specifically you need to assure that u is aligned suitably for the type T. Otherwise the result of reinterpret_cast<T*>(&u) will have an unspecified value, instead of pointing to u (or an object pointer-interconvertible with it) as expected. In any case, of course, you are not generally allowed to use the resulting reference to read from or write to the object, to access members, etc.
74,182,823
74,182,986
Getting a read access violation trying to spin up a Vulkan instance
I am trying to use the vkCreateInstance() method but I am getting a read access violation from vulkan-1.dll. I am using SDL for windowing, and am using Visual Studio 2022, and have both Windows and my graphics drivers up to date #include <vulkan/vulkan.hpp> #include <SDL.h> #include <SDL_vulkan.h> #include <vector> #include <iostream> SDL_Window* window; int main(int argc, char *argv[]) { if (SDL_Init(SDL_INIT_VIDEO) < 0) { std::cout << "Video initialization failed:" << std::endl; } window = SDL_CreateWindow("vkTest", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_VULKAN); SDL_vulkanInstance inst; VkInstanceCreateInfo inst_info; VkApplicationInfo appInfo; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pApplicationName = "engine"; appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.pEngineName = "engine"; appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.apiVersion = VK_API_VERSION_1_0; inst_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; inst_info.pApplicationInfo = &appInfo; inst_info.flags = 0; uint32_t vkExtensionCount = 0; if (!SDL_Vulkan_GetInstanceExtensions(window, &vkExtensionCount, NULL)) { std::cout << "Unable to get Vulkan extensions." << std::endl; exit(EXIT_FAILURE); } std::vector<const char*> vkExtensions; vkExtensions.resize(vkExtensionCount); if (!SDL_Vulkan_GetInstanceExtensions(window, &vkExtensionCount, vkExtensions.data())) { std::cout << "Unable to get Vulkan extensions." << std::endl; exit(EXIT_FAILURE); } std::cout << *vkExtensions.data() << std::endl; inst_info.enabledExtensionCount = vkExtensionCount; inst_info.ppEnabledExtensionNames = vkExtensions.data(); inst_info.enabledLayerCount = 0; VkResult res = vkCreateInstance(&inst_info, nullptr, &inst); if (res == VK_ERROR_INCOMPATIBLE_DRIVER) { std::cout << "Cannot find compadible vulkan driver." << std::endl; exit(EXIT_FAILURE); } else if (res) { std::cout << "unknown error" << std::endl; exit(EXIT_FAILURE); } }
The most likely cause for this is that your VkInstanceCreateInfo does contain uninitialized values. You declare it as VkInstanceCreateInfo inst_info; without initializing the structure. Later on you only set some members of it to defined values, thus passing uninitialized values to the implementation, which then fails at interpreting them. VkInstanceCreateInfo e.g. has a pNext member, which is a pointer chain to structures that can contain additional parameters for the instance creation. If this is uninitialized the implementation tries to interpret this as a pointer which will result in a read error. The correct way would be either setting all members of inst_info of zero-initializing it like this: VkInstanceCreateInfo inst_info{}; inst_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; inst_info.pApplicationInfo = &appInfo; In general (not only for Vulkan) you should zero-initialize all structs.
74,183,574
74,183,679
std::accumulate won't' perform sum of elements with std::plus functor
I have a class which contains an integer among some other things: class Foo { public: Foo() = default; Foo(int x) : x(x) {} int operator+(const Foo& rhs) { return x + rhs.x; } private: int x; float whatever = 0.0f; }; I also have a vector of these objects: std::vector<Foo> foos{1, 2, 3, 4}; now, what I wanted to do was to use std::accumulate with the std::plus functor (or maybe some other STL function) to sum the X values of all elements in the vector, here's what I tried: int sum = std::accumulate(foos.begin(), foos.end(), 0, std::plus<int>{}); But i'm getting a compiler error Error C2440: "'initializing' : cannot convert from 'type1' to 'type2' 'conversion' : cannot convert from 'type1' to 'type2'" what am i doing wrong, how do I go about fixing this?
You are trying to add an int and a Foo with a function that takes two Foos. You could use a function that adds int to Foo: // in Foo friend int operator+(int lhs, const Foo& rhs) { return lhs + rhs.x; } Or you could use a function that adds two Foos // in Foo Foo operator+(const Foo& rhs) { return { x + rhs.x }; } // in main Foo sum = std::accumulate(foos.begin(), foos.end(), Foo(0), std::plus<Foo>{});
74,184,464
74,184,540
How to validate the input of an array?
How do I validate input for the array to only accept integers? #include <iostream> #include <iomanip> #include <string> #include <string> using namespace std; int main() { int TheNumbers[10];// An array of 10 indexes int i; for (i=0; i<10; i++) // accepts input 10 times { cout << "Enter a number: "; cin >> TheNumbers[i]; } for (i=9; i>=0; i--) // returns inputs in reverse order { cout << TheNumbers[i] << endl; } // ERROR MSSG: While input is not an integer while(!(cin >> TheNumbers[10])) { cout << "**Inncorect input** \n" << "Please input a number: \n"; cin.clear(); cin.ignore(50, '\n'); } return 0; } Enter a number: Enter a number: Enter a number: Enter a number: Enter a number: Enter a number: Enter a number: Enter a number: Enter a number: 32765 -882742640 22081 1189945728 0 0 22081 1189946384 32744 0
You could try adding another nested loop: static const int MAXIMUM_NUMBERS = 10; //... for (int i = 0; i < MAXIMUM_NUMBERS; ++i) { std::cout << "Enter a number: "; while (!(cin >> number[i])) { std::cout << "Invalid number. Try again.\n"; std::cout << "Enter a number: "; std::cin.clear(); // Clear the error. std::cin.ignore(10000, '\n'); } } This is a simple example, there are other methods.
74,185,163
74,185,211
Speeding up a program that counts numbers divisable by 3 or 5
I'm trying to write a simple program that counts numbers that are divisible by 3 or 5 in a specific range. However, the program still fails to meet the desired execution time for some inputs. Here is the code: #include <cstdio> using namespace std; int main(){ unsigned long long int a=0, b=0, count=0; scanf("%d%d", &a, &b); unsigned long long int i=a; while(i<=b){ if(i%3==0){ ++count; } else if(i%10==0 || i%10==5) ++count; ++i; } printf("%d", (unsigned long long int) count); return 0; } I tried the version below too because I thought it will help with big numbers, but the results are still quite the same. #include <cstdio> using namespace std; int main(){ unsigned long long int a=0, b=0, ile=0; scanf("%d%d", &a, &b); for(unsigned long long int i=a; i<=b; ++i){ unsigned long long int liczba = i, suma=0; while(liczba>0){ suma+=liczba%10; liczba = liczba/10; } if(suma%3==0){ ++ile; } else if(i%10==0 || i%10==5) ++ile; } printf("%d", (unsigned long long int) ile); return 0; }
The divisibility of numbers by 3 and 5 repeats every 15 numbers. See, illustration 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 X X X X X X X 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 X X X X X X X Now, you need to use this fact to only check up to 15 numbers at the beginning of the range, up to 15 numbers at the end of the range and perform a multiplication to compute the rest real quick.
74,185,797
74,186,822
Why does `monotonic_buffer_resource` appear in the assembly when it doesn't seem to be used?
This is a follow-up from another question. I think the following code should not use monotonic_buffer_resource, but in the generated assembly there are references to it. void default_pmr_alloc(std::pmr::polymorphic_allocator<int>& alloc) { (void)alloc.allocate(1); } godbolt I looked into the source code of the header files and libstdc++, but could not find how monotonic_buffer_resource was selected to be used by the default pmr allocator.
The assembly tells the story. In particular, this: cmp rax, OFFSET FLAT:_ZNSt3pmr25monotonic_buffer_resource11do_allocateEmm jne .L11 This appears to be a test to see if the memory resource is a monotonic_buffer_resource. This seems to be done by checking the do_allocate member of the vtable. If it is not such a resource (ie: if do_allocate in the memory resource is not the monotonic one), then it jumps down to this: .L11: mov rdi, rbx mov edx, 4 mov esi, 4 pop rbx jmp rax This appears to be a vtable call. The rest of the assembly appears to be an inlined version of monotonic_buffer_resource::do_allocate. Which is why it conditionally calls std::pmr::monotonic_buffer_resource::_M_new_buffer. So overall, this implementation of polymorphic_resource::allocate seems to have some built-in inlining of monotonic_buffer_resource::do_allocate if the resource is appropriate for that. That is, it won't do a vtable call if it can determine that it should call monotonic_buffer_resource::do_allocate.
74,185,842
74,185,969
type casting unsigned integer
Consider val being a user input. I expect val to be between 0-65535 Instead of checking if val is not withing acceptable range before denying it, I was wondering if is this : uint16_t count = atoi(val); the same as this : uint16_t count = (uint16_t)atoi(val); Is this an acceptable way of "securing" the user input? I do not intend to send a feedback to the user, I just want to make sure it won't explode if someone submits -123 or 999999. It does not matter if count equals 2 because someone submitted 65538
Is this: uint16_t count = atoi(val); The same as this: uint16_t count = (uint16_t)atoi(val); They behave exactly the same. For the former, by assigning an int to a uint16_t, it is being implicitly converted anyway. Since a uint16_t cannot contain any more than 65536 or less than 0, the conversion safely stores the modulus of the int value in the uint16_t variable.
74,186,160
74,186,389
How to receive string result from Delphi DLL in C++Builder?
Calling a function from a DLL returning a string gives a memory error. What am I doing wrong? Note: Following codes show me the first character of the returned string and then gives a memory error. I am using Delphi 11.2 and C++Builder 5. void __fastcall TForm1::Button1Click(TObject *Sender) { HINSTANCE MyDll; typedef AnsiString(__stdcall *pfRes)(int); pfRes TestFunction; if ((MyDll = LoadLibrary("D:\\MyFirstLibrary.dll")) == NULL){ ShowMessage("Cannot Load DLL !"); return; } if ((TestFunction = (pfRes)GetProcAddress(MyDll,"TestFunction")) == NULL ) { ShowMessage("Cannot find DLL function!"); return; } ShowMessage(TestFunction(24)); FreeLibrary(MyDll); } DLL Code: (Delphi)(It works fine if call the dll from a delphi application) uses System.SysUtils, System.Classes, System.JSON; {$R *.res} function TestFunction(const _a: integer) : String; stdcall; var StrJSon : string; begin StrJSon := 'TEST STRING' Result := StrJSon; end; exports TestFunction; begin end.
Delphi's String type is an alias for AnsiString in Delphi 2007 and earlier, but is an alias for UnicodeString in Delphi 2009 and later. Since you are using Delphi 11.2, string is going to alias UnicodeString, not AnsiString. So, you have a type mismatch between your C++ and Delphi codes. However, neither type is safe to pass over a DLL boundary, unless you compile both the DLL and EXE projects with Runtime Packages enabled. In which case, you should also change the DLL project to be a Package instead, and then have the EXE load it using LoadPackage() instead of LoadLibrary(). Unfortunately, that approach is not going to work in your situation, since you are using C++Builder 5 instead of C++Builder 11.2, to match your Delphi 11.2. Runtime Packages simply do not work across major version boundaries. In which case, you will have to redesign your code to pass around a raw char* or wchar_t* pointer instead. Either: make the DLL dynamically allocate a C-style null-terminated string and return its pointer to the EXE, and then have the EXE pass that pointer back into the DLL to free the memory, eg: void __fastcall TForm1::Button1Click(TObject *Sender) { HINSTANCE MyDll; typedef char* (__stdcall *pfRes)(int); typedef void (__stdcall *pfFree)(char*); pfRes TestFunction; pfFree FreeFunction; if ((MyDll = LoadLibrary("D:\\MyFirstLibrary.dll")) == NULL){ ShowMessage("Cannot Load DLL !"); return; } TestFunction = (pfRes) GetProcAddress(MyDll, "TestFunction"); FreeFunction = (pfFree) GetProcAddress(MyDll,"FreeFunction"); if (TestFunction == NULL || FreeFunction == NULL) { ShowMessage("Cannot find DLL function!"); FreeLibrary(MyDll); return; } char *ptr = TestFunction(24); ShowMessage(ptr); FreeFunction(ptr); FreeLibrary(MyDll); } uses System.SysUtils, System.Classes, System.JSON; {$R *.res} function TestFunction(const _a: integer) : PAnsiChar; stdcall; var StrJSon : string; begin StrJSon := 'TEST STRING' Result := StrNew(PAnsiChar(UTF8String(StrJSon))); end; procedure FreeFunction(_a: PAnsiChar); stdcall; begin StrDispose(_a); end; exports TestFunction, FreeFunction; begin end. have the EXE pre-allocate a char[] or wchar_t[] buffer of sufficient size and pass a pointer to it into the DLL, which can then simply fill the buffer as needed, eg: void __fastcall TForm1::Button1Click(TObject *Sender) { HINSTANCE MyDll; typedef int (__stdcall *pfRes)(int, char*, int); pfRes TestFunction; if ((MyDll = LoadLibrary("D:\\MyFirstLibrary.dll")) == NULL){ ShowMessage("Cannot Load DLL !"); return; } TestFunction = (pfRes) GetProcAddress(MyDll, "TestFunction"); if (TestFunction == NULL) { ShowMessage("Cannot find DLL function!"); FreeLibrary(MyDll); return; } char buf[256]; if (TestFunction(24, buf, sizeof(buf)) > 0) ShowMessage(buf); /* or: int len = TestFunction(24, NULL, 0); if (len > 0) { char *buf = new char[len]; if (TestFunction(24, buf, len) > 0) ShowMessage(buf); delete[] buf; } */ FreeLibrary(MyDll); } uses System.SysUtils, System.Classes, System.JSON; {$R *.res} function TestFunction(const _a: integer; _buf: PAnsiChar; _size: Integer) : Integer; stdcall; var StrJSon : string; StrUtf8 : UTF8String; iSize : Integer; begin StrJSon := 'TEST STRING' StrUtf8 := UTF8String(StrJSon); iSize := Length(StrUtf8) + 1; if _buf = nil then Result := iSize else if _size < iSize then Result := -1 else begin Move(PAnsiChar(StrUtf8)^, _buf^, iSize); Result := iSize - 1; end; end; exports TestFunction; begin end.
74,186,548
74,186,701
Summing recursive functions return values to a variable
I'm currently learning C++ and I'm trying to complete a recursive function, which first reads a data-structure and then returns itself n-amount of times to the main function. These returns are supposed to be summed up in the main-function and assigned to a variable. In my program I have a little trickier data-structure. It is a Map, which consists of string and a vector-string. The purpose of the data-structure is to display a pyramid scheme: all the people associated with the leaders of the pyramid scheme. #include <iostream> #include <string> #include <vector> #include <map> using namespace std; int recursive_function(map<string, vector<string>> data_structure, string id) { // Going trough every name associated with the current id-name. for (auto& name : data_structure[id]) { // Recalling the function, when the current name is associated to the // first name-id declared in the main function (Hugo). recursive_function(data_structure, name); } // Returning the function, every time a single associate has been found. // In this case, we get 10 associates with Hugo, which means the recursive // function will be returned a total of 11 times (1 of these returns will be // ignored, since Hugo can't be an associate with himself in the example... cout << "Now returning." << endl; // This is just for clarity. return 1; } int main() { // Creating the data-structure, which displays a pyramid scheme. It can be // used to navigate trough connections between the people. map<string, vector<string>> data_structure; data_structure = { {"Hugo", {"Laura", "Jasper"}}, // Hugo is one of the leaders. He is // associated with Laura and Jasper, who // are associated with others etc. Laura // and Jasper too are one of the leaders. {"Laura", {"Helena", "Elias"}}, {"Jasper", {"Maria", "Bibek", "Raul"}}, {"Helena", {"Sofia", "Amelia", "Rick"}}, {"Sofia", {}} }; string id = "Hugo"; int associate_counter = 0; associate_counter += recursive_function(data_structure, id); cout << "Hugo has a total of " << associate_counter - 1 // Should print the equation 10-1 (10), but << " associates." // instead, prints 1-1 (0). << endl; return 0; } What am I doing wrong. Why can't I sum up the functions return times in the main functions associate_counter variable, by using recursion?
You're just discarding the values returned from all the calls to recursive_function. You need to add them up. Example: int sum = 0; for (auto& name : data_structure[id]) { sum += 1 + recursive_function(data_structure, name); // + 1 for the associate // + the sum of the associate's associates (recursively) } return sum; This will make it return 10 for Hugo. Demo
74,187,581
74,194,810
Using Boost::optional with ->multitoken and/or ->composing()
I'm trying to use Boost to be able to pass multiple arguments or have multiple occurrences of a flag with ->multitoken and ->composing. However, I want this to be an optional flag using boost::optional<>. Below is the basic boost example from their site, modified for my purpose. Without the boost::optional wrapper, everything works as expected. run //path/to/example:main --letter a b c results in a b c being printed. If I change options_description to be of boost::optional type: ("letter", po::value<boost::optional<vector<string>>>()->multitoken()->composing(), "multiple values"); Then --letter a b c' Errors with option '--letter' only takes a single argument And --letter a --letter b Errors with option '--letter' cannot be specified more than once Anyone know more about boost to be able to use both boost::optional and ->multitoken()/->composing()? I would like to avoid removing boost::optional and adding a default value. /* The simplest usage of the library. */ #include <boost/optional.hpp> #include <boost/program_options.hpp> namespace po = boost::program_options; #include <iostream> #include <iterator> using namespace std; int main(int ac, char* av[]) { try { po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("letter", po::value<vector<string>>()->multitoken()->composing(), "multiple values"); po::variables_map vm; po::store(po::parse_command_line(ac, av, desc), vm); po::notify(vm); if (vm.count("help")) { cout << desc << "\n"; return 0; } if (vm.count("letter")) { vector<string> list = vm["letter"].as<vector<string>>(); for (size_t i = 0; i < list.size(); ++i) cout << list[i] << " "; cout << '\n'; } } catch (exception& e) { cerr << "error: " << e.what() << "\n"; return 1; } catch (...) { cerr << "Exception of unknown type!\n"; } return 0; }
Simplicity reduces bugs and improves maintainability. Simplicity is usually when you reach the "sweet spot" of a library - the way it was designed. In this design, multi-token option are an extension of optionals (an optional is just like container with a maximum size of 1). The design does not expect you to layer both on top of each other. Instead, I'd leave the code as is and consume how you want to consume it: boost::optional<strings> dream_variable; if (vm.contains("letter")) { auto& opt = vm.at("letter"); if (!opt.defaulted()) { dream_variable = opt.as<strings>(); } } That's improving readability by using strings = std::vector<std::string>; Live Demo Live On Coliru #include <boost/optional.hpp> #include <boost/optional/optional_io.hpp> #include <boost/program_options.hpp> namespace po = boost::program_options; #include <iostream> int main(int ac, char* av[]) { using strings = std::vector<std::string>; try { po::options_description desc("Allowed options"); desc.add_options() // ("help", "produce help message") // ("letter", po::value<strings>() // ->multitoken() // ->composing() // ->implicit_value({}, ""), // "multiple values"); po::variables_map vm; store(parse_command_line(ac, av, desc), vm); notify(vm); boost::optional<strings> dream_variable; if (vm.contains("letter")) { auto& opt = vm.at("letter"); if (!opt.defaulted()) { dream_variable = opt.as<strings>(); } } if (dream_variable) { for (auto& letter : *dream_variable) { std::cout << " - " << letter << "\n"; } } else { std::cout << " * none\n"; } } catch (std::exception const& e) { std::cerr << "error: " << e.what() << "\n"; return 1; } catch (...) { std::cerr << "Exception of unknown type!\n"; return 1; } } With the output: + ./a.out --letter aa bb cc - aa - bb - cc + ./a.out --letter + ./a.out * none Note I assumed that you wanted implicit_value as well, because it's the only sensible way I can imagine how --letter without value tokens would be different from just not specifying the option.
74,187,652
74,189,353
Possible g++ linker bug in Boost on Msys2
I have already set up my Msys2 and installed mingw-w64-x86_64-boost on it. I provided a minimal example of c++ with boost which I will build using the command g++ main.cpp -o main.exe -lboost_program_options-mt: #include <boost/program_options.hpp> #include <string> #include <iostream> namespace po = boost::program_options; int main(int argc, char** argv) { // Arguments will be stored here std::string input; std::string output; // Configure options here po::options_description desc ("Allowed options"); desc.add_options () ("help,h", "print usage message") ("input,i", po::value(&input), "Input file") ("output,o", po::value(&output), "Output file"); // Parse command line arguments po::variables_map vm; po::store (po::command_line_parser (argc, argv).options (desc).run (), vm); po::notify (vm); // Check if there are enough args or if --help is given if (vm.count ("help") || !vm.count ("input") || !vm.count ("output")) { std::cerr << desc << "\n"; return 1; } std::cout << "The rest of the code will be here"; <- Indication that it is working } It compiles and links without logging an error when I ran the said command, but now when I try to run it, it just doesn't execute properly. At the least, I was expecting to see the text The rest of the code will be here to be outputted to the console when I ran it as an indication that it is being executed, however it didn't output it: I tried to debug it, but GDB itself can't debug it This is what it looks like in the VSCode Debug Console: Running a separate GBD on the command line: With all of that said, I am assuming that this is a linker error given that the resulting executable is being outputted by the compiler. What are your thoughts regarding this problem?
Yooo! I fixed the issue. I first tried to run it on a fresh virtual machine to cross out the possibility that this issue is caused by my current environment. Surprisingly enough, it worked perfectly fine on the virtual machine. Knowing that it only happens in my current environment, I did proceed to make the following changes (). Complete reinstallation of msys2 in my system, (you can disregard this step because I'm pretty sure that step 2 is enough) Moving up the priority of the msys2 path in the environment variables. To do step 2 follow these steps (windows 10): Search for "Edit environment variables for your account" in the search bar Under "User variables" select variable "path" and click edit Now, select the item for the bin path of the mingw on Msys2 Once you've selected it now, move up its priority as shown below. Press ok, then restart the terminal, and it should work now
74,188,070
74,188,159
Conversion operator with ref-qualifers: rvalue ref and const lvalue ref overloads ambiguity
While answering another question, I noticed something peculiar about conversion operators when dealing with ref-qualifiers. Consider the following code: using P = std::unique_ptr<int>; struct A { P p; operator P() && { return std::move(p); } operator P const&() const& { return p; } }; int main() { A a; P p; p = std::move(a); } This does not compile because apparently there is ambiguity when selecting the correct operator overload (see the errors in the demo below). It works if I remove the const qualifier on the second overload like this: operator P const&() & { return p; } Also, if instead of an assignment I simply construct a P object, it also works: P p = std::move(a); However, this only happens for conversion operators. If instead I write a normal member function that does the exact same thing, it compiles just fine. struct B { P p; P get() && { return std::move(p); } P const& get() const& { return p; } }; int main() { B b; P p; p = std::move(b).get(); } Why is that? What's so special about a conversion operator for these overloads to be ambiguous when they aren't on a normal member function? Full demo Side note: if instead of std::unique_ptr<int>, I use a custom non-copyable type, nothing changes. struct P { P() = default; P(P const&) = delete; P(P&&) = default; P& operator=(P const&) = delete; P& operator=(P&&) = default; }; Other side note: for some reason, MSVC doesn't say there is an ambiguity, it just selects the wrong overload. Unless I use my custom non-copyable type, in which case it agrees the call is ambiguous. So I guess it has to do with std::unique_ptr::operator=. Not too important, but if you have any idea why, I'd love to know.
When you write p = std::move(a), it is actually p.operator=(std::move(a)). There are two relevant candidates for this function: P& operator=(P&&) noexcept; // (1) Move assign operator P& operator=(const P&); // (2) Copy assign operator The fact that the second one is deleted isn't considered yet. So, the conversion from a A rvalue to something that P&& would accept in (1) calls the user defined conversion function operator P() &&. For the second overload, it would call operator const P&() const&. Both of these options are user-defined conversion functions, so neither is better in terms of overload resolution, thus an ambiguity. But if you remove the const from operator const P&() /*const*/&, it can no longer be called (since std::move(a) isn't an lvalue, so it can't call an lvalue qualified function if they aren't const qualified), and there is no ambiguity since the other choice is removed. You can try it yourself for a function not named operator=: struct P { void f(const P&) = delete; void f(P&&) {} }; struct A { P p; operator P() && { return std::move(p); } operator P const&() const& { return p; } }; int main() { A a; P p; p.f(std::move(a)); } For the case of B, std::move(b).get() is either going to be of type P or const P. The overload resolution is done by the call to get(), and an rvalue ref qualified function wins over a const lvalue ref qualified function for an rvalue, std::move(b).get() is going to be an rvalue P, and there are no ambiguities in choosing the move assign operator. For P p = std::move(a);, the overload resolution is a bit different: Since it is initializing a P object, it's looking for the best way to convert from std::move(a). The candidates are all the constructors of P + all the conversion functions of a. operator P() && beats operator P() const& because the conversion being considered is from std::move(a) to A&& or const A& to call the conversion operator, not to P&& or const P& when matching arguments of a constructor.
74,188,593
74,484,343
How to hide borders of combox and only show the bottom border in MFC?
I'm want to make a flat design ComboBox which only shows a blue bottom border. But I can only change 4 borders' color. How to hide right,left and top border and show bottom border?
Finally I made it. Just rewrite OnPaint() function and use CDC::DrawEdge(CRect, BDR_RAISEDINNER, BF_BOTTOM) to drwa a bottom border. void CCustomComboBox::OnPaint() { CPaintDC dc(this); CRect rc; GetClientRect(&rc); dc.DrawEdge(rc, BDR_RAISEDINNER, BF_BOTTOM); ... //draw other parts of ComboBox }
74,188,619
74,188,701
A class pointer does not name a type
I have 3 C++ files: Main.cpp #include "FileA.h" FileA.h #include "FileB.h" class FileA{ private: FileB* b; //It doesn't give error here! }; FileB.h class FileB{ private: FileA* A; //The error is here! }; When I run the Main.cpp file, the compiler says: 'FileA' does not name a type, did you mean 'FileB'? This is the first time I use StackOverflow to ask question so it's kinda messy, sorry. Anyone knows how to fix this problem and the cause of it ? Thank you in advance!
Spent too much time commenting and not answering. This is pretty much what Bolov showed, but with more of the gory details. Let's looks at this the way the compiler does. Whenever the compiler, really the preprocessor, finds an include directive, it replaces the include with the content of the included file. The compiler starts with Main.cpp. It sees the #include "FileA.h" and replaces it with FileA.h so now you have #include "FileB.h" class FileA{ private: FileB* b; //It doesn't give error here! }; The compiler picks up where it left off and finds #include "FileB.h" and replaces it with FileB.h. Now you have class FileB{ private: FileA* A; //The error is here! }; class FileA{ private: FileB* b; //It doesn't give error here! }; No more preprocessor work is required, so the compiler looks at the combined file. FileB is the first thing defined, and it needs a declaration of FileA to satisfy FileA* A;. The compiler hasn''t seen FileA yet, so it emits an error and keeps going. It finds FileA and the FileB* b; member, but at this point it's seen FileB, so no error. When you have a pointer or reference it's enough for the compiler to know that the identifier exists, even if it doesn't know what the named type looks like, because it doesn't have to hold an instance of the type. The fix is to forward declare FileA ahead of FileB` class FileA; // forward declaration class FileB{ private: FileA* A; //The error is here! }; class FileA{ private: FileB* b; //It doesn't give error here! }; Now FileA* A; is satisfied that there is such a thing as a FileA It doesn't know enough to construct one or how to access anything inside a FileA yet, but no one has asked it to. This resolves to a FileB.h that looks like class FileA; // forward declaration class FileB{ private: FileA* A; //The error is here! }; Bolov makes a very good point about preventing multiple includes of the same file. Sometimes you can get away with it, but often you wind up with recursive loops and nigh-inscrutable error messages. Best to be avoided with your choice of Include Guard mechanism.
74,189,699
74,189,838
Problem when deleting specifics nodes in linked list
I am trying to delete specifics nodes by a give data in my pop method, so my linked list code is: #include <iostream> #include <string> using namespace std; class Node { private: public: int n1; int n2; Node *next; Node(int n1, int n2) { this->n1 = n1; this->n2 = n2; this->next = NULL; } }; class LinkedList { private: public: Node *start; int size; LinkedList() { this->start = NULL; this->size = 0; } void append(int n1, int n2) { Node *node = new Node(n1, n2); if (this->start == NULL) { this->start = node; } else { Node *temp = this->start; while (temp->next != NULL) { temp = temp->next; } temp->next = node; } this->size++; } void print() { Node *temp = this->start; while (temp != NULL) { cout << "n1: " + to_string(temp->n1) + ", n2: " + to_string(temp->n2) + "\n"; temp = temp->next; } } void pop(int n1, int n2) { Node *temp = this->start; Node *prev = NULL; if (temp != NULL && temp->n1 == n1 && temp->n2 == n2) { this->start = temp->next; delete temp; this->size--; return; } else { while (temp != NULL && temp->n1 != n1 && temp->n2 != n2) { prev = temp; temp = temp->next; } if (temp == NULL) { return; } prev->next = temp->next; this->size--; delete temp; } } }; And then I was testing with different code in main method, so for example with the next main code I am tryng to delete the node that has (0, 0) data: int main(int argc, char const *argv[]) { LinkedList lk; lk.append(0, 0); lk.append(0, 1); lk.append(0, 2); lk.append(0, 3); lk.append(0, 5); lk.append(0, 6); lk.pop(0, 0); lk.print(); return 0; } And with the above code my output is successful because (0, 0) is not in the linked list: n1: 0, n2: 1 n1: 0, n2: 2 n1: 0, n2: 3 n1: 0, n2: 5 n1: 0, n2: 6 But with the next main code, I am tryng to delete intermediate nodes, last node, first node: int main(int argc, char const *argv[]) { LinkedList lk; lk.append(0, 0); lk.append(0, 1); lk.append(0, 2); lk.append(0, 3); lk.append(0, 5); lk.append(0, 6); lk.pop(0, 5); lk.pop(0, 1); lk.pop(0, 0); lk.pop(0, 6); lk.print(); return 0; } And with the above main code my output is nothing. It is only a message error: [Done] exited with code=3221225477 in 1.173 seconds Meanwhile my expected output should be: n1: 0, n2: 2 n2: 0, n2: 3 Testing with different main codes, I notice that my problem is in pop method, but I don´t really know how to fix it. Thanks.
This line: while (temp != NULL && temp->n1 != n1 && temp->n2 != n2) Should be while (temp != NULL && (temp->n1 != n1 || temp->n2 != n2)) Otherwise, it will delete first element that matches either n1 or n2, but not necessarily both. While we are here, let's simplify your pop() function: void pop(int n1, int n2) { Node *temp = start; Node *prev = NULL; while ( temp != NULL && ((temp->n1 != n1) || (temp->n2 != n2)) ) { prev = temp; temp = temp->next; } if (temp != NULL) { if (prev == NULL) { start = temp->next; } else { prev->next = temp->next; } size--; delete temp; } }
74,190,943
74,357,076
No line break after while-statement with clang-format
I want to configure clang-format (version 14.0.6) that it leaves single-line while-statement without adding a line break for the trailing semicolon (C++): For example, clang-format should just leave a "one-liner" as it is: while (checkWaitCondition() != true); But unfortunately clang-format adds by default a line break (plus an indentation of 4 spaces): while (checkWaitCondition() != true) ; I tried the options AllowShortBlocksOnASingleLine + AllowShortLoopsOnASingleLine, but without any impact... Does anyone have an idea how I can prevent, that clang-format breaks the semicolon into the next line? I use this .clang-format configuration file: BasedOnStyle: WebKit IndentWidth: 4 Language: Cpp AlignAfterOpenBracket: Align AllowShortFunctionsOnASingleLine: Empty AlwaysBreakTemplateDeclarations: Yes BreakBeforeBraces: Allman BreakInheritanceList: BeforeComma ColumnLimit: 120 Cpp11BracedListStyle: true IndentCaseLabels: true IndentPPDirectives: BeforeHash NamespaceIndentation: All PenaltyReturnTypeOnItsOwnLine: 1000000 SortIncludes: false DeriveLineEnding: false UseCRLF: false
I found the reason, why clang-format ignored the settings for AllowShortBlocksOnASingleLine and AllowShortLoopsOnASingleLine: I had another .clang-format file in a lower directory, which overwrote my test-configuration... With both flags set to true, the format works as expected, with the following setting in the .clang-format file: AllowShortLoopsOnASingleLine: true AllowShortBlocksOnASingleLine: true Produces the following format: while (checkWaitCondition() != true) { } But for my purpose, I want to use the continue statement from now, to improve the readability: while (checkWaitCondition() != true) { continue; }
74,191,067
74,306,384
Using preload-file compiler option for emscripten compiler to load local file in Qt
I am building an Qt Application using WebAssembly. I want to open a local file and read it frin my code which isn't exacty easy with WebAssembly. I tried using the preload-file option (reference) in my .pro file: CONFIG += preload-file /path/to/file/Settings.ini However, when compiling my application with WebAssembly, It fails showing my the following error: Application exit (RuntimeError: Aborted(native code called abort())) I am currently using Qt 6 with the fitting Emscripten version. My code works when compiling with GCC. Of course, emscripten compiles when removing the file handling stuff from my code. Using a file dialog isn't a suitable option.
I noticed you are using CONFIG += but the emscripten reference says it is a linker flag. Try using instead QMAKE_LFLAGS += --preload-file /path/to/file/Settings.ini. Personally, I have not tested preload-file option but two other options have been working for me: The similar embed-file functionality. In the .pro file add QMAKE_LFLAGS += --embed-file ../../cdpcore/Templates/Models@Models to make the folder specified to be available in [working directory]/Models. Use the Qt Resource system to embed files. Basically add a .qrc file to your project that lists resources to embed into the binary and then into the .pro file add RESOURCES += resources.qrc.
74,191,460
74,191,695
How to force terminate std::thread by TerminateThread()?
I called IMFSourceReader::ReadSample and I found it was stuck if it cannot read data. So I tried to terminate the thread by TerminateThread() but it returned 0 as a fail. How could I terminate the stuck thread? This is my sample code: #include <iostream> #include <vector> #include <codecvt> #include <string> #include <thread> #include <mutex> #include <chrono> #include <condition_variable> #include <Windows.h> using namespace std::chrono_literals; class MyObject { private: ... std::thread *t; std::mutex m; std::condition_variable cv; std::thread::native_handle_type handle; int getsample(uint8_t* data) { // call a ReadSample hr = pVideoReader->ReadSample( MF_SOURCE_READER_ANY_STREAM, // Stream index. 0, // Flags. &streamIndex, // Receives the actual stream index. &flags, // Receives status flags. &llTimeStamp, // Receives the time stamp. &pSample // Receives the sample or NULL. ); ... return 0; } int myfunc_wrapper(uint8_t* data) { int ret = 0; BOOL bpass = 0; if (t == nullptr) { t = new std::thread([this, &data, &ret]() { ret = this->getsample(data); this->cv.notify_one(); }); handle = t->native_handle(); t->detach(); } { std::unique_lock<std::mutex> l(this->m); if (this->cv.wait_for(l, 2500ms) == std::cv_status::timeout) { bpass = TerminateThread(handle, 0); if (bpass == 0) { std::cout << "TerminateThread Fail! " << GetLastError() << std::endl; } throw std::runtime_error("Timeout Fail 2500 ms"); } } delete t; t = nullptr; } public: int my_func(uint8_t* raw_data) { bool timedout = false; try { if (myfunc_wrapper(raw_data) != 0) return -1; } catch (std::runtime_error& e) { std::cout << e.what() << std::endl; timedout = true; } if (timedout) return -1; return 0; } }; int main() { uint8_t data[512]; MyObject* obj = new MyObject(); while (true) { obj->my_func(data); } return 0; } Output: TerminateThread Fail! 6 Timeout Fail 2500 ms TerminateThread Fail! 6 Timeout Fail 2500 ms ... I also tried to use pthread_cancel but it cannot be compiled because there is a type error. no suitable constructor exists to convert from "std::thread::native_handle_type" to "__ptw32_handle_t" handle = t->native_handle(); ... pthread_cancel(handle); // no suitable constructor exists to convert
The reason it failed to terminate is that the native handle is no longer valid after detaching, one way you could do this is to OpenThread using the thread id to get a new handle. To get the thread id, you could use its handle before detaching like this: DWORD nativeId = GetThreadId(t->native_handle()); t->detach(); After that, just open a new handle to the thread to terminate it: HANDLE hThread = OpenThread(THREAD_TERMINATE, FALSE, nativeId); if (hThread) { BOOL result = TerminateThread(hThread, 0); CloseHandle(hThread); } But you should not do this, consider other ways to signal the thread to terminate on its own.
74,191,617
74,191,697
How to return std::array of different size based on compile-time switch?
I need to create an array of static data, where the size (and data) is known at compile time, but differs between build configurations. This is a very dumbed-down version of what I'm trying to do (Please ignore glaring bad practices in this code as it is just an example): constexpr ProductType PRODUCT = ProductType::A; constexpr size_t dataSize() { return PRODUCT == ProductType::A ? 3 : 4; } constexpr std::array<int, dataSize()> createArray() { if constexpr (dataSize() == 4) { return std::array<int, dataSize()>{1, 2, 3, 4}; } else { return std::array<int, dataSize()>{1, 2, 3}; } } But this code fails to compile. The first branch of the constexpr-if is still evaluated and deemed invalid: <source>:22:54: error: too many initializers for 'std::array<int, 3>' 22 | return std::array<int, dataSize()>{1, 2, 3, 4}; | ^ But reading the docs I was under the impression that the code in the non-active branch of constexpr-if can contain code that will return wrong type, so why wouldn't this work?
The condition you pass to if constexpr does not depend on any template parameters, so both branches are compiled. From cppreference Outside a template, a discarded statement is fully checked. if constexpr is not a substitute for the #if preprocessing directive void f() { if constexpr(false) { int i = 0; int *p = i; // Error even though in discarded statement } }
74,192,257
74,195,313
Enabling the empty base class optimization globally in a C++ project on Windows
MSVC seems to disable empty base class optimization (EBO/EBCO) when using multiple inheritance. Sadly, this means that other compilers targetting windows have to also disable EBO in such scenarios. Now, MSVC provides __declspec(empty_bases) for re-enabling it, but now you have to put this attribute in every class that relies EBO. Is there a way to disable this behavior globally? That is, are there any compiler flags that will re-enable EBO for a project? (I'm mainly interested in clang with the GNU command line).
Is there a way to disable this behavior globally? That would break ABI compatibility with every type declared by any C++ code on your platform. Including code from your standard library or any pre-compiled library you link to, as well as any DLLs and the like. So... no, there is no way to do that. Platform ABIs, even when they are wrong, are not optional. If you want to have a type that doesn't follow platform ABI rules, that type's declaration has to have something in it to distinguish itself from those which do follow the platform's ABI rules.
74,192,356
74,203,599
Why does this vector throw a bad allocation exception?
Why does this seemingly innocent function throw a bad allocation exception for noUrls=300,000,000? #include <string> #include <vector> #include <algorithm> void generateUrls(int noUrls) { std::vector<std::string> urls; urls.resize(noUrls); //this always works std::size_t i = 0; std::string url = "abcdefghijklmnop"; urls[i] = "https://www." + url + ".com/home/index"; i++; while (std::next_permutation(url.begin(), url.end()) && (i < noUrls)) { urls[i] = "https://www." + url + ".com/home/index"; //this where it throws i++; } } int main() { generateUrls(100000000); //do something with the result return 0; } Why? Clues: noUrls=300,000,000 is not causing an overflow, my platform's maximum int size of 2,147,483,647 The resulting vector will be about 12GB large My system has 8GB physical RAM, but a page file size of another 16GB, so would have expected it to just stick some of the vector in the page file if it runs out of physical RAM. (A stupid assumption?)
You are only counting characters, but std::string is not just characters. On my platform, sizeof(std::string) is 32. That's about 9GiB for an array of zero-length strings, before you start adding any characters. If a string is short, most implementations keep the characters inside those 32 bytes to avoid allocations. But your strings are longer than that, so the characters are allocated on the free store. Add 12 GiB worth of characters, and you are well out of memory.
74,192,442
74,194,588
Template func with cond. const argument + template arg deduction
I am implementing a wrapper class that wraps some base class object. I want the wrapper to be as unnoticeable as possible and therefore, I have already overloaded the -> operator to return a reference to the wrapped object in order to provide immediate access to the base-class's interface. Additionally, I want my wrapper type to also implement all operators that the base-class implements and just delegates the respective operator calls to the wrapped object. However, since I want to be able to wrap any arbitrary base-class, I don't know a priori what operators are defined for the wrapped class. My current approach consists of just defining all operators for my wrapper and using SFINAE to disable those implementations that are not covered by base-class implementations. The implementation for the operator overload essentially always looks like this auto operator <operator> (const Wrapper &lhs, const Wrapper &rhs) { return lhs.get() <operator> rhs.get(); } auto operator <operator> (const Wrapper &lhs, const Base &rhs) { return lhs.get() <operator> rhs; } auto operator <operator> (const Base &lhs, const Wrapper &rhs) { return lhs <operator> rhs.get(); } where <operator> is the respective operator. Since, I don't want to duplicate this code for all operators, I have defined some macros to create the definitions for me. This works for most operators, but now I also want to support the various assignment operators (e.g. *=). Here, the lhs argument must not be const as it is modified via the action of the operator. I could just generate these separately, but I thought that there must be a way to simply make the lhs argument const or non-const depending on a constexpr boolean (available as macro-parameter). Thus, I created a templated helper cond_add_const< T, bool > that returns const T if passed true and T if passed false. The problem now is, that the overloads that involve the Base class as direct parameters fail to be resolved due to template argument deduction failure. The problem seems to be that in order to apply my conditional const, I essentially have the replace the respective type with cond_add_const< T, true >::type and apparently everything to the left of :: does not participate in template argument deduction. This seems rather frustrating and it also feels like for my simple case there should be a possibility to circumvent this limitation (or choose an approach that does not require it), but I just can't come up with one (that does not involve duplicating code). Any ideas? MWE illustrating my problem: #include <type_traits> template< typename T, bool is_const > struct cond_add_const { using type = typename std::conditional< is_const, typename std::add_const< T >::type, typename std::remove_const< T >::type >::type; }; template< typename T > void myFunc(typename cond_add_const< T, true >::type lhs, int rhs) { } int main() { myFunc(1, 2); } Compiling this snippet with g++ results in test.cpp: In function ‘int main()’: test.cpp:11:13: error: no matching function for call to ‘myFunc(int, int)’ 11 | myFunc(1, 2); | ^ test.cpp:7:29: note: candidate: ‘template<class T> void myFunc(typename cond_add_const<T, true>::type, int)’ 7 | template< typename T > void myFunc(typename cond_add_const< T, true >::type lhs, int rhs) { | ^~~~~~ test.cpp:7:29: note: template argument deduction/substitution failed: test.cpp:11:13: note: couldn’t deduce template parameter ‘T’ 11 | myFunc(1, 2); |
You might turn your template functions in non-template friend function of your class: template <typename T> struct Wrapper { // ... friend void myFunc(typename cond_add_const<Wrapper<T>, true >::type lhs, T rhs) { /*...*/ } }; Demo There are some caveats: the friend function can only be found via "ADL" (So at least one parameter should be of the Wrapper type).
74,192,646
74,192,876
Downcasting to base type of vector of shared_ptr
#include <vector> #include <memory> class Base { public: virtual ~Base() = default; virtual int f() = 0; }; class Derived : public Base { public: ~Derived() = default; int f() override { return 0; } }; int main() { const std::vector<std::shared_ptr<const Base>> vec{std::make_shared<const Derived>()}; } failed at compile time, then at link time, when I originally posted it here with two mistakes in the code. Too late to delete; no way to revert to the initial form. Hence let it stay as a minimal example to demonstrate that a vector of a shared_ptr can have a polymorphic base type. I have seen other questions touching this topic, with answers suggesting we need a pure virtual base class. Hence the virtual destructor and the pure virtual function in the above minimal example.
There is no problem with having a polymorphic type here, but you need to explicitly say that std::make_shared<const Derived>() is supposed to be an element, and not an argument of some fancy constructor. std::vector doesn't have any constructor that takes a single std::shared_ptr, but you can redirect the name lookup with use of curly braces initialisation syntax (it gives priority to std::initialiser_list constructors, and treats the enclosed objects as elements): const std::vector<std::shared_ptr<const Base>> vec{ std::make_shared<const Derived>(); }
74,193,198
74,193,247
Run function every 5s inside loop running every second
I need to run my function MyFunc() every five seconds using the parameters in the code (i.e. minimum code changes). There are two parameters in the code: ts and std::chrono::system_clock::now() What do I write in condition so that I can run my function at the interval? auto ts = std::chrono::system_clock::now() + std::chrono::seconds(1); do { // 1s timer if ( ts <= std::chrono::system_clock::now()) { // ... doing some work // here I need to start MyFunc() every 5s if (condition) { MyFunc(); } ts += std::chrono::seconds(1); } } while (isWork);
The way in my mind is to check whether the time passed is greater than 5 seconds. You could do something similar to this, where there is a separate variable to keep track of 5 seconds after the last time that the function was run: auto ts = std::chrono::system_clock::now() + std::chrono::seconds(1); auto fiveseconds = std::chrono::system_clock::now() + std::chrono::seconds(5); do { // 1s timer if ( ts <= std::chrono::system_clock::now()) { // ... doing some work // here I need to start MyFunc() every 5s if (fiveseconds <= std::chrono::system_clock::now()) { MyFunc(); fiveseconds = std::chrono::system_clock::now() + std::chrono::seconds(5); } ts += std::chrono::seconds(1); } } while (isWork); Note that this may not run it exactly every five seconds, just about when it runs the once-a-second loop, and then checks if it has been over five seconds.
74,193,446
74,195,111
Code to convert decimal to hexadecimal without using arrays
I have this code here and I'm trying to do decimal to hexadecimal conversion without using arrays. It is working pretty much but it gives me wrong answers for values greater than 1000. What am I doing wrong? are there any counter solutions? kindly can anyone give suggestions how to improve this code. for(int i = num; i > 0; i = i/16) { temp = i % 16; (temp < 10) ? temp = temp + 48 : temp = temp + 55; num = num * 100 + temp; } cout<<"Hexadecimal = "; for(int j = num; j > 0; j = j/100) { ch = j % 100; cout << ch; }
There's a couple of errors in the code. But elements of the approach are clear. This line sort of works: (temp < 10) ? temp = temp + 48 : temp = temp + 55; But is confusing because it's using 48 and 55 as magic numbers! It also may lead to overflow. It's repacking hex digits as decimal character values. It's also unconventional to use ?: in that way. Half the trick of radix output is that each digit is n%r followed by n/r but the digits come out 'backwards' for conventional left-right output. This code reverses the hex digits into another variable then reads them out. So it avoids any overflow risks. It works with an unsigned value for clarity and a lack of any specification as how to handle negative values. #include <iostream> void hex(unsigned num){ unsigned val=num; const unsigned radix=16; unsigned temp=0; while(val!=0){ temp=temp*radix+val%radix; val/=radix; } do{ unsigned digit=temp%16; char c=digit<10?'0'+digit:'A'+(digit-10); std::cout << c; temp/=16; }while(temp!=0); std::cout << '\n'; } int main(void) { hex(0x23U); hex(0x0U); hex(0x7U); hex(0xABCDU); return 0; } Expected Output: 23 0 8 ABCD Arguably it's more obvious what is going on if the middle lines of the first loop are: while(val!=0){ temp=(temp<<4)+(val&0b1111); val=val>>4; } That exposes that we're building temp as blocks of 4 bits of val in reverse order. So the value 0x89AB with be 0xBA98 and is then output in reverse. I've not done that because bitwise operations may not be familiar. It's a double reverse! The mapping into characters is done at output to avoid overflow issues. Using character literals like 0 instead of integer literals like 44 is more readable and makes the intention clearer.
74,193,587
74,193,822
Function that accepts any pointer type
I have a function void Foo(MyType* mt). I want callers to be able to pass any pointer type to this function (e.g. unique_ptr, shared_ptr or iterator) and not require passing a raw pointer. Is there any way to express this? I could write: template <typename T> void Foo(T t); This will work since it will only compile if T supports operator-> and operator* which I use inside Foo, it will also only work if T has the same interface as MyType but it seems wrong to not specify in the API that I expect that template argument to be a pointer to MyType. I could also write my own wrapper: template <typename T> class PointerWrapper { public: PointerWrapper(T* t) : raw_ptr(t) {} PointerWrapper(const std::unique_ptr<T>& t) : raw_ptr(t.get()) {} ... private: T* raw_ptr; }; void Foo(PointerWrapper<MyType> mt); This seems clunky because I will need to extend PointerWrapper for every smart pointer type under the sun. Is there an accepted way to support this?
In C++20, you'd write a concept such as template <typename P, typename T> concept points_to = requires(P p) { { *p } -> std::common_reference_with<T &> } && std::equality_comparable_with<std::nullptr_t> template <points_to<MyType> T> void Foo(T t); Prior to that, you could write something involving std::pointer_traits template <typename T> std::enable_if_t<std::is_same_v<MyType, typename std::pointer_traits<T>::element_type>> Foo(T t);
74,194,101
74,194,210
Why does the rvalue parameter change to lvalue when used?
I pass rvalue std::move(x) to testForward(T&& v), but it calls print(T& t) inside. It seems that the rvalue v has changed to an lvalue before it calls print(). I do not know why this happened. Can anyone explain it? #include<iostream> using namespace std; template<typename T> void print(T& t) { std::cout << "Lvalue ref" << std::endl; } template<typename T> void print(T&& t) { std::cout << "Rvalue ref" << std::endl; } template<typename T> void testForward(T&& v) { print(v); // call print(T& t); } int main(int argc, char* argv[]) { int x = 1; testForward(std::move(x)); // output: Lvalue ref }
The value category of the expression v is an lvalue, because: ... Even if the variable's type is rvalue reference, the expression consisting of its name is an lvalue expression If you want to forward a forwarding reference as its original category, use std::forward, ie, template<typename T> void testForward(T&& v) { print(std::forward<T>(v)); }
74,194,673
74,194,731
How to use std::get in a tuple wrapper class?
I have an object that must store a tuple for some reason, something similar to this: template<typename... Types> class MultiStorer { public: tuple<Types...> my_tuple; MultiStorer(Types... elem) : my_tuple(tuple<Types...>(elem...)) {}; auto getElem(int&& pos) { return get<pos>(my_tuple); } }; But i get this compiler error C2672: 'get': no matching overloaded function found. I don`t get errors when I use 'get' over an instance of the object outside the class, just when I use 'get' inside of the class. int main() { MultiStorer multistorer{ int(2),int(3) }; cout << get<0>(multistorer.my_tuple); // This works cout << multistorer.getElem(0); // This doesn't return 0; }
A function parameter can never be used as a constant expression, so you cannot use it as the non type template parameter of get. What you can do is make your own function a template like template <std::size_t pos> auto getElem() { return get<pos>(my_tuple); } and then you would use it like cout << multistorer.getElem<0>();
74,194,702
74,194,989
Non-const reference of Eigen matrix only bind with dynamic types and not with non-dynamic types
I have an Eigen (3.4.0) related question that really troubles me. In this C++ code, there's a function pass_by_nonconst_ref which takes a non-const reference to a eigen matrix, and that does some work on the matrix. #include <iostream> #include "Eigen/Eigen" using namespace std; // A function that takes a non const reference to a vector void pass_by_nonconst_ref(Eigen::Matrix<float, -1, 1>& vec) { // do some work on your matrix... vec(0) = 1; } int main() { // This works without any problem. Eigen::Matrix<float, -1, 1> x1(3); x1 << 0.0, 0.0, 0.0 ; pass_by_nonconst_ref(x1); cout << "x = " << x1 << endl ; // But this does not !!!! Eigen::Matrix<float, 3, 1> x2; x2 << 0.0, 0.0, 0.0 ; // if you uncomment this line, it won't compile... // pass_by_nonconst_ref(x2); cout << "x = " << x2 << endl ; // And to check that x2 is not a temporary? Eigen::Matrix<float, 3, 1> x3; x3 << 0.0, 0.0, 0.0 ; x3(0) = 1; cout << "x = " << x3 << endl ;// this works return 0; } This code only compiles if I pass to the function an object the type Eigen::Matrix<float, -1, 1>. If I use instead Eigen::Matrix<float, 3, 1>, then there is the following compilation error: error: cannot bind non-const lvalue reference of type ‘Eigen::Matrix<float, -1, 1>&’ to an rvalue of type ‘Eigen::Matrix<float, -1, 1>’ 22 | pass_by_nonconst_ref(x2); The only difference (that I see) is that x2 knows it only has 3 rows, whereas x1 has a dynamic number of rows. I am aware that a non-const reference can't bind to a temporary, but I really don't see why x2 can be considered as one and not x1. I can't understand why I have to specify the dynamic type to make it work. It got me quite curious. Is there something obvious that I am missing ? I suspect it is related to type conversion.
Eigen::Matrix<float, 3, 1> is a different type than Eigen::Matrix<float, -1, 1>. The only reason the function call resolves at all when you call it with x2 is that Eigen supplies an implicit cast operator that knows how to create a dynamic matrix from a fixed-size one. However, what this means is that a temporary is created and passed, which is what is causing your error. See the Eigen documentation at the section "In which cases do functions taking a plain Matrix or Array argument fail?" That same page provides alternate ways to write your function so that it takes Eigen matrices of all types. If you use this signature, your program compiles and runs: template <typename Derived> void pass_by_nonconst_ref(Eigen::MatrixBase<Derived>& vec) { // do some work on your matrix... vec(0) = 1; } Still, beware of temporaries, since Eigen passes around expression types. The documentation page suggests (argh!) in some cases accepting a const reference and casting away the constness. If you pass a plain local Eigen matrix object as I wrote above, you should be fine.
74,194,786
74,194,933
BOOST Asio async_write_some vs asio::async_write , force a single write operation
Some special files have semantics associated with individual writes. (For example, FunctionFS (USB gadgets in userspace) associates a single write to a sequence of USB packets within a single USB transfer. Two writes will never be merged into a single USB packet. Hence the first write may end with a short packet.) I therefore don't want to use asio::async_write, because it allows zero or more calls to the underlying async_write_some of the passed stream. However if I use stream.async_write_some directly, it allows that not all the data will have been written. What I need is the guarantee that the streams's async_write_some (of posix::basic_stream_descriptor) passes all buffers in the sequence to the vectored write system call, and write less data only when the system call decides to do so. How can I achieve that? Am I on the completely wrong way?
What would you use in terms of POSIX API? Likely it ends up the exact same underlying API that ASIO hooks into. So, if that API behaves in the way you describe you can expect ASIO to behave in the same way (not resulting in partial completions). The only place where I readily know ASIO might have opinions on buffer division/operation is the other way around where SSL buffer-sequences may be combined prior to writes for performance reasons. It would help if we knew both interfaces you're trying to contrast/impact analyze. E.g. there will be a difference between using asio::posix::stream_descriptor or asio::serial_port for obvious reasons. There might be platform differences at play, but I assume the platform is Linux because of FunctionFS.
74,195,031
74,195,350
how to jump a line in file c++
I want to increase second line in my file but I can't, please help me. Here is my file content 0 0 I want to increase second 0 by 1, here is my code #include <iostream> #include <fstream> #include <string> int main() { std::fstream file; file.open("file1.txt"); std::string line; getline(file, line); getline(file, line); int a = std::stoi(line); ++a; line = std::to_string(a); file.close(); file.open("file1.txt"); std::string line1; getline(file,line1); getline(file,line1); file << line; file.close(); }
You are trying too hard. This is the easy way int main() { std::ifstream file_in("file1.txt"); int a, b; file_in >> a >> b; file_in.close(); ++b; std::ofstream file_out("file1.txt"); file_out << a << '\n' << b << '\n'; file_out.close(); } Read the whole contents of the file. Make the modification needed. Write the whole contents of the file. Doing partial updates (as you are trying) can be done, but it's tricky.
74,195,215
74,195,265
How to convert a string containing only 0 or 1 into a binary variable?
How to convert a C++ string (containing only "0" or "1") to binary data directly according to its literal value? For example, I have a string str, it's value is 0010010. Now I want to convert this string to a binary form variable, or a decimal variable equal to 0b0010010 (is 18). int main() { string str_1 = "001"; string str_2 = "0010"; string str = str_1 + str_2; cout << str << endl; int i = stoi(str); double d = stod(str); cout << i << " and " << d << endl; } I tried stoi and stod, but they all can't work. They all treated binary 0b0010010 as decimal 10010. So how can I achieve this requirement? Thanks a lot!
std::stoi has an optional second argument to give you information about where the parsing stopped, and an optional third argument for passing the base of the conversion. int i = stoi(str, nullptr, 2); This should work. Corollary: If in doubt, check the documentation. ;-)
74,195,991
74,197,399
C++ stringstream question, how can I make each line seperate
I'm sorry the title may be inaccurate.I'm new to C++. Here is my code and output... #include <iostream> #include <sstream> using namespace std; class LogLine { private: stringstream ss; string message; public: ~LogLine() { ss << "\n"; message = ss.str(); cout << message; message = ""; } template <class T> LogLine& operator<<(const T& thing) { ss<< thing; return *this; } LogLine& operator<<(std::ostream &(*manip)(std::ostream &)) { manip(ss); return *this; } }; int main(int argc, char *argv[]) { LogLine log; cout<< "Line One"<<endl; log << "I'm " << 25 << " years old...."<<endl; cout<<"Line Two"<<endl; log << "I " << "Live in " << " Houston...."; return 0; } Current output: Line One Line Two I'm 25 years old.... I Live in Houston.... Desired output: Line One I'm 25 years old.... Line Two I Live in Houston.... I hope in each line of "log" be able to detect the end of that line and print out current message, and then clean itself. I know the reason of current output, but I can't figure out how should I modify my code to get desired output.("endl" can be missing) Thanks a lot for any comments. As described above...
When I understand you correctly, you want to detect the end of the statement, where log is used, and then append a std::endl. My solution is similar to that one of @MarekR, but it forces a line break, when log is not rebound: It does not detect "\n" and flushes it to std::cout, that would be contra productive on parallel std::cout calls. #include <iostream> #include <sstream> using std::cout; using std::endl; class LogLine { std::stringstream ss; public: LogLine(LogLine&&) noexcept = default; LogLine() = default; ~LogLine() { if(ss && ss.peek() != -1){ cout << ss.str() << std::endl; } } template <class T> friend LogLine operator<<(LogLine& lhs, const T& thing) { lhs.ss << thing; return std::move(lhs); } template <class T> friend LogLine&& operator<<(LogLine && lhs, const T& thing) { lhs.ss << thing; return std::move(lhs); } LogLine&& operator<<(std::ostream& (*manip)(std::ostream&)) { manip(ss); return std::move(*this); } }; int main() { LogLine forced; cout << "Line One" << endl; forced << "I'm " << 25 << " years old...."; cout << "Line Two" << endl; LogLine() << "I " << "Live in " << " Houston...." << endl << endl << endl; forced << "forced 2"; std::cout << "End of the sausage" << std::endl; return 0; } That what happens here is: every call to operator<< creates a temporary, which steals the resources of the original structure. Therefore, when it is not rebound, the destructor gets called directly after the line, flushing the stringstream.
74,198,046
74,198,144
Overriding protected field members in C++ not working?
In the following, I expected class Child's protected field member _AorB to be of type B, and not A, but reality shows otherwise. What am I mis-understanding, and how can I adjust the code for the desired behavior? class A{ public: void doit(){ std::cout<<" this is A!"<<std::endl; } }; class B{ public: void doit(){ std::cout<<" this is B!"<<std::endl; } }; class Parent{ public: void doit(){ _AorB.doit(); } protected: A _AorB; }; class Child: public virtual Parent{ protected: B _AorB; }; int main() { cout<<"Hello World"; auto c = Child(); c.doit(); // I expected this to print "This is B" because c is Child(), and Child class's _AorB is of type B. return 0; }
You can make such changes: template <typename AorB> class Parent{ public: void doit(){ _AorB.doit(); } protected: AorB _AorB; }; class Child: public virtual Parent<B> { } Also take a look at What are the rules about using an underscore in a C++ identifier? Reserved in any scope, including for use as implementation macros: identifiers beginning with an underscore followed immediately by an uppercase letter
74,199,536
74,262,045
Computing the outer product of two vectors in Eigen c++
I have a piece of python code written using numpy that I'm trying to port over to C++ using the eigen library. I haven't really found anything suitable in the eigen library. This is the python equivalent: u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x = np.outer(np.cos(u), np.sin(v)) y = np.outer(np.sin(u), np.sin(v)) z = np.outer(np.ones(np.size(u)), np.cos(v)) And What I've written using the Eigen Library is: Eigen::VectorXf u = Eigen::VectorXf::LinSpaced(100, 0, 2*PI); Eigen::VectorXf v = Eigen::VectorXf::LinSpaced(100, 0, PI); Eigen::MatrixXf x = u.cos().cross(v.cos()); Eigen::MatrixXf y = u.sin().cross(v.sin()); Eigen::MatrixXf z = Eigen::VectorXf::Ones(u.size()).cross(v); Unfortunately, it looks like the cross function only works for vectors of size 3 as I get this error: THIS_METHOD_IS_ONLY_FOR_VECTORS_OF_A_SPECIFIC_SIZE and I'm trying to compute for a much larger size. I found this from a thread a while back but it doesn't seem that this functionality was implemented. Does anyone know how to achieve this?
To achieve the same behavior as np.outer(a, b), where a and b are both column vectors (i.e. VectorXf for instance) in Eigen it would simply be: a * b.transpose() For info, the thread you linked has nothing to do with the outer product. Rather, it's about the "exterior product" (I know the two names are confusingly similar to each other); this is also known as wedge product and it is basically an extension of the cross product to N-dimensional vectors. According to this definition, the exterior product of N dimensional vectors is a skew-symmetric NxN matrix with i,j-th entry equal, up to the sign, a[i]*b[j] - a[j]*b[i], while on the case of the outer product it would simply be a[i]*b[j]
74,199,759
74,200,039
Is there a way to pass a brace enclosed list to variadic templates?
I would like to pass a variable list of objects to be passed to a template function as a series of brace enclosed initializers. So something like this: enum class E { a, b, c }; template <typename T> struct Info { template <typename U> Info(E e, U u) : e(e) , size(sizeof(u)) {} E e; size_t size; }; template <typename...Ts> void fn(Info<Ts>&&...args) { } int f() { fn({ E::a, 5 }); } If I replace the above with concrete types, the brace enclosed initializers does work: enum class E { a, b, c }; struct InfoBase { E e; int size; }; void f1(InfoBase&& a, InfoBase&& b) { } void f() { f1({ E::a, 4 }, { E::b, 6 }); } But replacing f1 with the following fails: void f1() { } template <typename...Ts> void f1(InfoBase&& a, Ts&&...args) { f1(std::forward<Ts>(args)...); } Presumably because it's can't infer Ts? Error messages are: <source>: In function 'void f()': <source>:22:7: error: no matching function for call to 'f1(<brace-enclosed initializer list>, <brace-enclosed initializer list>)' 22 | f1( { E::a, 4 }, { E::b, 6 } ); | ~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~ <source>:16:6: note: candidate: 'void f1(InfoBase&&, Ts&& ...) [with Ts = {}]' 16 | void f1(InfoBase&& a, Ts&&...args) { | ^~ <source>:16:6: note: candidate expects 1 argument, 2 provided <source>:14:6: note: candidate: 'void f1()' 14 | void f1() { } | ^~ <source>:14:6: note: candidate expects 0 arguments, 2 provided I'm thinking that because Ts has no concrete type to bind to, it just fails, even though that information is available later in the call tree. Is that correct? Is what I'm attempting just not possible?
Since the plain {}, has no type, it can not be used in the template type deduction. From what I understood, that you're trying to achieve, I propose the following template <typename T, typename...Ts> void fn(E e, T&& val, Ts&&...args) { Info<T> ob{ e, std::forward<T>(val) }; // do something with ob // .... if constexpr (sizeof...(args) == 1u) { std::cout << "At least required two args!\n"; // other error msgs or handling } else if constexpr (sizeof...(args)) { fn(std::forward<Ts>(args)...); // process what left by recursive calls } } Now pass/ call the function as fn(E::a, 4, E::b, 6); See a demo in godbolt.org
74,199,956
74,201,242
QSqlQuery fails to get SQL Server stored procedure output value
I am converting web server code written in VB.NET to Qt 5.15.12. The server accesses a Microsoft SQL Server 2012 database. I have several stored procedures that take an output parameter. The output parameter works as expected with VB.net. One stored procedure is giving me issues in Qt. The stored procedure checks if a record exists in a table. If not, it adds it. If so, it updates it. The stored procedure initially returned @@ROWCOUNT but I could not figure out how to get Qt to give me the stored procedure return value so I added an output parameter. The stored procedure essentially looks like this: CREATE PROCEDURE AddUpdateRecord @Param1 NChar(12), @Param2 NVarChar(80), @RetVal Int Output AS BEGIN SET NOCOUNT ON SET @RetVal = 0 SELECT Column1 FROM MyTable WHERE Column1=@Param1 IF @@ROWCOUNT > 0 BEGIN UPDATE MyTable SET Column2=@Param2 WHERE Column1=@Param1 SET @RetVal = @@ROWCOUNT END ELSE BEGIN INSERT INTO MyTable (Column1, Column2) VALUES (@Param1, @Param2) SET @RetVal = @@ROWCOUNT END END The Qt code that calls the stored procedure looks like this: QSqlQuery qry(dbObject); qry.prepare("execute AddUpdateRecord ?, ?, ?); qry.bindValue(0, "012345678912"); qry.bindValue(1, "ABCDEFGHIJKLMNOP"); qry.bindValue(2, QVariant(int(-1)), QSql::Out); if ( qry.exec() && (qry.boundValue(2).toInt() > 0) ) { return(true); } return(false); If I call the stored procedure with a key that does NOT exist, I successfully get the output value. If I call it with a key that DOES exist, the bound value does not change from -1. Am I doing something wrong that is preventing Qt from getting the output value or is this a bug in Qt?
A bare SELECT in the body of the stored procedure sends a resultset to the client. SELECT Column1 FROM MyTable WHERE Column1=@Param1 The output parameter is sent after the resultset in the TDS response, and in many client libraries you must consume the resultset before checking the output parameters. You can avoid this and improve this procedure by removing a race condition like this: CREATE PROCEDURE AddUpdateRecord @Param1 NChar(12), @Param2 NVarChar(80), @RetVal Int Output AS BEGIN SET NOCOUNT ON SET @RetVal = 0 BEGIN TRANSACTION IF EXISTS (SELECT * FROM MyTable with (updlock,holdlock) WHERE Column1=@Param1) BEGIN UPDATE MyTable SET Column2=@Param2 WHERE Column1=@Param1 SET @RetVal = @@ROWCOUNT END ELSE BEGIN INSERT INTO MyTable (Column1, Column2) VALUES (@Param1, @Param2) SET @RetVal = @@ROWCOUNT END COMMIT TRANSACTION END
74,200,487
74,213,792
Is there a precedence to type_traits?
I'm pretty new to SFINAE, and was wondering if there's a precidence to which template the compiler will select if multiple std::enable_if_t<true, std::is_...<T>> end up applying to T. Like in this example: template<typename T, typename = void> class Thing { // Thing A }; template<typename T> class Thing<T, std::enable_if_t<true, std::is_scalar<T>> { // Thing B }; template<typename T> class Thing<T, std::enable_if_t<true, std::is_float<T>> { // Thing C }; template<typename T> class Thing<T, std::enable_if_t<true, std::is_signed<T>> { // Thing D }; template<> class Thing<float> { // Thing E }; int main(){ Thing<float> x; // what order would the compiler try out? } I think it'll try to pick the most "specific" template specialization, so E first, and A last, but that's all I'm sure of. I don't know how it'd disambiguate from B, C, or D, or how to combine multiple conditions for T if I need to control the disambiguation process.
To also answer the question: no, that kind of precedence does not exist. The action of enable_if, though clever, is to either fail or succeed the substitution. More importantly, the substitution occurs before any potential instantiations are compared with each other. The rules for this comparison are complicated, but in your example it does come down to choosing the most specialized option, using the following ranking: Thing A is the primary (least specialized) template; Things B, C and D are equally specialized, but more specialized than A; Thing E is the most specialized. Therefore E will be selected. B, C and D must be considered because their conditions all evaluated to true, and they are equally specialized because they each have the single type parameter T. Since a valid program must have one unambiguous match for each use of a name, you will get a compiler error if you remove Thing E from the example. Now, you can disambiguate B, C and D by using enable_if with more appropriate (combinations of) conditions, and the problem of ambiguity doesn't magically vanish by using concepts. However, you can use concepts directly with template parameters like so: #include <concepts> template<typename T> class Thing {}; // Thing A template<std::integral T> class Thing<T> {}; // Thing B template<std::signed_integral T> class Thing<T> {}; // Thing C template<std::floating_point T> class Thing<T> {}; // Thing D template<> class Thing<float> {}; // Thing E int main() { Thing<float> E; Thing<double> D; Thing<int> C; Thing<bool> B; Thing<void> A; } This is just a short example, but I think concepts are such a significant improvement to generic C++ that they should be taught and learned at the same time as templates. They are now widely supported, so you can always try them out on Compiler Explorer if you happen to have an older compiler.
74,200,777
74,200,849
Why does codecvt_utf8 give hex value as ffffff appended in beginning?
for this code - int main() { std::wstring wstr = L"é"; std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv; std::stringstream ss; ss << std::hex << std::setfill('0'); for (auto c : myconv.to_bytes(wstr)) { ss << std::setw(2) << static_cast<unsigned>(c); } string ssss = ss.str(); cout << "ssss = " << ssss << endl; Why does this print ffffffc3ffffffa9 instead of c3a9? Why does it append ffffff in beginning? If you want to run it in ideone - https://ideone.com/qZtGom
c is of type char, which is signed on most systems. Converting a char to an unsigned causes value to be sign-extended. Examples: char(0x23) aka 35 --> unsigned(0x00000023) char(0x80) aka -128 --> unsigned(0xFFFFFF80) char(0xC3) aka -61 --> unsigned(0xFFFFFFc3) [edit: My first suggestion didn't work; removed] You can cast it twice: ss << std::setw(2) << static_cast<int>(static_cast<unsigned char>(c)); The first cast gives you an unsigned type with the same bit pattern, and since unsigned char is the same size as char, there is no sign extension. But if you just output static_cast<unsigned char>(c), the stream will treat it as a character, and print .. something .. depending on your locale, etc. The second cast gives you an int, which the stream will output correctly.
74,200,954
74,201,268
Can't Pass `std::array` From Within Closure
Using the following declarations: #include <array> template <typename V> void makeError(V& v) {} the following code snippet fails to compile under MSVC 16.11.13 with /std:c++17: int main() { [&]() { std::array bugs{0}; [&]() { makeError(bugs); }; }; return 0; } The error message is as follows: main.cpp(9,5): error C2955: 'std::array': use of class template requires template argument list The same code compiles perfectly fine under GCC 10.4 with --std=c++17. The real problem came up when I tried removing the inner closure: int main() { [&]() { std::array bugs{0}; makeError(bugs); }; return 0; } Or the outer closure: int main() { std::array bugs{0}; [&]() { makeError(bugs); }; return 0; } Both of these compile happily under MSVC and GCC. Is the first snippet invalid C++? If so, what part of the standard am I violating?
Looks like this is a bug in msvc's legacy lambda processor. Your code compiles if you pass /Zc:lambda: https://godbolt.org/z/91z4chhTx This seems to be the matching bug report: https://developercommunity.visualstudio.com/t/class-template-argument-deduction-fails-in-the-bod-1/414204 How I found this I would always recommend using godbolt in cases like this, since it allows you to quickly switch between compilers, versions and command line args. If something smells like a compiler bug, checking the latest versions is always a good idea. If something compiles under gcc & clang, but not msvc, it smells like a compiler bug. I tried your code in the latest msvc and since it involves lambdas and captures, I remembered that there were changes to that in c++20, so I tried compiling as such. Since that worked, I had look through cppreference to see if I could find any relevant change to the standard that might legitimately cause this. I didn't find any, but then remembered that msvc has also constantly be increasing its standards conformance over the recent years. So I used /permissive- with c++17 and once I noticed that this builds, I had a look through the conformance flags and found /Zc:lambda. This confirmed this as a fixed compiler bug to me. And fixed bugs often have bug reports, so I googled the keywords that seemed relevant to the situation: msvc nested lambdas template deduction. The bug report is the second result for me.
74,201,108
74,242,011
Implementing a container for both const and mutable types in C++
Let's say we have a class X that holds a pointer to an object of class Y. X never changes Y in any way, but other objects which might want to change Y can ask X for a pointer to Y. We want class X to be able to hold both const and variable objects. If we write something like this: class Y; class X { public: const Y* getY(); private: const Y* y; }; then we could never alter Y when getting it from X, even when the original "Y object" is not const. An example where this would be useful is a linked list that holds both const and variable objects. How would one go about implementing this?
You can think about the analogous situation of std::unique_ptr: one that holds a pointer to a mutable Y is std::unique_ptr<Y>, while one that holds a pointer to a const Y is std::unique_ptr<const Y>. X can similarly be made into a template: class Y; template <class T> class X { public: T* getY(); private: T* p; }; Here, X<Y> can hold a Y*, and X<const Y> can hold a const Y*. You may also want to make X<Y> implicitly convertible to X<const Y> by providing an appropriate constructor, so that any function that has a parameter of type X<const Y> can be called with an argument of type X<Y>: template <class T> class X { public: X(const X& other) = default; X(const X<std::remove_const_t<T>>& other) requires (!std::is_const_v<T>) : p(other.getY()) {} T* getY() const; private: T* p; }; If you want to hide the templatedness from the users, you can do so like this: namespace detail { template <class T> class X_impl { public: X_impl(const X_impl& other) = default; X_impl(const X_impl<std::remove_const_t<T>>& other) requires (!std::is_const_v<T>) : p(other.getY()) {} T* getY() const; private: T* p; }; } // namespace detail using X = X_impl<Y>; using CX = X_impl<const Y>;
74,201,479
74,201,547
How to initialize a constexpr struct containing arrays without using intermediate variables?
Is it possible to initialize a constexpr struct which contains array-like fields without defining intermediate variables. Using intermediates is the only solution I could find to workaround compilation errors due to passing temporary arrays, but that pattern seems more verbose than necessary. I'm open to using something other than std::span for the field member types to enable a cleaner pattern. #include <span> struct MyStruct { // Feel free to replace span with array, etc. std::span<const int> a; std::span<const int> b; // ... contains many array-like fields }; // Would like to avoid creating these intermediate variables constexpr std::array my_a{1,2,3}; constexpr std::array my_b{5,6}; // ... constexpr MyStruct foo{ .a = my_a, // Works, but requires annoying intermediate // .a = {1,2,3}, // Error, no matching std::span constructor // .a = {{1,2,3}}, // Error, creates non-constexpr temporary // .a = std::array{1,2,3}, // Error, creates non-constexpr temporary .b = my_b, // ... }; constexpr MyStruct bar{ // Will create different instances with a variety of field sizes //.a = {{1,2}}, //.b = {{1,2,3,4,5}}, // ... };
Put your value in a template parameter: constexpr MyStruct foo{ .a = std::integral_constant<std::array<int, 3>, std::array{1, 2, 3}>::value }; // or more tersely template<auto V> inline constexpr auto static_storage(V); constexpr MyStruct foo{ .a = static_storage<std::array{1, 2, 3}> }; And you can use a lambda for non-structural types: template<auto F> inline constexpr auto call_static(F()); constexpr MyStruct foo{ .a = call_static<[]{ return std::array{1, 2, 3}; }> .b = call_static<[]{ return std::array{5, 6}; }> }; // In a macro if you want #define STATIC_STORAGE(...) (call_static<[]() -> decltype(auto) { return (__VA_ARGS__) ; }>) Since you asked in the comments, in C++17 it is quite a bit more difficult to use arrays in template arguments. For simple types, you can use a parameter pack: template<auto First, decltype(First)... Rest> inline constexpr std::array<decltype(First), sizeof...(Rest)+1u> static_array{{First, Rest...}}; // .a = static_array<1, 2, 3> For more complicated types, you can still use a lambda but pass it in more creatively: template<typename Lambda> struct call_static_holder { static_assert(std::is_empty_v<Lambda> && std::is_trivially_copy_constructible_v<Lambda>, "Lambda must be stateless"); static constexpr Lambda lambda() { // No default constructor in C++17, copy all 0 members instead const Lambda l(l); return l; } static constexpr decltype(auto) value = lambda()(); }; template<typename Lambda> constexpr auto& call_static(Lambda) { return call_static_holder<Lambda>::value; } // .a = call_static([]{ return std::array{1, 2, 3}; })
74,201,941
74,202,004
Can I call these member functions of std::unordered_map concurrently?
I have a global std::unordered_map<int, int> m. I also have exactly one thread that is type A and multiple threads are type B running concurrently. Thread type A: call insert(), erase() to add/remove some elements (guarantee not the elements read/write in the thread type B concurrently) of m Thread type B: call operator[] of m, do something like m[key] = value. (guarantee thread type B will not modify the same element concurrently, and the key exists in m already) Is it safe to do these operations concurrently without a lock?
No. insert can rehash the array which reallocates the bucket array. If that happens right before operator[] accesses it, that's a use-after-free. This probably isn't the only reason it's unsafe, but we only have to find one, to prove that it's unsafe.
74,202,405
74,203,036
How to dynamically create and populate an array of size n?
I am trying to populate an array with varying sizes (ex: A[100], A[1000], etc) with randomly generated numbers. Within the problem statement, vectors are not allowed to solve the problem. These arrays are being generated outside of main and their size, which is given by user input, is being passed as a parameter to the function. I can not figure out how to generate these arrays without hard coding in the array sizes and setting multiple different arrays. What is the best way to generate arrays in this manner, without using vectors? int size; cout << "What is the array size? "; cin >> size; for (int i = 0; i < size + 1; i++) { srand(time(0)); A[i] = rand() % size; } Here I ask for the desired array size and run a for loop to step through the size of the array and set each element in the array with a randomly generated number. int randNumArray(n) { int A[n]; for (int i = 0; i < size+1; i++) { srand(time(0)); A[i] = rand() % size; } return A; } This is the function I also tried to implement to set the elements of an array of size n with randomly generated numbers. The parameter n was initialized in main with the users input and was then passed to this function.
Creating an array of an undefined size is incorrect because, in c++, an array is initialized in compile time. When the program compiles the user has not provided the value for n, therefore int A[n]; is incorrect. To dynamically create an array of size n you must use the new keyword. The new keyword performs a memory allocation on the heap, making arr a pointer to the allocated memory. Since objects are created at run-time, int* arr = new int[n]; allocates memory of the inputted size n and returns a pointer to the array. The populate function can then be called on the array's address. This means that the populate function does not have to return anything because it is directly modifying the array's data in the heap. It takes in the address and size of the array and modifies it directly. When you are done using the array you must free it using delete [] arr;. This will guarentee that your program will free the memory when the program terminates. void populate(int a[], int size) { srand(time(0)); for(int i = 0; i < size; i++) { a[i] = rand() % size; } } int main() { int n; cout << "Enter array size: "; cin >> n; int* arr = new int[n]; populate(arr, n); // populates array with random numbers cout << "Listing elements: " << endl; for(int i = 0; i < n; i++) { cout << arr[i] << endl; } delete [] arr; }
74,202,928
74,202,981
What does it mean to 'instantiate' a class?
I have found this code regarding 3D perlin noise: https://blog.kazade.co.uk/2014/05/a-public-domain-c11-1d2d3d-perlin-noise.html I created a noise.h file from the first chunk of code. Then I added the second chunk to my C++ project, included the noise.h header file, and added it to my project via the solution explorer. Everything is fine and I have no errors with the inserted code. The problem is that I don't really understand how to use it. He simply states: It's pretty straightforward to use, just instantiate a Perlin, or PerlinOctave instance, and call noise(x, y, z); Simples. I am not overly experienced with C++ so I don't know what he means by instantiating. But my attempts were: float n = noise(x,y,z); (Where x,y,z are my float variables). I also tried: float n = PerlinOctave::noise(x,y,z); (Where x,y,z are my float variables). Visual Studio reports an error saying: "A namespace name is not allowed" He also doesn't give any instructions on how to use the octave function, which is separate from the noise function. Does anyone have a better understanding of how to use this code?
Instantiation means creating an object. The author means you create a Perlin object as follows: uint32_t seed = 42; noise::Perlin perlin(seed); And then you can call the noise methods: for (double x = 0.0; x < 1.0; x += 0.1) { std::cout << perlin.noise(x) << "\n"; } Similarly for the PerlinOctave class. It might pay to take a step back and learn the basics of C++ if you're going to continue with the language. Otherwise, you should prepare for a whole world of pain.
74,203,154
74,203,344
How to find Maximum number and negative numbers from a .txt file and also how to output Total result to another .txt file
I want to find Maximum numbers from my "numbers.txt" file and amount of negative numbers. And i want to output the Total result to another .txt file and console and the rest to the console only. Im very new and just cant figure out how to do it. This is what i have now a "numbers.txt" file with -4 53 -5 -3 2 and #include <iostream> #include <fstream> using namespace std; int main() { int n = 0; int sum = 0, total = 0; fstream file("numbers.txt"); while (file >> n) { sum += n; total++; } int average = (float)sum / total; int AmountOfNumbersAdded = total; int Highest; int Negative; cout << "Total result: " << sum << endl; cout << "Numbers added: " << AmountOfNumbersAdded << endl; cout << "Average number: " << average << endl; cout << "Maxiumum number: " << endl; cout << "Negative numbers: " << endl; return 0; } i tried to do float Highest = INT_MIN; if (Highest < num[i]) { Highest = num[i]; but it just wouldn't work.
You don't need to store the numbers to find the maximum or the amount of negative numbers, but you need to track them inside the loop, like you're already doing with the sum and the total amount of numbers. int Highest = INT_MIN; int Negative = 0; while (file >> n) { sum += n; total += 1; if (n < 0) { Negative += 1; } if (n > Highest) { Highest = n; } } float average = (float)sum / total;
74,203,223
74,249,259
D3D12 Pipeline State Object use clarification
I'm working on my own D3D12 wrapper, and I'm in the beginning 'schema' phase. I understand the purpose of the PSO in a very simple rendering pipeline, but say I've multiple objects, meshes, models, whatever terminology works best, and I would like to use a different pixel shader for each, for clarification, I would make multiple PSOs for each of these objects correct? Sorry for the simple question, it's just a clarification I really need, thank you.
You need a distinct Pipeline State Object for every unique combination of all states: VS, PS, GS, etc. Shader Objects Blend, Depth, and Raster state Render Target format Number of render targets (MRT vs. 1) Sample count (MSAA vs. not) In practice that means at least one PSO per unique material in your entire scene.
74,203,233
74,203,302
Forward declaring a template type parameter
I see this question has been discussed in various places, e.g. here,here,here and here .But, i have still not been able to relate to the questions aforementioned. My situation: I am trying to implement a simple generic visitor pattern in C++. The hosts in this pattern are different pets, these are in a file called Pet.h. The visitors are in a separate header called Visitors.h. The concrete Pet classes accept, generic visitor classes(See Comment 0 in Pet.h), and the generic visitor classes visits the generic Pet classes. So, there is a natural cyclic dependency. Earlier, when all the code was in a single header, there were no problems. Now there is. To illustrate, here is the Pet.h class. P.S: I am using Visual Studio 2017. #pragma once #include <string> #include "Visitors.h" namespace pet { class Pet { public: virtual ~Pet() {} virtual void accept(temp_visitor::PetVisitor& v) = 0; //Comment 0 Pet accepts a gneric PetVisitor virtual std::string getAnimal() = 0; private: std::string color_; }; template <typename Derived> class Visitable : public Pet { public: using Pet::Pet; Visitable() = default; Visitable(const std::string& animal) : animal_(animal) {} void accept(temp_visitor::PetVisitor& v) override { v.visit(static_cast<Derived*>(this)); } std::string getAnimal() override { return animal_; } std::string animal_; }; class Cat : public Visitable<Cat> { using Visitable<Cat>::Visitable; }; class Dog : public Visitable<Dog> { using Visitable<Dog>::Visitable; }; } And here is the Visitors.h file. The void visit(pet::Pet* p) gives the following error "use of undefined type pet::Pet on using p->getAnimal() #include<iostream> #pragma once namespace pet { class Pet; //Comment 1. Attempted forward declaration. } namespace temp_visitor { template <typename ... Types> class Visitor; template <typename T> class Visitor<T> { public: virtual void visit(T* t) = 0; }; using PetVisitor = Visitor<pet::Pet>; class FeedingVisitor : public PetVisitor { public: void visit(pet::Pet* p) override { std::cout << "Feed veggies to the "+ p->getAnimal() << std::endl; } //Comment 2: Gives the following error "use of undefined type pet::Pet" }; } So how do i fix this problem ?
You need to move the FeedingVisitor to a new header and cpp as well. In header you will have #include "Visitors.h", forward declration for Pet and in cpp #include "Pet.h" Something like Visitors.hpp namespace pet { class Pet; //Comment 1. Attempted forward declaration. } namespace temp_visitor { template <typename ... Types> class Visitor; template <typename T> class Visitor<T> { public: virtual void visit(T* t) = 0; }; } FeedingVisitor.hpp #include "Visitors.h" namespace temp_visitor { using PetVisitor = Visitor<pet::Pet>; class FeedingVisitor : public PetVisitor { public: void visit(pet::Pet* p) override; // only declaration }; } FeedingVisitor.cpp // move the definition to cpp void temp_visitor::FeedingVisitor::visit(pet::Pet* p) { std::cout << "Feed veggies to the " + p->getAnimal() << std::endl; }
74,203,442
74,204,807
CreateProcess on top of other windows applications MFC
I'm developing the MFC Application (C++) On i want to open the Labview program inside the MFC application and run top of the other windows on the main application. So, it does not work on CreateProcess() function. #define DIR_TEMP_MONITER ".\\Application.exe" STARTUPINFO stStartup = { NULL, }; PROCESS_INFORMATION stProcess = { NULL, }; stStartup.cb = sizeof( STARTUPINFO );// The size of the structure stStartup.lpReserved = NULL; // Reserved stStartup.lpDesktop = NULL; // For NT stStartup.lpTitle = NULL; // Console app title stStartup.dwFlags = 0; // Which member is valid stStartup.cbReserved2 = 0; stStartup.lpReserved2 = NULL; ::CreateProcess(DIR_TEMP_MONITER, // The name of the executable module NULL, // Command line string NULL, // Security descriptor NULL, // Security descriptor FALSE, // Handle inheritance option NORMAL_PRIORITY_CLASS, // High priority class NULL, // New environment block NULL, // Current directory name &stStartup, // Startup information &stProcess ); // Process information I want to make this executable program run on top of the other windows. Is there any other method to do that?
I used the Labview program to Always on top the all application then it open in the windows CreateProcess function. That gives always on top of the other windows applications. thank you.
74,203,587
74,203,914
Getting an element of vector which includes enums
I get inputs from user and I put them into a vector. After that I want to get any value of vector at some index. It gives a number. How can I get the exact input value? enum Enums { I, O,T, J , L, S, Z }; int main() { unsigned int index; Piece piece; for (index=0; index < 5; index ++) { cout << "What are the " << index+1 << ". piece?\n"; cin >> piece.inputPiece; piece.pieceList.push_back(static_cast<Enums>(piece.inputPiece)); } Enums firstPiece= piece.pieceList[0]; cout <<firstPiece; } Out Value is 79;
One way to solve this is to fix the underlying type of the enum to unsigned char and also change the type of inputPiece to unsigned char as shown below: //----------vvvvvvvvvvvvv---->fixed this to unsigned char enum Enums: unsigned char { I, O,T, J , L, S, Z }; class Piece { public: //--vvvvvvvvvvvvv------------->changed this to unsigned char unsigned char inputPiece; vector<Enums> pieceList; private: }; int main() { unsigned int index; Piece piece; for (index=0; index < 5; index ++) { cout << "What are the " << index+1 << ". piece?\n"; cin >> piece.inputPiece; piece.pieceList.push_back(static_cast<Enums>(piece.inputPiece)); } Enums firstPiece= piece.pieceList[0]; cout <<firstPiece;//prints I for input I J T L S } Working demo. The output of the program for the input: I J T L S is: I
74,204,004
74,204,138
Can I compile and execute C++ project without copying any license?
Can I just download and execute a C++ project on GitHub licensed under the MIT license without copying that license somewhere? For example, download a single file, g++ it and run? What about bash scripts in this repo? There are considered source code, not binary. Can I also execute them without any attribution?
The MIT license says no The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. That categorically says all copies. It doesn't matter if you're the only person with access to a copy. But in practice? When you execute a file, your computer copies its contents (or, at least, "substantial portions" of its contents) into RAM. It doesn't copy the license file into RAM - it doesn't even know about the license file. I'd argue that if all you're doing is copying a .c file that happens to be MIT-licensed off of GitHub, and compiling and executing it to see what it does, you're fine - especially if you know you're going to delete it immediately afterwards. Where you'd get into trouble is if you set up something using that executable (or source file) sans license, and then later you forget about how that file got there and send it to someone, even privately, for example as a way to share a solution to something, or someone else comes across it by any other means (e.g. if it's on a shared server). In any case, the safest thing to do would be to just clone the Git repo and run it from there.
74,204,311
74,204,426
why is it balance 0 i dont get it
#include <iostream> static float balance = 30000.0; void deposit(float amount) { if (amount < 0.0 && amount > 100000.0 ) { printf("Error invalid amount entered "); } else { balance += amount; } } float withdrawal(float withdrawal) { if (balance == 0.0) printf("NO MONEY BROKIE"); if (withdrawal < 17000.0) { printf("Error invalid amount entered "); } if (balance <= withdrawal) { withdrawal = balance; balance = 0; } balance -= withdrawal; return withdrawal; } void Check() { printf("Your Account Balance is : %f ", &balance); } int main() { float amount; int task; printf(" 1. Check Balance \n 2. Deposit \n 3. Withdrawal"); printf(" \n\nPlease note :\nThe deposit amount must not be greater than $100,000 "); printf("\nThe withdrawal amount must not be greater than $17,000 "); printf("\n\nWhat service would you like to perform : "); scanf_s("%d", &task); if (task == 1) { Check(); } else if (task == 2) { printf("Enter the amount you would like to deposit : "); scanf_s("%f", &amount); deposit(amount); printf("Thanks for doing business you have deposited %f ", &amount ); } else if (task == 3) { printf("Enter the amount you would like to withdraw : "); scanf_s("%f", &amount); float Withdrawal = withdrawal(amount); printf("Thanks for doing business you have withdrawn : %f ", &Withdrawal); } else { printf("Invalid task number !"); } } I was expecting it to function. Why is balance 0.0000 when I run and any other errors I might have missed Im new so more details more details more details more details more details why is it asking for more detail ..................................................................................................................
You had made some syntax errors, Here is the complete working code: #include <iostream> static float balance = 30000.0; void deposit(float amount) { if (amount < 0.0 && amount > 100000.0 ) { printf("Error invalid amount entered "); } else { balance += amount; } } float withdrawal(float withdrawal) { if (balance == 0.0) printf("NO MONEY BROKIE"); if (withdrawal < 17000.0) { printf("Error invalid amount entered "); } if (balance <= withdrawal) { withdrawal = balance; balance = 0; } balance -= withdrawal; return withdrawal; } void Check() { printf("Your Account Balance is : %f ", balance); } int main() { float amount; int task; printf(" 1. Check Balance \n 2. Deposit \n 3. Withdrawal"); printf(" \n\nPlease note :\nThe deposit amount must not be greater than $100,000 "); printf("\nThe withdrawal amount must not be less than $17,000 "); printf("\n\nWhat service would you like to perform : "); scanf("%d", &task); if (task == 1) { Check(); } else if (task == 2) { printf("Enter the amount you would like to deposit : "); scanf("%f", &amount); deposit(amount); printf("Thanks for doing business you have deposited %f ", amount ); } else if (task == 3) { printf("Enter the amount you would like to withdraw : "); scanf("%f", &amount); float Withdrawal = withdrawal(amount); printf("Thanks for doing business you have withdrawn : %f ", Withdrawal); } else { printf("Invalid task number !"); } }
74,204,376
74,204,454
Why adding "variable + 1" doesn't increment its value by one for every loop in a for loop? (C++)
I'm having a hard time understanding why using a increment operator in a for loop in C++ has a different result than doing 'variable' + 1. The variable in the second case simply isn't remembered after each iteration of the loop: Take the following code: #include <iostream> int main(){ int a{0}; for (int i = 0; i < 5; i++){ std::cout << ++a; } return 0; } It outputs as expected: 12345 However, if I instead replace ++a with a + 1: #include <iostream> int main(){ int a{0}; for (int i = 0; i < 5; i++){ std::cout << a + 1; } return 0; } I get: 11111 Even if I make the 'a' variable static: static int a{0}; It still outputs 11111. Why doesn't 'a + 1' preserve its value after every loop? What would I need to do if I wanted to preserve its value after every iteration without using ++ (for instance, with another operation like a * 2)?
Why doesn't 'a + 1' preserve its value after every loop? a + 1 is an expression that doesn't assign anything to a. That is a is not affected in any way. This means when you do just a + 1, the value of a is still 0(the old value). On the other hand ++a has the same effect as: v---------->assignment done here implicitly a = a+1 In the above expression ++a, the value of is incremented by 1 so that the new value of a is now 1.
74,204,399
74,205,677
Is flattening an array of structs undefined behavior in C++?
Is flattening an array of structs that contain an array like in the example below undefined behavior according to the C++ standard, even if there is no padding in the struct S? #include <iostream> struct S { S() : v{1,2,3,4,5} {} int v[5]; }; static_assert(sizeof(S) == 5 * sizeof(int)); void print_array(int* begin, int* end) { while (begin != end) std::cout << *begin++ << " "; std::cout << "\n"; } int main(int, char**) { S s[3]; int* p = s[0].v; // treat p as a flat array of 5*3 ints - is this UB? print_array(p, p + 5*3); return 0; } It works in practice with gcc and msvc, but I wonder if it is guaranteed to work.
Short answer: this is not defined in the standard so it is UB, and you have no guarantee that it will work Long answer: The standard defines undefined behavior as (3.64 [defns.undefined]): undefined behavior behavior for which this document imposes no requirements You are there... The standard never says that a struct can be browsed as an array except as an array of characters to access its representation. Furthermore, pointer arithmetics is only defined inside an array, which can be explicitely declared or dynamically allocated (still with the exception for character pointers). So even if we all know that, as you controlled that no padding is involved, the representation of the structure will be consecutive representations of integer objects, this is not a declared array, so per standard you are not allowed to perform pointer arithmetics inside it. This is often called formal UB. All current well known implementations will correctly translate this code, and the resulting program will produce expected results. But another compiler, or a later version of a currently working compiler could perfectly decide differently...
74,204,445
74,212,125
Android NDK: CMake fails while linking static library (OpenSSL)
I'm writing a simple proof of concept app that integrates OpenSSL using NDK. Unfortunately, it gives me undefined reference errors during build. What I did: Cross-compiled OpenSSL for Android (x86_64 is shown, and similarly for other ABIs): openssl-1.1.1q $ ./Configure android-x86_64 openssl-1.1.1q $ make openssl-1.1.1q $ cp libssl.a <path_to_project_cpp_dir>/libs/x86_64/ openssl-1.1.1q $ cp -r ./include/openssl <path_to_project_cpp_dir>/libs/include/ Added the following CMakeLists.txt into project's cpp dir: cmake_minimum_required(VERSION 3.18.1) project("ndk-poc") add_library( # Sets the name of the library. ndk-poc # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). ndk-poc.cpp) find_library( # Sets the name of the path variable. log-lib # Specifies the name of the NDK library that you want CMake to locate. log) add_library(libssl STATIC IMPORTED) set_target_properties( # Specifies the target library. libssl # Specifies the parameter you want to define. PROPERTIES IMPORTED_LOCATION # Provides the path to the library you want to import. ${CMAKE_SOURCE_DIR}/libs/${ANDROID_ABI}/libssl.a ) include_directories(${CMAKE_SOURCE_DIR}/libs/include/) target_link_libraries( # Specifies the target library. ndk-poc # Links the target library to the log library # included in the NDK. libssl ${log-lib}) And this is my test ndk-poc.cpp: #include <jni.h> #include <string> #include <openssl/bn.h> #include <openssl/evp.h> #include <openssl/sha.h> extern "C" JNIEXPORT jstring JNICALL Java_com_techyourchance_android_screens_home_HomeFragment_stringFromJNI( JNIEnv* env, jobject /* this */) { /* Testing OPENSSL prime generation and BigNum. */ BIGNUM *prime1 = NULL; int bits = 16; /* Number of bits for the generated prime. */ int safe = 0; prime1 = BN_new(); if (prime1 == NULL) { printf("Out of memory.\n"); } else if (BN_generate_prime_ex(prime1, bits, safe, NULL, NULL, NULL)) { printf("Success!\n"); int len; len = BN_num_bytes(prime1); unsigned char* buffer; buffer = static_cast<unsigned char*>(malloc(len)); if (!buffer) { printf("Out of memory allocating buffer.\n"); } else { int wlen; wlen = BN_bn2bin(prime1, buffer); printf("Wrote %d bytes.\n", wlen); int i; for(i=0;i<wlen;++i) { printf("Byte %d of buffer = %d.\n", i, buffer[i]); } free(buffer); char* st; st = BN_bn2dec(prime1); printf("Prime = %s.\n", st); OPENSSL_free(st); } } else { printf("Error generating prime.\n"); } std::string result = "Test completed!"; return env->NewStringUTF(result.c_str()); } Results: I don't see any errors inside Android Studio, but when I try building the project, all usages of OpenSSL's APIs in my test code result in unresolved reference errors: ... C:/Users/Vasiliy/projects/ndk-poc/app/src/main/cpp/ndk-poc.cpp:38: error: undefined reference to 'BN_bn2dec' C:/Users/Vasiliy/projects/ndk-poc/app/src/main/cpp/ndk-poc.cpp:40: error: undefined reference to 'CRYPTO_free' clang++: error: linker command failed with exit code 1 (use -v to see invocation) ninja: build stopped: subcommand failed. What did I miss?
OpenSSL consists of (at least) two libraries: libcrypto which has the general-purpose cryptographic functions; and libssl which is a TLS implementation built on top of libcrypto. So in your case libcrypto would be the appropriate library to link against.
74,205,201
74,231,238
C++ COM (non MFC) calling method with pointer argument
I'm trying to reproduce a COM client in c++ in the non MFC way. I'm able to connect to the com interface and call some methods that require simple values as parameter, but I'm not able to call a method with a pointer as argument, the function is this: short sProdGetCurrentMachineType(short* p_psMachineType) and in the short variable pointed by p_psMachineType will be stored the result value. I tried this: DISPID dispid; //omitted for brevity, i get it from QueryInterface() on the com VARIANT pVarResult; EXCEPINFO pExcepInfo; unsigned int* puArgErr = 0; DISPPARAMS dispparams{}; VARIANTARG rgvarg[1]; short *p_psMachineType; rgvarg[0].vt = VT_I2; rgvarg[0].piVal = p_psMachineType; dispparams.rgvarg = rgvarg; dispparams.cArgs = 1; dispparams.cNamedArgs = 0; hresult = (*pDisp)->Invoke( dispid, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &dispparams, &pVarResult, &pExcepInfo, puArgErr ); but I get a TYPE_MISMATCH ERROR.. Instead I saw that using it as named argument I don't get error in the call but the pointer value is not populated, but i cannot find any example of pointers passed as named arguments. Does anybody know how to handle it?
As Simon Mourier said the correct parameter to set on the rgvarg array was VT_I2 | VT_BYREF instead of VT_I2
74,205,967
74,206,061
How to find the longest subarray such that its xor has even parity?
I've found a solution in O(n^2) complexity which is as follows: But is there any way in which I can reduce its time complexity? This is the bin function int bin(int n) { int i = 0; while (n > 0) { if (n % 2 == 1) i++; n = n / 2; } return i; } This is the code in main for (int j = 0; j < n; j++) { int ans = a[j]; for (int k = j + 1; k < n; k++) { ans = ans ^ a[k]; if (bin(ans) % 2 == 0) { if (k - j + 1 > final) { final = k - j + 1; } } } }
Note two things: Xor of two elements have even parity if and only if sum of their parities are even. Xor of n elements equals to xor of n-1 elements xored with the nth. If the sum of parities of all elements are even, then you are done. Array itself is the longest. If not, then you can go through both end of the array at the same time looking for an odd parity byte. The sub-array leaving the first such element and the rest behind it is the longest. Done. Note that there should be such element because otherwise sum will be even.
74,206,115
74,206,752
How to define a lambda function to be able to capture the 'this' pointer of a class?
I have a time class which tracks the time. I want my other classes to be able to register a callback function if the day changes. I have this working snippet: #define MAX_CB_CHANGE_FUNCTIONS 50 typedef void (*dayChangeFunc)(int prevDay,int nowDay); class TimeSystem { private: // array for the function pointers. dayChangeFunc dayChangeFunctions[MAX_CB_CHANGE_FUNCTIONS]; // emit function if the day changes. void emitDayChange(int prev, int now); public: void regDayChange(dayChangeFunc); }; /* * Registering a day change function. * Maximum function pointer count is MAX_CB_CHANGE_FUNCTIONS ( see timeSys.h ) */ void TimeSystem::regDayChange(void (*dayChangeFunc)(int prevDay,int nowDay)){ if( currDayCbIndex >= MAX_CB_CHANGE_FUNCTIONS ){ if(isDebugOn){ debug.print(DEBUG_WARN,"[Time_sys] - Can not register an other day change function.\n"); return; } } dayChangeFunctions[currDayCbIndex] = dayChangeFunc; currDayCbIndex++; } /* * Emitting day change to every registered function. */ void TimeSystem::emitDayChange(int prev, int now){ // Preventing change on initialization. if( prev == 0 ){ return; } for (size_t i = 0; i < MAX_CB_CHANGE_FUNCTIONS; i++){ if(dayChangeFunctions[i]){ dayChangeFunctions[i](prev,now); } } } This works and other calsses can use this like this: timeSys.regDayChange([](int prevDay,int nowDay){ Serial.printf("Day changed from prev: %d to now: %d\n",prevDay,nowDay); }); Now i want to capture the 'this' pointer in the lambda to be able to call some internal function of a class. timeSys.regDayChange([this](int prevDay,int nowDay){ callSomeInternalFunction(); }); Error i get: no suitable conversion function from "lambda [](int prevDay, int nowDay)->void" to "dayChangeFunc" How could i define my lambda to be able to capture the 'this' pointer? ******** EDIT: SOLVED ******** Here are the modifications: I had to define my lambda function type like this: using dayChangeFunc = std::function<void(int, int)>; Define the function pointer register function like this: void regDayChange(dayChangeFunc cb); And rewrite the declaration like this: /* * Registering a day change function. * Maximum function pointer count is MAX_CB_CHANGE_FUNCTIONS ( see timeSys.h ) */ void TimeSystem::regDayChange( dayChangeFunc cb ){ if( currDayCbIndex >= MAX_CB_CHANGE_FUNCTIONS ){ if(isDebugOn){ debug.print(DEBUG_WARN,"[Time_sys] - Can not register an other day change function.\n"); return; } } dayChangeFunctions[currDayCbIndex] = cb; currDayCbIndex++; } And now i can use it in any class like this: class SampleClass(){ private: int exampleCounter = 0; public: void init(){ TimeSystem timeSys; timeSys.regDayChange([this](int prevDay,int nowDay){ Serial.printf("Day changed from prev: %d to now: %d\n",prevDay,nowDay); exampleCounter++; }); } }
Change the callback type to std::function<void(int, int)> using dayChangeFunc = std::function<void(int, int)>; or typedef std::function<void(int, int)> dayChangeFunc; and change the function prototype, void TimeSystem::regDayChange(dayChangeFunc func). (If you had used your type alias consistently you wouldn't have needed to change the prototype, only the alias itself. Type aliases are most useful if you use them.)
74,206,119
74,206,336
Why aren't the default arguments of my template used in this case
I am leaning the topic templates in C++, it says I can also assign the datatype in the template syntax. But if I pass a different datatype in the object of class and call the method of my class it should throw an error or a garbage output, but it does not whereas it gives the correct output if I assign the datatype while declaring the object of the class and calling it. Why is so? Here is the program I was practicing on #include <iostream> using namespace std; template <class t1 = int, class t2 = int> class Abhi { public: t1 a; t2 b; Abhi(t1 x, t2 y) { a = x; b = y;**your text** } void display() { cout << "the value of a is " << a << endl; cout << "the value of b is " << b << endl; } }; int main() { Abhi A(5,'a'); A.display(); Abhi <float,int>N(5.3,8.88); N.display(); return 0; } I am facing the issue in the first object A while the second object N gives the correct output The output of the above program for the first object is the value of a is 5 the value of b is a The output of the above program for the second object is the value of a is 5.3 the value of b is 8
A char can be implicitly converted to an int. Although the type of A will be deduced by C++20 to Abhi<int,char>. That's why when you output it you get an a and not its corresponding integer representation. See CTAD for a more detailed explanation of the mechanism. More interesting is why your compiler implicitly converts double to int or float in N. This indicates that your compiler warning flags are insufficiently high or you are actively ignoring them.
74,206,509
74,206,891
Idiomatic C++11 for delegating template specialisations to a default implementation
I'm making a struct Box<T> that handles some data. The specifics are unimportant. An important note however is that Box<T> can store a pointer, but it might not. So both Box<int> and Box<int *> are valid. Obviously, if we own Box.data, we're going to need to delete data if it is a pointer type. Here's a solution I came up with that works in C++11: template <typename T> struct BoxTraits; template <typename T> struct Box { using traits_t = BoxTraits<T>; T data; ~Box() = default; // not required, I know T get_data() { return traits_t::get_data(this); } }; template <typename T> struct Box<T *> { using traits_t = BoxTraits<T *>; T *data; ~Box() { delete data; } T *get_data() { return traits_t::get_data(this); } }; template <typename T> struct BoxTraits { static T get_data(Box<T> *const box) { return box->data; } }; Box::get_data is here to illustrate an issue with this design pattern. For every single method I want to add to Box, I need to add some boiler plate in each specialisation. Note that I would also need a Box<T *const> specialisation. This seems like quite a rubbish solution. In C++14, I could use if constexpr with a is_ptr<T> trait and only have to write extra code in the methods that need specialising... Is there any way I can do this is in C++11? This solution is shorter, cleaner and works for Box<U *const>! template <typename T> struct is_ptr { static const bool value = false; }; template <typename U> struct is_ptr<U *> { static const bool value = true; }; template <typename U> struct is_ptr<U *const> { static const bool value = true; }; template <typename T> struct Box { T data; ~Box() { if constexpr (is_ptr<T>::value) { delete data; } } T get_data() { return data; } };
First off, C++11 already has std::is_pointer, no need to roll your own. You can see that it inherits from std::true_type or std::false_type instead of defining its own value member. The reason for that is tag dispatching, that can effectively replace if constexpr in this situation: template <typename T> struct Box { T data; ~Box() { destroy(std::is_pointer<T>{}); } private: void destroy(std::true_type) { delete data; } void destroy(std::false_type) {} // nothing to do }; Demo I think this is the most idiomatic way in C++11 for delegating to different implementations based on type traits. In many situations, tag dispatching can replace if constexpr (from C++17, not C++14), and I believe the latter always replaces the former in addition to being clearer. Tag dispatching can also be used before C++11 if you roll your own type traits. Last note: you don't need to use the standard type traits, you can do something like this: template <typename T> struct is_ptr { static const bool value = false; }; template <typename T> struct is_ptr<T*> { static const bool value = true; }; template <typename T> struct is_ptr<T* const> { static const bool value = true; }; template <typename T> struct is_ptr<T* volatile> { static const bool value = true; }; template <typename T> struct is_ptr<T* const volatile> { static const bool value = true; }; template<bool b> struct bool_constant {}; template<typename T> struct Box { T data; ~Box() { destroy(bool_constant<is_ptr<T>::value>{}); } private: void destroy(bool_constant<true>) { delete data; } void destroy(bool_constant<false>) {} // nothing to do }; Demo However, this pretty much amounts to recreating the standard type traits, but probably worse. Just use the standard library when possible.
74,207,011
74,207,171
is casting float to unsigned char a valid conversion?
Can someone please explain how float to uint32_t casting works? Is it a valid conversion? The output of the first line in the below code make sense to me, but the rest are I can't figure out myself. cout<<uint8_t(256+33)<<'\n'; cout<<uint8_t(float(256+33))<<'\n'; cout<<int(uint8_t(float(256+33)))<<'\n'; cout<<int(uint8_t(float(256+3)))<<'\n'; cout<<int(uint8_t(float(256+20)))<<'\n'; output ! � 255 255 255 uint8_t(256+33) is int to unsigned char, and it gives !, which is what I expect. However, float to uint8_t does not work at all. And when I try to cast the output to int, it gives me constant number 255. I've a vector<float> and want to convert it into vector<uint8_t>, which will to passed into a function. What it a valid way to convert float to uint8_t? Will static_cast<uint8_t> will work? Should I first convert float to int and then int to uint8_t?
They are not valid, but are undefined. In C++17: 4.10 Floating-integral conversions [conv.fpint] A prvalue of a floating-point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type. The int conversion is well-defined, which you can't assume just because the result makes sense to you: 4.8 Integral conversions [conv.integral], item 2 If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type).
74,207,064
74,207,129
Why does my code result in a blackscreen?
i"am learning c++ and decided to make a simple calculator and when i compiled the project and ran it all it showed is a black screen. Btw im running MS VSCode 2022. Thanks in advance for help! :) ` #include <iostream> using namespace std; int main() { int konec = 0; double cislox = 0; double cisloy = 0; int operace = 0; double vysledek1 = 0; double vysledek2 = 0; double vysledek3 = 0; double vysledek4 = 0; while (konec == 0); { cout << "Vítejte v kalkulačce Ver. 0.1" << endl; cout << "stiskněte 1 pro sčítání, 2 pro odčítání, 3 pro násobení, 4 pro dělení" << endl; cin >> operace; switch (operace) { case 1: cout << "Zadejte číslo X" << endl; cin >> cislox; cout << "Zadejte číslo Y" << endl; cin >> cisloy; vysledek1 = cislox + cisloy; cout << cislox << "+" << cisloy << "=" << vysledek1; break; case 2: cout << "Zadejte číslo X" << endl; cin >> cislox; cout << "Zadejte číslo Y" << endl; cin >> cisloy; vysledek2 = cislox - cisloy; cout << cislox << "-" << cisloy << "=" << vysledek2; break; case 3: cout << "Zadejte číslo X" << endl; cin >> cislox; cout << "Zadejte číslo Y" << endl; cin >> cisloy; vysledek3 = cislox * cisloy; cout << cislox << "*" << cisloy << "=" << vysledek3; break; case 4: cout << "Zadejte číslo X" << endl; cin >> cislox; cout << "Zadejte číslo Y" << endl; cin >> cisloy; vysledek2 = cislox / cisloy; cout << cislox << "/" << cisloy << "=" << vysledek4; break; } cout << "chcete ukoncit program?" << "1 = ANO; 0 = NE" << endl; cin >> konec; } return 0; } ` Well, i tried cheking all the code, but there should be no mistakes. Maybe im compiling it wrong? (im a MS VSCode user only for a while)
There is a typo in the while loop: while (konec == 0); { The ; on there makes it an infinite while loop that does not execute any code, since it's empty. The correct way should be: while (konec == 0) {
74,207,266
74,207,323
c++ std::set compare function when object is member of the set
I have a set composed of objects; in order to work the operator< must be defined for ordering the objects inside the set. If I define the operator< as a friend function, it works; if I define the operator< as a member function I get the error: Error C2678 binary '<': no operator found which takes a left-hand >operand of type 'const _Ty' (or there is no acceptable conversion). I do not understand why the version of operator< implemented as member function does not work/what should be changed about it. I provide bellow a simplified example of the problem case: class TestObj { private: int m_a; public: TestObj(int a): m_a{a} {} /* operator < as friend function works */ /*friend bool operator< (const TestObj& t1, const TestObj& t2) { return t1.m_a < t2.m_a; }*/ /* operator < as member function does not work! */ bool operator< (const TestObj& t2) { return m_a < t2.m_a; } }; void testSetCompare() { std::set<TestObj> set1; set1.insert(10); set1.insert(20); } I do not understand why the version of operator< implemented as member function does not work/what should be changed about it.
You need to make the member function const. Because you declared it as 'non-const' the compiler cannot decide if yout operator willl change *this so your operator cannot be used in a when you have a const TEstObj& what is needed for insert bool operator< (const TestObj& t2) const { return m_a < t2.m_a; } will do the job. Edit: The "No acceptable converson" means that it cannot convert from const TestObj& to TestObj& because it would break the rules of const. (and your operator needs a TestObj&)
74,207,355
74,207,688
Several dependent init-statements within one if condition
I need to place two dependent init statements within one if condition. As a raw example: if (bool x = false; bool y = true) std::cout << "Check!\n"; The whole expression evaluates to true, and that is the problem. Suppose I want to test a pointer in the first statement and dereference this pointer to test something else in the second statement: if (auto ptr = ptr_to_check; auto sth_else = ptr_to_check->sth_else()) { /* do something */ } And this one is going to crash as I can still dereference nullptr. I want to avoid nested if's as in my program there are other statements nested within this one. Can I place these two statements within one condition somehow?
When it comes to several statements within one if, only the last statement is evaluated as a condition. In this case, a ternary operator is a solution: if (bool x = false; bool y = x ? true : false) std::cout << "Check!\n"; So, in case of pointers: if (auto ptr = ptr_to_check; auto sth_else = ptr_to_check ? ptr_to_check->sth_else() : sth_evaluating_to_false) { /* do something */ }
74,207,456
74,207,564
Why can't I reassign the value of a pointer?
I am using a library for GUI (Qtitan for Qt). There I have a class called NavigationViewHeader whose pointer I can access by navigationView->header(). Now I want to reassign the content of the pointer, but it tells me (translated) The function "NavigationViewHeader::operator=(const NavigationViewHeader &)" (implicit declared)" cannot be referenced (it is a deleted function). NavigationViewHeader newHeader(navigationView); NavigationViewHeader* oldHeader = navigationView->header(); *oldHeader = newHeader; Is it possible to reassign the value or does the framework maybe restrict this by themself? There Is no = delete function inside the framework-class.
The error message is a bit confusingly worded. NavigationViewHeader doesn't declare a copy assignment operator, which is why the compiler implicitly declares one. However, one of its base classes has a deleted assignment operator, so this fails. I assume NavigationViewHeader inherits from QObject since you mentioned it being a Qt GUI. Those cannot be copy-assigned. See here in the documentation. QObject has neither a copy constructor nor an assignment operator. This is by design. Actually, they are declared, but in a private section with the macro Q_DISABLE_COPY(). In fact, all Qt classes derived from QObject (direct or indirect) use this macro to declare their copy constructor and assignment operator to be private. The reasoning is found in the discussion on Identity vs Value on the Qt Object Model page. Side note: I think this part of the documentation is a bit outdated. Privating operators was a C++03 technique. They likely changed that macro to delete the method instead.
74,207,537
74,208,603
type checking constexpr function to check non-template type or template type on C++17
I wrote type checking constexpr function. It the type is type1 or type2 then returns true, otherwise returns false. Here is the code. It works as I expected. #include <type_traits> struct type1{}; struct type2{}; struct type3{}; template <typename T> constexpr bool is_type1or2() { return std::is_same_v<T, type1> || std::is_same_v<T, type2>; } static_assert(is_type1or2<type1>()); static_assert(is_type1or2<type2>()); static_assert(!is_type1or2<type3>()); int main(){} https://godbolt.org/z/dncKo1Pbb Now, type1 is changed to template that has non-type parameter. How to do the same type checking? #include <type_traits> template <std::size_t N> struct type1{}; struct type2{}; struct type3{}; template <typename T> constexpr bool is_type1or2() { return std::is_same_v<T, type2>; } template <typename T, std::size_t N> constexpr bool is_type1or2() { return std::is_same_v<T, type1<N>>; } // I want to write as follows but I couldn't find a way, so far. // static_assert(is_type1or2<type1<42>>()); // so I pass explicit second template argument 42. static_assert(is_type1or2<type1<42>, 42>()); static_assert(is_type1or2<type2>()); static_assert(!is_type1or2<type3>()); int main(){} https://godbolt.org/z/G1o5447z8 I tried but I can't eliminate the second template argument. It avoids generic code. Is there any good way to check the type is type1<anyN> or type2 ? In my actual case, I have 20 of non template types like type2 and 20 of template types like type1. And half of them need to match. I want to avoid code repeatation as long as I can. Clarify requirement For template type type1<N>, N is not important. Both template is type1 is important. So the result of is_type1or2<type1<10>>() and is_type1or2<type1<20>>() are always same. I don't need to define individual template argument specialization based matching.
This can be solved easily if you change the syntax of the static_assert to accept the type as a function argument, as this will allow function template argument deduction (see Takatoshi Kondo's answer). However, this can also be solved by writing a template that checks whether a type is an instantiation of a template: template<template <std::size_t> typename, typename> struct is_instance_of : std::false_type {}; template<template <std::size_t> typename T, std::size_t N> struct is_instance_of<T, T<N>> : std::true_type {}; Now is_instance_of can be used in the function (without argument deduction) as: template <typename T> constexpr bool is_type1or2() { return is_instance_of<type1, T>::value // repeat for other templates that take a size_t parameter or std::is_same_v<T, type2>; // repeat for non-template types } If you have other template types that you want to allow (i.e. templates that take parameters other than a size_t), you can edit is_instance_of as needed. Here's a demo.
74,207,607
74,207,903
type conversion from int to class behaving weirdly
So. I am trying to convert a uint16_t (16 byte int) to class. To get the class member varaible. But it is not working as expected. class test{ public: uint8_t m_pcp : 3; // Defining max size as 3 bytes bool m_dei : 1; uint16_t m_vid : 12; // Defining max size as 12 bytes public: test(uint16_t vid, uint8_t pcp=0, bool dei=0) { m_vid = vid; m_pcp = pcp; m_dei = dei; } }; int main() { uint16_t tci = 65535; test t = (test)tci; cout<<"pcp: "<<t.m_pcp<<" dei: "<<t.m_dei<<" vid "<<t.m_vid<<"\n"; return 0; } Expected output: pcp:1 dei: 1 vid 4095 The actual output: pcp: dei: 0 vid 4095 Also, cout<<sizeof(t) returns 2. shouldn't it be 4? Am I doing something wrong?
test t = (test)tci; This line does not perform the cast you expect (which would be a reinterpret_cast, but it would not compile). It simply calls your constructor with the default values. So m_vid is assigned 65535 truncated to 12 bits, and m_pcp and m_dei are assigned 0. Try removing the constructor to see that it does not compile. The only way I know to do what you want is to write a correct constructor, like so: test(uint16_t i) { m_vid = i & 0x0fff; i >>= 12; m_dei = i & 0x1; i >>= 1; m_pcp = i & 0x7; } Demo Also I'm not sure why you would expect m_pcp to be 1, since the 3 highest bits of 65535 make 7. Also, cout<<sizeof(t) returns 2. shouldn't it be 4? No, 3+1+12=16 bits make 2 bytes.
74,208,129
74,208,202
push_back an element into a vector of an another structure vector's back()
struct Thing { int id; std::vector<int> v2; }; std::vector<Thing> v1; int main() { int n; cin>>n; for(int i=0;i<n;i++) { Thing pic; cin>>pic.id; v1.push_back(pic); int x; cin>>x; v1.back().v2.push_back(x); } } v1 is not an empty vector. I can't understand the line v1.back().v2.push_back(x); what's the actual meaning of this line
v1.back() is the last element of v1 with the type of Thing v1.back().v2 is the v2 member of that element with the type of vector<int> So you are calling the push_back() on a vector<int> with an int what is fine Note that if v1 is empty then v1.back() is UB Edit: v1.back().v2.push_back(x); is kind of like { Thing& t=v1.back(); vector<int>& v=t.v2; v.push_back(x); }
74,208,585
74,209,101
What is the difference between using the '*' operator vs the '%' operator when using the rand() function in C++?
Below I am going to show two different versions of rand() implementations. First, the modulo operator (%): int r = rand() % 10; Now, I know that this statement produces a random integer between 0-9. Second, the multiplication operator(*): double r = rand() * 101.0 / 100.0; This is the one I am confused about. I have seen this implementation once before but I cannot find a good explanation of what the 'rules' are here. What are the bounds/restrictions? What is the purpose of the division instead of just typing: double r = rand() * 1.0;
There is no different implementations for rand() function. The difference in these two cases is the mathematical operation you do with the value returned by rand() function. In the first case you just take the number returned by rand() and divide it to 10 using modulo operator (so getting a number between 0 to 9). And in the second case you just multiplying it by 101 (or 1). For example rand() has returned number 123. case first: 123 % 10 gives you 3 (the reminder of the normal division). case second: you just multiply 123 by 101 which is 12423. Checkout this.
74,208,798
74,209,282
Setting priority on std::async thread
When using std::async, what is the best way to set priority? I realize this is platform dependent, but with a posix compliant operating system, would this work? // Launch task with priority 8 auto future = std::async(std::launch::async, // async policy required [] () { pthread_setschedprio(pthread_self(), 8); // do work }); I've found answers about std::thread, but not for std::async. Edit. In my case I am on a QNX operating system. So I believe setting the priority like I've done above is valid. However, it does seem like there are valid concerns raised about whether or not the priority will persist after the async task is complete (depending how async is implemented). Edit2 Potential options seem to be... Leverage std::thread (perhaps with a thread pool) to keep explicitly managed threads at a given priority Justify in my situation that setting the priority is not necessary. Create an RAII class to change priority back to the original at the end of the async launched lambda.
I suspect your design is a bad idea. std::async is required to behave as-if it was a new std::thread. But it doesn't have to be on a new pthread. The implementation is free to (and probably should) have a set of underlying threads that it recycles for std::async -- just clean up thread_local storage and handle stuff like set_value_at_thread_exit it would work (under the standard). Accessing the underlying pthread and messing with its priority, in that case, might impact later async tasks. I cannot state certainly this would happen, but I found on at least one system that there is an underlying thread pool -- the symptom was that after a certain number of std::asyncs new ones waited to be scheduled for old ones to finish. On a low-core system, this caused a deadlock in some insufficiently paranoid code (the dependency chain of waiting for other threads got larger than the thread pool size, so the last task wasn't scheduled). That deadlock shouldn't happen under the standard; but it is evidence that platforms do use thread pools for async. Consider making your own thread pool on top of std::thread, and implementing something async-like on top of it with a priority. If you are keeping std::threads around and managing the priority yourself that is less likely to cause problems. For std::thread, you can get its native_handle, which on your system is probably a pthread handle.
74,208,893
74,209,825
translating pixel unpacking to halide algorithm
I have a buffer filled with pixel data in pattern UY1VY2... and I want to unpack that to another buffer in pattern Y1UVY2UV... So basically if I had a vector of that data I want following operation for(x=0; x<sizeof(in_buffer); x+=4) out_buffer.push_back(in_buffer[x+1]+ in_buffer[x+0] + in_buffer [x+2: x+4]) ---> [Y1,U,V,Y2,U,V] Can this kind of operation be implemented with halide? Thanks!
Sure, something like this ought to work: out_buffer(c, x) = in_buffer(mux(c, {1, 0, c}), x); Then in the schedule, you'd use set_bounds and unroll to make sure the c loop didn't actually have to check the value of c. See this tutorial for more details: https://halide-lang.org/tutorials/tutorial_lesson_16_rgb_generate.html
74,209,381
74,289,127
Global initialized variable in a DLL
Is it possible to use a global variable from one DLL module to initialize global variable in other DLL module? If so, how? I am using Microsoft Visual Studio 17.3.6 and use a C++/CLI wrapper class with some C files. I am in a bigger project but I have put together a smaller example that exhibits the behavior. I would have thought that it would work like this. There are four files, file1.c, file1.h in one project and file2.c and file2.h in second project. They are built to two DLLs, file1.dll and file2.dll. First project has file1_EXPORTS preprocessor symbol defined and second has file2_EXPORTS defined. Include guards omitted for clarity. file1.c: #include <file1.h> #include <file2.h> structure1_t struct1 = { &struct2 }; file1.h: typedef struct { structure2_t* ptr; } structure1_t; #ifdef file1_EXPORTS #define EXPORT_SYMBOL __declspec(dllexport) #else #define EXPORT_SYMBOL __declspec(dllimport) #endif EXPORT_SYMBOL structure1_t struct1; file2.h: typedef struct { int* i; } structure2_t; #if defined (file2_EXPORTS) #define EXPORT_SYMBOL __declspec(dllexport) #else #define EXPORT_SYMBOL __declspec(dllimport) #endif EXPORT_SYMBOL structure2_t struct2; file2.c: #include <file2.h> #include <file1.h> int i; structure2_t struct2 = { &i }; However, it cannot be compiled like this. There is an error C2099: initializer is not a constant. When I change the line (in file2.h) #define EXPORT_SYMBOL __declspec(dllimport) to #define EXPORT_SYMBOL extern, there are linker errors LNK2001: unresolved external symbol struct2 and LNK1120: 1 unresolved externals. Only combination that works for me is leaving the definition empty, e.g. #define EXPORT_SYMBOL. Other change that I must do is leave the definition in file1.h or the program fails in the next step. Now those are built correctly and libraries file1.dll and file2.dll are created. Assume that there is a third file file3.cpp which uses the DLLs: #include <file1.h> #include <file2.h> #include <iostream> int main(void) { std::cout << struct1.ptr << std::endl; std::cout << struct2.i << std::endl; return 0; } it prints: 0000000000000000 0000000000000000 So, my question is, is there some way this could work without the NULL pointers (e.g. struct1 has pointer to struct2 and struct2 has pointer to the integer)? Why is the program behaving like this, is it because file3.cpp sees only the declarations in the header and the variables are never initialized correctly? Other variant and solution would perhaps be to have an initialization function that puts the needed values to the structures. However, I am hesitant to doing this as I have a lot of structures that I would have to manually fill in. Or perhaps it could be filled in the DllMain as per here. Furthermore, I should mention that the C files have the extern "C" blocks in them. I tried different combinations of __declspec(dllimport), __declspec(dllexport) and extern keywords but I cannot manage to make it work correctly. Also, putting EXPORT_SYMBOL to the C files as per Exporting global variables from DLL did not help either. This answer would suggest that what I want to do is not possible but I do not know if it is relevant only to const variables or not.
What I was trying to do is not possible. Address of dllimported symbol cannot be used in an initializer of static data. I solved it by including the .c files with the structures' definition in each module that needed them. Structures themselves may stay extern when it is implemented this way. So with regards to my code examples, it would look like this: file1.c: #include <file1.h> #include <file2.h> #include <file2.c> structure1_t struct1 = { &struct2 }; file1.h: typedef struct { structure2_t* ptr; } structure1_t; extern structure1_t struct1; file2.h: typedef struct { int* i; } structure2_t; extern structure2_t struct2; file2.c: #include <file2.h> int i; structure2_t struct2 = { &i }; (for illustration, have not tested it). This way, effectively no data are shared across DLLs as each one has its own copy. If data had to stay in the separate DLLs or if including the .c files was not possible, other solution would be not to have an initializer at all, use __declspec() instead of extern and initialize structures in a function call. However, I chose not to do that as I have hundreds of structures and it would not be feasible this way.
74,209,430
74,210,218
C++: is it possible to use "universal" pointer to vector?
Good day, SO community! I am new to C++ and I've ran into a situation in my project, where I have 2 vectors of similar paired data types: std::vector<std::pair<int, std::string> firstDataVector std::vector<std::pair<int, std::string> secondDataVector and in one part of the code I need to select and process the vector depending on the external string value. So my question is - is it possible to create a pointer to vector outside of the conditions if (stringValue.find("firstStringCondition")) { //use firstDataVector } if (stringValue.find("secondStringCondition")) { //use secondDataVector } some kind of pDataVector pointer, to which could be assigned the existing vectors (because now project has only two of them, but the vectors count might be increased) I've tried to createstd::vector<std::string> &pDataVector pointer, but it will not work because reference variable must be initialized. So summarizing the question - is it possible to have universal pointer to vector?
You are trying to create a reference to one of the vectors - and that's certainly possible, but it must be initialized to reference it. You can't defer it. It's unclear what you want to happen if no match is found in stringValue so I've chosen to throw an exception. now project has only two of them, but the vectors count might be increased Create a vector with a mapping between strings that you would like to try to find in stringValue and then the vector you'd like to create a reference to. When initializing pDataVector, you can call a functor, like a lambda, that returns the reference. In the functor, loop over the vector holding the strings you'd like to try to find, and return the referenced vector on the first match you get. It could look like this: #include <functional> #include <iostream> #include <string> #include <vector> int main() { using vpstype = std::vector<std::pair<int, std::string>>; vpstype firstDataVector{{1, "Hello"}}; vpstype secondDataVector{{2, "World"}}; // A vector of the condition strings you want to check keeping the order // in which you want to check them. std::vector<std::pair<std::string, std::reference_wrapper<vpstype>>> conditions{ {"firstStringCondition", firstDataVector}, {"secondStringCondition", secondDataVector}, // add more mappings here }; // an example stringValue std::string stringValue = "ssdfdfsdfsecondStringConditionsdfsfsdf"; // initialize the vpstype reference: auto& pDataVector = [&]() -> vpstype& { // loop over all the strings and referenced vpstypes: for (auto& [cond, vps] : conditions) { if (stringValue.find(cond) != std::string::npos) return vps; } throw std::runtime_error("stringValue doesn't match any condition string"); }(); // and use the result: for (auto [i, s] : pDataVector) { std::cout << i << ' ' << s << '\n'; // prints "2 world" } }
74,209,432
74,310,525
Incredibuild: Compiler failed to generate PCH file
Some members of my team, as well as our build server, are getting a compiler error and failed build when using Incredibuild to build our largest Visual Studio solution. We get the following (sanitized) error: Target ClCompile: stdafx.cpp IncrediBuild: Error compiling stdafx.obj: Compiler failed to generate PCH file (no errors reported) Build FAILED. Building the affected projects individually first before building the entire solution seems to resolve the issue, but that only works for the developers, it does nothing to solve the issue on the build server. At first, we thought it was an issue with the build order, but that no longer seems to be the case; in one instance we're seeing this with a project that has no other dependencies within the solution, and the other projects that depend on this project have that dependency correctly configured. One of the reasons we thought it might be a build order issue is that it seems to somewhat random, and experience has shown us that poorly defined build dependencies can lead to this type of random build failure. Another reason to think it's not a build order issue is that we haven't made any changes to project files, property files, or the solution files since this started. We did have a fairly significant set of updates applied recently, but that was after the first recorded instance of this issue. What is the root cause of this issue, and how do we go about preventing it?
Apparently it is caused by some recent Windows Updates. There is a support bulletin about it on Incredibuild's support page with links to download an "emergency patch version" (9.6.10) that fixes the issue: https://incredibuild.force.com/s/. I experienced the same problem - the build would succeed on some computers but fail with the "failed to generated PCH file" error on others. Installing this updated version seems to have fixed the issue.
74,210,086
74,210,251
Qt Creator fails to start (Qt platform plugin problem), fresh install for C++ development
I recently installed Qt, actually I am developing a C++ project which was written to comply with Qt 5.15.2, so I downloaded that one, and installed Creator 8.0.1 (Enterprise) too. Creator does not start, but it welcomes me with this message: The application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem. Available platform plugins are: direct2d, minimal, offscreen, windows. I already tried with reinstalling related Qt components, it does not help. Also, I installed Qt Creator 9.0.0-beta1, but that gives the exact same error message. I tried to google the error message to get an answer, but eveywhere (e.g. https://ugetfix.com/ask/how-to-fix-application-failed-to-start-because-no-qt-platform-plugin-could-be-initialized-error-in-windows/) they say I should search for some kind of "pyqt5_tools" folder, and copy the contents of a subdirectory inside Python install directory on my computer into a subdirectory in that folder... but I do not have Python on my computer, and it has nothing to do my project or anything. The project I am working on is in C++, and I would only like to use the Qt Creator application for that. Should I download Python or something for this? How exactly is Python related to Qt Creator at all? (Anyway, Qt itself works fine, I can develop my code using VSCode and Qt libraries, build and debug them, but I would like to use Creator as an IDE because for certain things it is easier for a Qt app development.) My machine is nice and new, just freshly reinstalled it a few months ago, 480GB SSD as main drive, 8GB RAM, Intel i7-2820QM CPU. I am using Windows 8.1 Pro with all latest updates. I appreciate any help. Thanks in advance!
QtCreator 8.0.1 does not support Windows 8.1 (because it is developed in Qt 6, which supports only Windows 10 and newer, see https://doc.qt.io/qt-6/supported-platforms.html). You will probably need to download and install older versions of QtCreator. You can find some of them here https://download.qt.io/archive/qtcreator/ Alternatively you should upgrade to Windows 10, which is definitely a more future-proof solution for you...
74,210,274
74,210,562
How to substitute a function argument with a string in c++?
I'm new to c++, and am trying to make a fullscreen setting in SFML. But nothing I tried works. Working code: sf::RenderWindow window(sf::VideoMode(1920, 1080, 32), "title", sf::Style::Fullscreen); Code that would look like what I am looking for (but doesn't work): string str1 = "sf::Style::Fullscreen"; sf::RenderWindow window(sf::VideoMode(1920, 1080, 32), "title", str1);
The 3rd parameter of sf::RenderWindow is a Uint32 (at least that's what the documentation says), but you are trying to pass a string which is rather pointless. You probably want something like this: Uint32 mystyle = sf::Style::Fullscreen; sf::RenderWindow window(sf::VideoMode(1920, 1080, 32), "title", mystyle); or better: auto mystyle = sf::Style::Fullscreen; sf::RenderWindow window(sf::VideoMode(1920, 1080, 32), "title", mystyle);
74,210,881
74,211,363
C++, question about references and pointers and about their functioning in function
everybody! Really, I just want to understand what is going on with this references and pointers. Can you explain me, why in one case all is workking fine, but in another I receive nothing I will start with working case. So, there is a program (this is not mine): #include <iostream> #include <conio.h> using namespace std; struct node{ double data; node *left; node *right; }; node *tree = NULL; void push(int a, node **t) { if ((*t) == NULL) { (*t) = new node; (*t)->data = a; (*t)->left = (*t)->right = NULL; return; } if (a > (*t)->data) push(a, &(*t)->right); else push(a, &(*t)->left); } void print (node *t, int u) { if (t == NULL) return; else { print(t->left, ++u); for (int i=0; i<u; ++i) cout << "|"; cout << t->data << endl; u--; } print(t->right, ++u); } int main () { int n; int s; cout << "Enter the amount of elements "; cin >> n; for (int i=0; i<n; ++i) { cout << "Enter the value "; cin >> s; push(s, &tree); } cout << "Your binary tree\n"; print(tree, 0); cin.ignore().get(); } This is binary search tree made with struct, pointers and references. And it is work exactly fine But if i modify program in the way below it doesn't work. And i don't understand why, because int *tree; int **treePointer; cout << (tree = *treePointer) <<endl; // Shows 1 i.e. true Modified code: #include <iostream> #include <conio.h> using namespace std; struct node{ double data; node *left; node *right; }; node *tree = NULL; void push(int a, node *t) { if ((t) == NULL) { (t) = new node; (t)->data = a; (t)->left = (t)->right = NULL; return; } if (a > (t)->data) push(a, (t)->right); else push(a, (t)->left); } void print (node *t, int u) { if (t == NULL) return; else { print(t->left, ++u); for (int i=0; i<u; ++i) cout << "|"; cout << t->data << endl; u--; } print(t->right, ++u); } int main () { int n; int s; cout << "Enter the amount of elements "; cin >> n; for (int i=0; i<n; ++i) { cout << "Enter the value "; cin >> s; push(s, tree); } cout << "Your binary tree\n"; print(tree, 0); cin.ignore().get(); } As you see, all changes happen in push function argument. Why it is not working? I am expecting that original program and modified will work the same
This happens because of the following line in the modified code (t) = new node; You are assigning memory to your pointer which is being created in a function call, a memory that will be lost after the function call. Note that if you make changes to a member of a struct in a function call, the change will be reflected throughout because in that case, you will handle the member of the struct by reference. But pointing the pointer to a new memory location created inside a function call will not propagate the changes. You need to pass the pointer by reference as well (thus pointer to a pointer). Consider the following example - #include <iostream> typedef struct exampleStruct { int a; } exampleStruct; void changeStruct(exampleStruct* S, int changedValue) { S = new exampleStruct; S->a = changedValue; printf("Value of a inside Function = %d\n", S->a); } void changeStruct(exampleStruct** S, int changedValue) { (*S) = new exampleStruct; (*S)->a = changedValue; } int main() { exampleStruct* S = new exampleStruct; S->a = 100; printf("Value of a before calling function = %d\n", S->a); changeStruct(S, 900); printf("Value of a after calling the function = %d\n", S->a); changeStruct(&S, 1300); printf("Value of a after calling 2nd function = %d\n", S->a); } The output is as follows - Value of a before calling function = 100 Value of a inside Function = 900 Value of a after calling the function = 100 Value of a after calling 2nd function = 1300 In the above example, similar to the modified code, the first function fails to propagate the changes, whereas the using pointer to the pointer does the trick
74,211,320
74,281,456
WebRTC: Track.onOpen() is called, but track is not open
Using libdatachannel, I establish a PeerConnection between two partners using some out-of-band signaling. I can create DataChannels and send data between them successfully (with peer_connection->createDataChannel()). But I am struggling to do the same with a video track. Here is what I do: I create a track from one partner: rtc::Description::Video media("myvideo", rtc::Description::Direction::RecvOnly); media.addH264Codec(96); media.setBitrate(3000); auto track = peer_connection->addTrack(media); peer_connection->setLocalDescription(); Note how I call setLocalDescription() after addTrack, so that libdatachannel will negotiate the track and I don't need to send an SDP out of band (at least that's my understanding). From the other partner, I check the onTrack() callback: peer_connection->onTrack([this](const std::shared_ptr<rtc::Track>& track) { track->onClosed([]() { std::cout << "onClosed" << std::endl; }); track->onOpen([]() { std::cout << "onOpen" << std::endl; if (track->isOpen()) { std::cout << "track is open" << std::endl; } else { std::cout << "track is not open" << std::endl; } }); } What I observe is that onTrack is called, and the track has the mid I set from the sending side ("myvideo"). But right in the onOpen() callback, the call to track->isOpen() says that "track is not open". If I try to use the track later (with e.g. track->send()), if fails with a SIGABRT: terminate called after throwing an instance of 'std::runtime_error' what(): Track is closed Signal: SIGABRT (Aborted) So somehow it feels like my track was never properly open in the first place. Though I would expect track->onOpen() to be called... when the track is open. Am I missing something?
That was a bug in libdatachannel.
74,211,453
74,225,020
External openMP build does not set threads equal to OMP_NUM_THREADS
I want to use an external build for OpenMP (not the one that comes natively with the compiler). For the external build am cloning https://github.com/llvm-mirror/openmp.git and then cmake with the following options: cmake \ -DCMAKE_BUILD_TYPE=Debug \ -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \ -DCMAKE_CXX_FLAGS="-std=c++17" \ -DCMAKE_CXX_COMPILER=clang++ \ -DCMAKE_C_COMPILER=clang \ -S ${OMP_DIR} -B ${OMP_DIR}/cmake-build/Debug After that I cmake --build and cmake --install. For my application build and application linking to OpenMP I use the following CMakeLists.txt: cmake_minimum_required(VERSION 3.18) project(foo C CXX) find_package(OpenMP) add_executable(hello_world hello.cpp) target_link_libraries(hello_world <path_to_external_openmp>/cmake-install/Debug/lib/libomp.so) The source file is just a dummy: #pragma omp parallel { std::cout << "Hello World, from thread: " << omp_get_thread_num() << std::endl; } Finally, when I execute OMP_NUM_THREADS=4 ./hello_world I get the following result which is clearly not the one expected: Hello World, from thread: 0 Also, note that ldd ./hello_world gives: linux-vdso.so.1 (0x00007fffd311b000) libomp.so => <path_to_external_openmp>/cmake-install/Debug/lib/libomp.so (0x00007fcbcbca0000) libstdc++.so.6 => /lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007fcbcba70000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fcbcb840000) /lib64/ld-linux-x86-64.so.2 (0x00007fcbcbde4000) libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fcbcb750000) libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fcbcb730000) Any ideas on what could be the reason for this unexpected behavior?
You need the -fopenmp flag; either add set(CMAKE_CXX_FLAGS "-fopenmp") to the CMakeLists.txt file or -DCMAKE_CXX_FLAGS="-fopenmp" to the cmake command. As a side note, you can also remove the find_package(OpenMP) since you are explicitly linking against the library with the absolute path.
74,211,567
74,213,705
How to access BPF map from userspace that was created in kernel space
I am a complete novice at anything ebpf but trying out some random ideas to get some knowledge. I wanted to have an eBPF module that could filter some packets based on an allowed list of CIDR. A userspace application should be able to update the allowed list so that filtering can happen without reloading the eBPF probe. I started with some very simple kernel code: // IPv4 addr/mask to store in the trie struct ip4_trie_key { __u32 prefixlen; struct in_addr addr; }; struct { __uint(type, BPF_MAP_TYPE_LPM_TRIE); __uint(max_entries, 128); __type(key, struct ip4_trie_key); __type(value, char); __uint(map_flags, BPF_F_NO_PREALLOC); } allowlist SEC(".maps"); SEC("socket") int test_ip_filter(struct __sk_buff *skb) { // get header struct iphdr iph; if (0 != bpf_skb_load_bytes(skb, 0, &iph, sizeof(iph))) { return BPF_DROP; } // Form the key to lookup in the allowlist struct ip4_trie_key key = { .prefixlen = 32, .addr = iph.saddr }; if (bpf_map_lookup_elem(&allowlist, &key)) { return BPF_OK; } return BPF_DROP; I load the module with bpftool prog load bpf_filter.o /sys/fs/bpf/ipfilter and can see with the same tool it looks ok: [root@~]$ bpftool -f map show ... 134: socket_filter name test_ip_filter tag ac82ae2a45a2e98d gpl loaded_at 2022-10-26T16:36:03+0100 uid 0 xlated 472B jited 276B memlock 4096B map_ids 38,40 pinned /sys/fs/bpf/ipfilter btf_id 191 [root@~]$ bpftool -f map show ... 38: lpm_trie name allowlist flags 0x1 key 8B value 1B max_entries 128 memlock 4096B btf_id 191 Now in my userspace application I want to connect to the map and update it. I thought I could maybe do something like this: // note, error checking omitted. // Get object fd int obj_fd = bpf_obj_get("/sys/fs/bpf/ipfilter"); // Get the bpf object struct bpf_object *obj; // <= HOW TO GET THIS // Get the maps FD (use for updating etc). int map_fd = bpf_object__find_map_fd_by_name(obj, "allowlist"); // get details about the map (key size etc). struct bpf_map_info map_info = {}; __u32 info_len = sizeof(map_info); bpf_obj_get_info_by_fd(map_fd, &map_info, &info_len); Assuming what I have is correct so far, how do I retrieve bpf_object struct or am I way off in my undertanding?
Posting an answer myself as I seem to have found a way (although not sure it is the correct thing to do?). I set the pinning mode of the struct in kernel space to be pinned by name e.g struct { __uint(type, BPF_MAP_TYPE_LPM_TRIE); __uint(max_entries, 128); __type(key, struct ip4_trie_key); __type(value, char); __uint(map_flags, BPF_F_NO_PREALLOC); __uint(pinning, LIBBPF_PIN_BY_NAME); // <= THIS LINE FIXED IT } allowlist SEC(".maps"); This gave the map it's own pinned file in /sys/fs/bpf/allowlist which I could then just access with bpf_obj_get("/sys/fs/bpf/allowlist").
74,211,585
74,211,840
Missing wingdi functions when exporting using gcc
So i'm trying to compile this simple piece of c++ code using gcc: #include <windows.h> #include <wingdi.h> int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { HWND hwnd = GetDesktopWindow(); HDC hdc = GetWindowDC(hwnd); RECT rekt; GetWindowRect(hwnd, &rekt); for (int i = 0; i < 50000; i++) { int x = rand() % 1920; int y = rand() % 1080; SetPixel(hdc, x, y, RGB(255, 255, 255)); } ReleaseDC(hwnd, hdc); } and i'm using the following console command to (try to) build the executable: .\g++.exe -lgdi32 -o output WindowsProject1.cpp But i'm getting the following error: WindowsProject1.cpp:(.text+0xcd): undefined reference to `SetPixel@16' collect2.exe: error: ld returned 1 exit status I'm guessing this is some linking issue? I'm pretty new to compiling c++, and it runs fine in Visual Studio, so i'm not quite sure what to do. As mentioned before, the command I'm using to build the executable does contain "-lgdi32" and this was an attempt of linking the library, but this still did not resolve the issue.
Putting -lgdi32 at the end as suggested by @user4581301 fixed this issue.
74,211,950
74,212,948
QT - how to fix link error 2019 with qt VS tools
I'm trying to create a simple qt application in visual studio, I also made sure to install all qt components. Code: #include "QtWidgetsApplication2.h" #include <QtWidgets/QApplication> #include <QtDataVisualization/Q3DSurface> #include <QtDataVisualization/QSurfaceDataProxy> #include <QtDataVisualization/QHeightMapSurfaceDataProxy> #include <QtDataVisualization/QSurface3DSeries> #include <QtWidgets/QSlider> int main(int argc, char *argv[]) { QApplication a(argc, argv); QtWidgetsApplication2 w; Q3DSurface* graph = new Q3DSurface(); QWidget* container = QWidget::createWindowContainer(graph); w.show(); return a.exec(); } I have already set the correct QT version, and the path to the aditional libraries for the linker(at C:\Qt\6.4.0\msvc2019_64\lib) but somehow i'm still getting an error linker LNK2019. What gives? EDIT: my .pro file: TEMPLATE = app TARGET = QtWidgetsApplication2 DESTDIR = ../x64/Debug CONFIG += debug DEPENDPATH += . MOC_DIR += . OBJECTS_DIR += debug UI_DIR += . RCC_DIR += . include(QtWidgetsApplication2.pri)
From the Qt documentation for Q3DSurface here: https://doc.qt.io/qt-6/q3dsurface.html on the qmake line at the top it has qmake: QT += datavisualization the QT += datavisualization part is what you need to add to your .pro file to use the Q3DSurface class. This will setup the linking and any additional include directories.
74,212,589
74,212,606
Can you get/re-use a promise from a future object when you're done with the future object
is there code that works like this? promise<type> p; future<type> f{p.get_future()}; ..thread stuff... f.get(); //now the important part | // v p=f.get_promise();
You cannot get a promise from a future at all. And once a promise's value is set, it cannot be changed. You could reset a particular std::promise object by move-assigning from a freshly created promise, but no future attached to it would be updated. They would all be looking at the previous shared state, not the new one.
74,213,511
74,213,570
Iterative Binary Search Tree C++; Why sometimes my program run correctly and other time not?
I am trying to insert new nodes to binary search tree. I get no error, but if I run this program sometimes the tree displays correctly in cmd and sometimes nothing happens and the program doesn't crash, but the console is like waiting for something. I can't figure it out where the mistake is. Here is the code: #include <iostream> #include <string> template <typename T> class BinarySearchTree { public: class Node { public: T data; Node* left; Node* right; }; Node* root; BinarySearchTree() { root = nullptr; } Node* getRoot() { return root; } Node* createNode(T data) { Node* newNode = new Node(); newNode->data = data; newNode->left = nullptr; newNode->right = nullptr; return newNode; } Node* insert(Node*& root, T data) { Node* current = root; Node* prev = nullptr; while (current != nullptr) { prev = current; if (current->data < data) current = current->right; else if (current->data > data) current = current->left; else continue; } if (prev == nullptr) prev = createNode(data); else if (prev->data < data) prev->right = createNode(data); else if (prev->data > data) prev->left = createNode(data); else if (prev->data == data) prev->data = data; return prev; } class Trunk { public: Trunk* prev; std::string str; Trunk(Trunk* prev, std::string str) { this->prev = prev; this->str = str; } }; void showTrunks(Trunk* p) { if (p == nullptr) return; showTrunks(p->prev); std::cout << p->str; } void printTree(Node* root, Trunk* prev, bool isLeft) { if (root == nullptr) return; std::string prev_str = " "; Trunk* trunk = new Trunk(prev, prev_str); printTree(root->right, trunk, true); if (!prev) trunk->str = "---"; else if (isLeft) { trunk->str = ".---"; prev_str = " |"; } else { trunk->str = "`---"; prev->str = prev_str; } showTrunks(trunk); std::cout << " " << root->data << std::endl; if (prev) prev->str = prev_str; trunk->str = " |"; printTree(root->left, trunk, false); } }; struct Point { int x; int y; Point(int x, int y) { this->x = x; this->y = y; } Point() { x = 0; y = 0; } bool operator>(const Point& point) { if ((x + y) > (point.x + point.y)) return true; return false; } bool operator<(const Point& point) { if ((x + y) < (point.x + point.y)) return true; return false; } bool operator==(const Point& point) { if ((x + y) == (point.x + point.y)) return true; return false; } bool operator!=(const Point& point) { if ((x + y) != (point.x + point.y)) return true; return false; } }; std::ostream& operator<<(std::ostream& COUT, Point& point) { COUT << "(" << point.x << ", " << point.y << ")"; return COUT; } And here is the main function: int main() { srand(time(0)); BinarySearchTree<Point>* tree = new BinarySearchTree<Point>(); BinarySearchTree<Point>::Node* root = tree->getRoot(); Point point; point.x = 100; point.y = 100; root = tree->insert(root, point); for (int i = 0; i < 10; i++) { Point point; point.x = rand() % 100; point.y = rand() % 100; tree->insert(root, point); } tree->printTree(root, nullptr, false); return 0; }
During while (current != nullptr) { prev = current; if (current->data < data) current = current->right; else if (current->data > data) current = current->left; else continue; } If current->data is equal to data, what will happen? You will continue the loop, with current unchanged. This will loop forever. That would explain your program hanging. There is also no point in passing a reference in: Node* insert(Node*& root, T data) This would do just as well an be less of an eye sore: Node* insert(Node* root, T data)
74,214,333
74,214,385
How to get return value of c++ int main() output using subprocess.check_output() in python script
I am using a C++ script as follows: int main(){ int x =7; std::cout<<"print num:"<<x<<std::endl; if(x>0){ std::cout<<" good"<<std::endl; return 5; } return 0; } For this in my python file I am calling the subprocess as follows: result0_1 = subprocess.check_output(MYCPP_fILE_PATH,shell =True) print(result0_1.decode("utf-8")) It prints out "print num:" and "good" but dosn't provide me the return value "5". How can I get the return value but not the std::cout from the cpp file?
From Python 3 docs And very similar Python 2 docs If the return code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute.
74,214,646
74,240,715
C++ macros - holding keys for certain time
I just started with C++ and I want to make my game character being IDLE in any game. I've tried some code to make him move but it seems that it glitches, how can I make it so that a key are being hold for a small amount of time and then the next key? For example: Pressing W for 2 sec, then A for 2 sec, then S for 2 sec and finally D for 2 sec. Here's my code and I would like if someone helps me with it because I don't understand most of the lines :P int sleepBetween = 50; if (GetAsyncKeyState(VK_NUMPAD1)) { std::cout << "Working..." << endl; SHORT key; UINT mappedkey; // Loop while (true) { INPUT input = {}; key = VkKeyScan('w'); mappedkey = MapVirtualKey(LOBYTE(key), 0); input.type = INPUT_KEYBOARD; input.ki.dwFlags = KEYEVENTF_SCANCODE; input.ki.wScan = mappedkey; SendInput(1, &input, sizeof(INPUT)); Sleep(10); input.ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP; SendInput(1, &input, sizeof(INPUT)); Sleep(sleepBetween); key = VkKeyScan('a'); mappedkey = MapVirtualKey(LOBYTE(key), 0); input.type = INPUT_KEYBOARD; input.ki.dwFlags = KEYEVENTF_SCANCODE; input.ki.wScan = mappedkey; SendInput(1, &input, sizeof(INPUT)); Sleep(10); input.ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP; SendInput(1, &input, sizeof(INPUT)); Sleep(sleepBetween); key = VkKeyScan('s'); mappedkey = MapVirtualKey(LOBYTE(key), 0); input.type = INPUT_KEYBOARD; input.ki.dwFlags = KEYEVENTF_SCANCODE; input.ki.wScan = mappedkey; SendInput(1, &input, sizeof(INPUT)); Sleep(10); input.ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP; SendInput(1, &input, sizeof(INPUT)); Sleep(sleepBetween); Sleep(sleepBetween); key = VkKeyScan('d'); mappedkey = MapVirtualKey(LOBYTE(key), 0); input.type = INPUT_KEYBOARD; input.ki.dwFlags = KEYEVENTF_SCANCODE; input.ki.wScan = mappedkey; SendInput(1, &input, sizeof(INPUT)); Sleep(10); input.ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP; SendInput(1, &input, sizeof(INPUT)); Sleep(sleepBetween); // Stop with NUM 2 if (GetAsyncKeyState(VK_NUMPAD2)) { std::cout << "Stopped!" << endl; break; }
Forget that it was about a game it's just a macros. It's design was to press a key and that's it. I fixed it by making a method for holding a key and then recalling it for each key I wanted. void HoldKey(char keyToHold, double repeatingTime) { SHORT key; UINT mappedkey; INPUT input; key = VkKeyScan(keyToHold); mappedkey = MapVirtualKey(LOBYTE(key), 0); for (int i = 0; i < repeatingTime; i++) { input.type = INPUT_KEYBOARD; input.ki.dwFlags = KEYEVENTF_EXTENDEDKEY; // Press Key input.ki.wScan = mappedkey; SendInput(1, &input, sizeof(INPUT)); Sleep(100); input.ki.dwFlags = KEYEVENTF_KEYUP; // Releaase Key SendInput(1, &input, sizeof(input)); } And I recalled it in my main method: HoldKey('w', repeatingTime); HoldKey('a', repeatingTime); HoldKey('s', repeatingTime); HoldKey('d', repeatingTime);
74,214,843
74,215,011
How to save classes and vectors for later, so I don't have to create them every time I start my program in C++?
I have a .txt file with millions of Data points, and I want to organize them into Classes and Vectors. So the data is usable. However this will take a very long time and I don't want to do it every time I start my program. Is there a way to store the created classes and the data inside them so I only have to go through this process once? This is my first attempt at a practical program, so I apologize if this is a stupid question. If you could just point me in the right direction I would really appreciate it.
It sounds like a premature optimization to me. You say it "will take a very long time", but have not quantified that. How long does it take (as a function of data size), and what are your performance requirements? It sound like you have not yet written this code, so have no real idea of the actual performance. If this is your first substantial C++ project, the techniques necessary may be too advanced, and the benefit may not be realised. One solution could be instantiate your objects in memory mapped files, and restore them using placement new. However unless the construction, processing and transformations required to load the text file into the data structures is significant, I doubt the complexity of that would be justified by the result. Simply serialising the data into a binary rather than text file so that in re-reading it, fewer conversions are required could be a far simpler method. That is to say, you could rewrite the data file in a form that can be more efficiently and directly re-loaded subsequently. You would then write your code to be able to read either format, and generate the optimised format from the text format.