question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
71,031,763
71,032,005
Move tuple containing lambda
I am trying to implement a generic RAII cleanup. This looked like it was working, until I tried to use the move constructor: #include <functional> #include <tuple> #include <utility> template <typename R, typename D> class Cleaner { public: Cleaner() = default; Cleaner(R r, D d = {}) : data(std::move(d), std::move(r)), owns(true) { } ~Cleaner() { if (!owns) return; std::apply( [](auto&&... args){ std::invoke(std::forward<decltype(args)>(args)...); }, std::move(data) ); } Cleaner(Cleaner&& other) noexcept { swap(*this, other); } Cleaner& operator=(Cleaner&& other) noexcept { swap(*this, other); return *this; } void release() { owns = false; } R& get() { return std::get<1>(data); } R const& get() const { return std::get<1>(data); } friend void swap(Cleaner& a, Cleaner& b) noexcept { using std::swap; swap(a.data, b.data); swap(a.owns, b.owns); } private: std::tuple<D, R> data; bool owns = false; }; #include <iostream> int main() { auto c = Cleaner(0, [](int){ std::cout << "clean\n"; }); auto a(std::move(c)); // <- this fails to compile } (The compile error message is to long to copy here, but you can see it here: https://godbolt.org/z/5fqz5qTxT) The message starts with: source>: In instantiation of 'Cleaner<R, D>::Cleaner(Cleaner<R, D>&&) [with R = int; D = main()::<lambda(int)>]': <source>:48:24: required from here <source>:20:37: error: no matching function for call to 'std::tuple<main()::<lambda(int)>, int>::tuple()' 20 | Cleaner(Cleaner&& other) noexcept { | ^ In file included from /opt/compiler-explorer/gcc-trunk-20220208/include/c++/12.0.1/functional:54, from <source>:1: /opt/compiler-explorer/gcc-trunk-20220208/include/c++/12.0.1/tuple:1259:9: note: candidate: 'template<class _Alloc, class _U1, class _U2, typename std::enable_if<__is_explicitly_constructible<_U1, _U2>(), bool>::type <anonymous> > std::tuple<_T1, _T2>::tuple(std::allocator_arg_t, const _Alloc&, std::pair<_U1, _U2>&&) [with _U1 = _Alloc; _U2 = _U1; typename std::enable_if<std::_TupleConstraints<true, _T1, _T2>::__is_explicitly_constructible<_U1, _U2>(), bool>::type <anonymous> = _U2; _T1 = main()::<lambda(int)>; _T2 = int]' 1259 | tuple(allocator_arg_t __tag, const _Alloc& __a, pair<_U1, _U2>&& __in) | ^~~~~ [...] Can someone help me understand what the problem is so I can fix it?
Your issue is that lambda is not default constructible (non-capturing ones are since C++20). You might change constructor to: Cleaner(Cleaner&& other) noexcept : data(std::move(other.data)), owns(other.owns) { other.owns = false; } Demo
71,032,192
71,032,292
does pop( ) method delete the object from the memory?
In the following code: #include<iostream> #include<queue> using namespace std; int main() { queue<int> q; int a = 5; q.push(a); cout << q.front() << endl; // 5 int* b = &(q.front()); q.pop(); cout << *b; // Outputs 5 but why ? } Is a copy of 'a' created inside the queue when I pass 'a' into it ? And when I pop out 'a', then why I am able to dereference the pointer to get the correct output i.e. 5. All I know is that pop() calls the destructor . Please help !
Calling the destructor means that the object is destroyed and the program is no longer using it. It doesn't mean that the memory it took is now overwritten. So, in short: The object data might still be in memory as garbage. So the contents of the same memory address will depend on whether the program has already used that memory for something else or not. As the behaviour of accessing garbage data is undefined, this might vary between executions.
71,032,456
71,032,457
Is enum E { a } e = E(2); valid?
A recent and interesting C language-lawyer question asked: Is enum { a } e = 1; valid? This Q&A asks the same question for the similar cases for C++(*): are these valid? enum EA { a } ea = EA(2); // #1 enum EB { b } eb = static_cast<EB>(2); // #2 I've already noted that the variation enum EC { c } ec = EC{2}; is rejected at compile time ("cannot initialize a value of type 'E' with an rvalue of type 'int'), whereas #1 and #2 are accepted, ruling out ill-formed but not ill-formed NDR and UB for #1 and #2. (*) Posted here as a self-answered Q&A after being prompted to break out overly eager and misplaced C++-focused answer to the original C language-lawyer question.
Unspecified behavior until C++14; undefined behavior since C++17 Whilst the corresponding construct is legal in C—as answered thoroughly in the linked-to C language-lawyer Q&A—due to the stronger "compatible type" requirement, the same does not hold for C++, where "C style" unscoped enums with no fixed underlying type have subtle differences from C. First of all, we may note that the original C example enum E { a } e = 1; is not legal in C++ as C++ does not allow implicit conversion from an integer type to an unscoped enum with no explicit underlying type, thus the slightly modifyed examples of the OP // Syntactically legal -> compiles. enum EA { a } ea = EA(2); // #1 enum EB { b } eb = static_cast<EB>(2); // #2 As per [dcl.enum]/7, For an enumeration whose underlying type is fixed, the values of the enumeration are the values of the underlying type. Otherwise, the values of the enumeration are the values representable by a hypothetical integer type with minimal width M such that all enumerators can be represented. The width of the smallest bit-field large enough to hold all the values of the enumeration type is M. [...] the underlying type of EA and EB is implementation-defined. As per [expr.static.cast]/10: A value of integral or enumeration type can be explicitly converted to a complete enumeration type. [...] If the enumeration type does not have a fixed underlying type, the value is unchanged if the original value is within the range of the enumeration values ([dcl.enum]), and otherwise, the behavior is undefined. [...] #2 above may (depending on the implementation-defined underlying type of the E) lead to undefined behavior in C++17 and forward, via the resolution of CWG 1766, and unspecified behavior in C++14 and earlier. Conceptually, the conversion could possibly cause signed integer overflow (which is UB). Case #1 is, as per [expr.type.conv], also an explicit (type) conversion, and the same argument as for #2 applies also for this functional cast case.
71,032,474
71,032,565
Std::nth_element is not giving the correct element
I don't know why in this case the function std::nth_element is not giving me the correct median for the X axis. For this test I created a vector of point: std::vector<Point> points = {Point {70, 70}, Point {50, 30}, Point {35, 45}}; The function call is: int median = (start + end) / 2; Point split = get(points.begin() + start, points.begin() + median, points.begin() + end); Where start = 0; end = 2; In my mind the correct median for the X axis is Point(50, 30), instead this code gives me Point(70, 70). Below there is the code for finding the median: template <typename Iterator> Point get(Iterator start, Iterator median, Iterator end) { std::nth_element( start, median, end, [](const Point &point1, const Point &point2) { return point1.getX() < point2.getX(); } ); std::vector<Point>::iterator iter = median; std::cout << *iter << std::endl; return *iter; }
The variable end is not correctly pointing to the end of the vector. Hence, you only perform nth_element() on the first 2 elements. Since the variable median value is 1, the point with greater x value will be returned. You can use points.end() instead of points.begin() + end.
71,032,714
71,032,838
Reading unsigned int into uint64_t from binary file
I am trying to read a binary file using fstream. I know the types of everything in this file but there are two different versions, an old and a new version. The old version contains variables of type 'unsigned int' deemed to have insufficient range, and are replaced by 'uint64_t' in the new version. I'd like one file reader capable of reading both formats(for backwards compatibility). The read result should always be a uint64_t. I am sure this is a common problem. I've tried simply reading 4 bytes from an ifstream into the memory of the uint64_t, comparable to the snippet below(without checking for any problems): std::uint64_t buff=0; std::ifstream is(filePath, std::ios_base::binary) std::is.read(&buff,sizeof(unsigned int)); This gives me the correct value but I realize this might be subject to endianness. Is there a common method to solve this problem?
You need to read it into a variable of the correct type and then you can assign it to your uint64_t variable. static_assert(std::endian::native == std::endian::big || std::endian::native == std::endian::little); constexpr auto file_endianess = std::endian::big; // or little std::uint64_t buff = 0; std::ifstream is(filePath, std::ios_base::binary); if (is) { std::uint32_t temp; if (is.read(reinterpret_cast<char*>(&temp), sizeof temp)) { // ... deal with endianess here ... // (example from C++23 below) #ifdef __cpp_lib_byteswap if constexpr(std::endian::native != file_endianess) { temp = std::byteswap(temp); } #else // an alternative endianess solution goes here #endif buff = temp; } }
71,033,511
71,033,676
Why can't I use `using` in a multiple inheritance c++?
I tried to implement some interfaces and their children. This is my idea: Interface / \ Interface2 InterfaceDefination | / Interface2Defination And this is my code: #include <iostream> class Interface { public: virtual void method1() = 0; virtual void print() = 0; }; class Interface2 : public Interface { public: virtual void method2() = 0; }; class InterfaceDefination : public Interface { public: virtual void method1() override { std::cout << "method1 from InterfaceDefination\n"; } }; class Interface2Defination : public Interface2, public InterfaceDefination { public: using InterfaceDefination::method1; virtual void print() override { std::cout << "print from Interface2Defination\n"; } virtual void method2() override { std::cout << "method2 from Interface2Defination\n"; } }; int main() { Interface2Defination c; c.method1(); c.method2(); c.print(); } My expected output is: method1 from InterfaceDefination method2 from Interface2Defination print from Interface2Defination But accidentally i received these errors: main.cpp:33:24: error: variable type 'Interface2Defination' is an abstract class Interface2Defination c; ^ main.cpp:5:16: note: unimplemented pure virtual method 'method1' in 'Interface2Defination' virtual void method1() = 0; ^ 1 error generated. make: *** [<builtin>: main.o] Error 1 exit status 2 https://godbolt.org/z/9ncoGfn4P In this case, the error means using keyword is not making method method1 usable in class Interface2Defination. What should i do with it?
A using declaration is a declaration. It is not a definition. It does not define anything "new". What it does is declare: ok, I have a symbol X, but it really refers to X in my parent class (for this version of a using declaration). You might ask what's the point, aren't you inheriting X from your parent class in the normal fashion. Yes, that's true, but it's not the same thing, but the technical differences are mostly immaterial here. What's also important here is that the shown diagram is misleading. It is a popular way to portray (non-virtual) diamond inheritance, but every time it's shown, it is 100% wrong. This is because Interface2Defination does not inherit one instance of Interface, but two. This is a more accurate inheritance diagram: Interface Interface | | Interface2 InterfaceDefination | / Interface2Defination For each one of the two instances of Interface parent classes, only one of its abstract methods gets defined and overridden, hence the shown code is ill-formed. The using declaration does not define the imported method in the child class, and formally override it. A using declaration does not "count" for the purpose of overriding an abstract method. Only formally defining an inherited abstract method does that, not declaring one.
71,033,950
71,034,025
In C++ map, which is better for usage/perfomance and conforms to the guidelines, using find_if or find then and .at
I am using a C++ map, in which I need to search for an element then get the element if it is exist. The first way to do that is using find if (mymap.find(mykey) == mymap.end()) { //return error code return ERROR_CODE; } else { value = mymap.at(mykey).second; return SUCCESS_CODE; } second way to do that: auto iter= find_if(mymap.begin(), mymap.end(), [&key](auto &item){return item.first == key;}) if(iter == mymap.end()) { return ERROR_CODE; } else { value = iter->second; return SUCCESS_CODE; } Is there any technical consideration or guidelines (like cpp guideline) that mention something like that, which way is better?
You should not use std::find_if which is linear, whereas you might have iterator in logarithm time. You might do auto it = mymap.find(mykey) if (it == mymap.end()) { //return error code return ERROR_CODE; } else { value = it->second; return SUCCESS_CODE; }
71,034,159
71,044,910
How to encapsulate the H.264 bitstream of video file in C++
I'm trying to convert a video file (.mp4) to a Dicom file. I have succeeded to do it by storing single images (one per frame of the video) in the Dicom, but the result is a too large file, it's not good for me. Instead I want to encapsulate the H.264 bitstream as it is stored in the video file, into the Dicom file. I've tried to get the bytes of the file as follows: std::ifstream inFile(file_name, std::ifstream::binary); inFile.seekg(0, inFile.end); std::streampos length = inFile.tellg(); inFile.seekg(0, inFile.beg); std::vector<unsigned char> bytes(length); inFile.read((char*)&bytes[0], length); but I think I have missed something like encapsulating for the read bytes because the result Dicom file was a black image. In python I would use pydicom.encaps.encapsulate function for this purpose: https://pydicom.github.io/pydicom/dev/reference/generated/pydicom.encaps.encapsulate.html with open(videofile, 'rb') as f: dataset.PixelData = encapsulate([f.read()]) Is there anything in C ++ that is equivalent to the encapsulate function? or any different way to get the encapsulated pixel data of video at one stream and not frame by frame? This is the code of initializing the Dcmdataset, using the bytes extracted: VideoFileStream* vfs = new VideoFileStream(); vfs->setFilename(file_name); if (!vfs->open()) return false; DcmDataset* dataset = new DcmDataset(); dataset->putAndInsertOFStringArray(DCM_SeriesInstanceUID, dcmGenerateUniqueIdentifier(new char[100], SITE_SERIES_UID_ROOT)); dataset->putAndInsertOFStringArray(DCM_SOPInstanceUID, dcmGenerateUniqueIdentifier(new char[100], SITE_INSTANCE_UID_ROOT)); dataset->putAndInsertOFStringArray(DCM_StudyInstanceUID, dcmGenerateUniqueIdentifier(new char[100], SITE_STUDY_UID_ROOT)); dataset->putAndInsertOFStringArray(DCM_MediaStorageSOPInstanceUID, dcmGenerateUniqueIdentifier(new char[100], SITE_UID_ROOT)); dataset->putAndInsertString(DCM_MediaStorageSOPClassUID, UID_VideoPhotographicImageStorage); dataset->putAndInsertString(DCM_SOPClassUID, UID_VideoPhotographicImageStorage); dataset->putAndInsertOFStringArray(DCM_TransferSyntaxUID, UID_MPEG4HighProfileLevel4_1TransferSyntax); dataset->putAndInsertOFStringArray(DCM_PatientID, "987655"); dataset->putAndInsertOFStringArray(DCM_StudyDate, "20050509"); dataset->putAndInsertOFStringArray(DCM_Modality, "ES"); dataset->putAndInsertOFStringArray(DCM_PhotometricInterpretation, "YBR_PARTIAL_420"); dataset->putAndInsertUint16(DCM_SamplesPerPixel, 3); dataset->putAndInsertUint16(DCM_BitsAllocated, 8); dataset->putAndInsertUint16(DCM_BitsStored, 8); dataset->putAndInsertUint16(DCM_HighBit, 7); dataset->putAndInsertUint16(DCM_Rows, vfs->height()); dataset->putAndInsertUint16(DCM_Columns, vfs->width()); dataset->putAndInsertUint16(DCM_CineRate, vfs->framerate()); dataset->putAndInsertUint16(DCM_FrameTime, 1000.0 * 1 / vfs->framerate()); const Uint16* arr = new Uint16[]{ 0x18,0x00, 0x63, 0x10 }; dataset->putAndInsertUint16Array(DCM_FrameIncrementPointer, arr, 4); dataset->putAndInsertString(DCM_NumberOfFrames, std::to_string(vfs->numFrames()).c_str()); dataset->putAndInsertOFStringArray(DCM_FrameOfReferenceUID, dcmGenerateUniqueIdentifier(new char[100], SITE_UID_ROOT)); dataset->putAndInsertUint16(DCM_PixelRepresentation, 0); dataset->putAndInsertUint16(DCM_PlanarConfiguration, 0); dataset->putAndInsertOFStringArray(DCM_ImageType, "ORIGINAL"); dataset->putAndInsertOFStringArray(DCM_LossyImageCompression, "01"); dataset->putAndInsertOFStringArray(DCM_LossyImageCompressionMethod, "ISO_14496_10"); dataset->putAndInsertUint16(DCM_LossyImageCompressionRatio, 30); dataset->putAndInsertUint8Array(DCM_PixelData, (const Uint8 *)bytes.data(), length); DJ_RPLossy repParam; dataset->chooseRepresentation(EXS_MPEG4HighProfileLevel4_1, &repParam); dataset->updateOriginalXfer(); DcmFileFormat fileformat(dataset); OFCondition status = fileformat.saveFile("C://temp//videoTest", EXS_LittleEndianExplicit);
The trick is to redirect the value of the attribute PixelData to a file stream. With this, the video is loaded in chunks and on demand (i.e. when the attribute is accessed). But you have to create the whole structure explicitly, that is: The Pixel Data element The Pixel Sequence with... ...the offset table ...a single item containing the contents of the MPEG file Code // set length to the size of the video file DcmInputFileStream dcmFileStream(videofile.c_str(), 0); DcmPixelSequence* pixelSequence = new DcmPixelSequence(DCM_PixelSequenceTag)); DcmPixelItem* offsetTable = new DcmPixelItem(DCM_PixelItemTag); pixelSequence->insert(offsetTable); DcmPixelItem* frame = new DcmPixelItem(DCM_PixelItemTag); frame->createValueFromTempFile(dcmFileStream.newFactory(), OFstatic_cast(Uint32, length), EBO_LittleEndian); pixelSequence->insert(frame); DcmPixelData* pixelData = new DcmPixeldata(DCM_PixelData); pixelData->putOriginalRepresentation(EXS_MPEG4HighProfileLevel4_1, nullptr, pixelSequence); dataset->insert(pixelData, true); DcmFileFormat fileformat(dataset); OFCondition status = fileformat.saveFile("C://temp//videoTest"); Note that you "destroy" the compression if you save the file in VR Implicit Little Endian. As mentioned above and obvious in the code, the whole MPEG file is wrapped into a single item in the PixelData. This is DICOM conformant but you may want to encapsulate single frames each in one item. Note : No error handling presented here
71,034,432
71,034,876
Generate const array of pointers to callback functions
I'd like to generate an array of N pointers to callbacks so I don't have to type them explicitly (LOC is not the issue here). I use C++17. Here is what I have: using Callback = void(*)(); auto constexpr N = 2; const Callback callbacks[N] = { [](){ auto i = 0; std::cout<<"callback " << i << "\n";}, [](){ auto i = 1; std::cout<<"callback " << i << "\n";} }; callbacks[0](); callbacks[N-1](); Here is what I want: const auto callbacks = generate_callbacks<N>(); // or generate_callbacks(N) callbacks[i](); // cout<<"callback " << i << "\n"; I tried various ways, but I keep running into the problems with constant parameters even when they are from a constexpr function or variadic template. If I try this: Callback callbacks[N] = { }; for(int i=0;i<N;++i) { callbacks[i] = [i](){ std::cout<<"callback " << i << "\n";}; } for(int i=0;i<N;++i) { callbacks[i](); } I get the following error: main.cpp:91:66: error: cannot convert ‘main()::’ to ‘Callback {aka void (*)()}’ in assignment callbacks[i] = [i](){ std::cout<<"callback " << i << "\n";}; If I make i static and leave out the capture it only uses the last value of i: callback 2 callback 2 This is odd to me as capturing should be done at construction. Are the lambdas constructed after the loop exits? As for the purpose. I want to apply this technique to generating interrupt handlers for microcontrollers. I can put the function pointers in the interrupt vector table directly. These functions have no parameters and I don't know a clean way to detect which interrupt source called the handler. I can write a handler for each interrupt, but I don't like repeating this code 6 times: void handler0() { do_something(0); } Typing it as a lambda and/or using a template makes it a little cleaner, but I still have to type something N times. And if N changes I have to change multiple lines of code. This is not elegant.
Off Topic Suggestion: don't use, when you can, C-styles arrays but C++ std::array. For example: the following line const auto callbacks = generate_callbacks<N>(); can't works if you want that callbacks is a C-style array (a function can't return that type) but works when generate_callback() return a std::array<Callback, N> instance. End of Off Topic Suggestion. In this particular case, given that N is a constexpr value, I propose the use of template meta-programming. So I suggest the following generate_callbacks() function, that just create a sequence of template values from zero to N-1 and call an helper function template <std::size_t N> auto generate_callbacks () { return gc_helper(std::make_index_sequence<N>{}); } and a simple helper function that uses the template values and create the callbacks lambdas without capturing them (so remaining convertible to function pointers) template <std::size_t ... Is> std::array<Callback, sizeof...(Is)> gc_helper (std::index_sequence<Is...>) { return {{ []{ auto i = Is; std::cout<<"callback " << i << "\n"; }... }}; } If you can use C++20, using template lambdas you can avoid the external gc_helper() function and make all inside generate_callbacks() as follows template <std::size_t N> auto generate_callbacks () { return []<std::size_t ... Is>(std::index_sequence<Is...>) -> std::array<Callback, N> { return {{ []{ std::cout<<"callback " << Is << "\n"; }... }}; } (std::make_index_sequence<N>{}); } The following is a full compiling C++17 C++14 example #include <iostream> #include <utility> #include <array> using Callback = void(*)(); auto constexpr N = 2; template <std::size_t ... Is> std::array<Callback, sizeof...(Is)> gc_helper (std::index_sequence<Is...>) { return {{ []{ auto i = Is; std::cout<<"callback " << i << "\n"; }... }}; } template <std::size_t N> auto generate_callbacks () { return gc_helper(std::make_index_sequence<N>{}); } int main() { const auto callbacks = generate_callbacks<N>(); for ( auto ui = 0 ; ui < N ; ++ui ) callbacks[ui](); }
71,034,909
71,042,795
Finding element in QList
Suppose I have a struct SignalError which has an element "errName" and many other elements: typedef struct SignalError { QString errName; ..... }; I create QList of this struct: QList<SignalError> signalErrList; I will append the struct element to the QList using append call. SignalError sgErr1 = {"Error_1"}; signalerrList.append(sgErr1); Before appending the element to the list I want to check if there is any element with the same name "errName" already existing in the QList or not. If it is then I will not add the element to the list. How do I do this? Also, should I create a list of objects like: QList<SignalError> signalErrList; or create list of pointer to the object: QList<SignalError*> signalErrList;
You should use QList<SignalError> signalErrList; not a QList of pointers. If you don’t care about order, you should use a std::set<SignalError> which will give you deduplication automatically. If you care about order and the O(N) search isn’t a problem, then use QList or std::vector and do if (auto it = std::find(signalErrList.begin(), signalErrList.end(), sgErr1; it == signalErrList.end()) { signalErrList.push_back(std::move(sgErr1)); } which you could (and should) name as a function: //! A linear-time (O(n)) search followed by push-back if not found //! API modeled on https://en.cppreference.com/w/cpp/container/set/emplace template <typename Container, typename Value> std::pair<typename Container::iterator, bool> emplaceBackLinearUnique(Container& c, Value&& v) { if (auto it = std::find(c.begin(), c.end(), v); it != c.end()) { // Return iterator to the found one and say that it wasn't emplaced. return { it, false }; } // Not found: c.emplace_back(std::forward<Value>(v)); // Return iterator to the new last element and report that it was emplaced: return { c.begin() + c.size() - 1, true }; } which lets you replace. your use case with this.: emplaceBackLinearUnique(signalErrList, sgErr1);
71,035,326
71,035,587
std::ranges algorithm function object customisation points AKA niebloids - problems with std lib types
All done with gcc 11.2 and libstdc++-11 Below code shows a variety of ways of using std::sort and then std::ranges::sort to sort builtins, user defined types and a std library type. Only the std library type gives me trouble: I can't easily define a custom operator< or operator<=> because it is UB to add that to namespace std. I think there is no way around this? (without using a lambda or similar) for some reason I cannot pass a public member function as the proj parameter on the std lib type (but it works on the user defined type). Why? I was unable to penetrate the "wall of errors" enough to find out. gcc basically says: no known conversion for argument 3 from ‘<unresolved overloaded function type>’ to ‘std::identity’.. Update: My only theory on 2. above is that "unresolved overloaded function type" means that std::complex<double>::real has 2 overloads. One which takes a parameter (the "setter") and one which doesn't (the "getter"). Is there a syntax which allows me to specify that I want the "address of" the one without a parameter? Update2: Thanks to 康桓瑋 for pointing out in the comments that taking the address of a member function in std is just UB anyway. However if I add a sum(int c) overload to thing (now added below) I get the same "unresolved overloaded" error. So the question remains, how can I select the one with no params. Or is there no way? #include <algorithm> #include <compare> #include <complex> #include <iostream> #include <ranges> #include <vector> namespace std { // this is UNDEFINED BEHAVIOUR!!! --- but "it works", so we know this option is what would be // required, but is not available to us std::partial_ordering operator<=>(const std::complex<double>& a, const std::complex<double>& b) { return std::abs(a) <=> std::abs(b); } } // namespace std // a user defined type struct thing { int x{}; int y{}; [[nodiscard]] int sum() const { return x + y; } [[nodiscard]] int sum(int c) const { return x + y + c; } // added for update 2 friend std::strong_ordering operator<=>(const thing& a, const thing& b) { return a.x + a.y <=> b.x + b.y; } friend bool operator==(const thing& a, const thing& b) { return a.x + a.y == b.x + b.y; } friend std::ostream& operator<<(std::ostream& os, const thing& rhs) { return os << "[" << rhs.x << "," << rhs.y << "]"; } }; int main() { // builtin types auto ints = std::vector<int>{9, 10, 7, 8, 5, 6, 3, 4, 1, 2}; std::ranges::sort(ints); std::ranges::sort(ints, {}, [](const auto& c) { return -c; }); for (const auto& e: ints) std::cout << e << " "; std::cout << "\n"; auto things = std::vector<thing>{{9, 10}, {7, 8}, {3, 4}, {1, 2}, {5, 6}}; std::sort(things.begin(), things.end()); std::ranges::sort(things); std::ranges::sort(things, {}, [](const auto& e) { return e.sum(); }); std::ranges::sort(things, [](const auto& a, const auto& b) { return a < b; }, {}); std::ranges::sort(things, {}, &thing::x); std::ranges::sort(things, {}, &thing::sum); // COMPILE ERROR afte r update 2 for (const auto& e: things) std::cout << e << " "; std::cout << "\n"; auto complexes = std::vector<std::complex<double>>{{9, 10}, {7, 8}, {3, 4}, {1, 2}, {5, 6}}; std::sort(complexes.begin(), complexes.end()); // requires operator< or <=> which is UB std::ranges::sort(complexes); // requires operator<=> which is UB std::ranges::sort(complexes, {}, [](const auto& c) { return std::abs(c); }); std::ranges::sort(complexes, {}, &std::complex<double>::real); // COMPILE ERROR!! for (const auto& e: complexes) std::cout << e << " "; std::cout << "\n"; return EXIT_SUCCESS; }
You need to specify a comparison for T if std::less<T> is unavailable. Both std::sort and std::ranges::sort require a strict weak ordering predicate, not operator<=> (but that can supply one, via < and std::less) template<typename T> bool complex_less (std::complex<T> lhs, std::complex<T> rhs) { return abs(lhs) < abs(rhs); }; int main() { auto things = std::vector<thing>{{9, 10}, {7, 8}, {3, 4}, {1, 2}, {5, 6}}; std::sort(things.begin(), things.end()); std::ranges::sort(things); std::ranges::sort(things, {}, [](const auto& e) { return e.sum(); }); std::ranges::sort(things, [](const auto& a, const auto& b) { return a < b; }, {}); std::ranges::sort(things, {}, &thing::x); std::ranges::sort(things, {}, static_cast<int (thing::*)()>(&thing::sum)); // need cast to disambiguate pointer-to-member for (const auto& e: things) std::cout << e << " "; std::cout << "\n"; auto complexes = std::vector<std::complex<double>>{{9, 10}, {7, 8}, {3, 4}, {1, 2}, {5, 6}}; std::sort(complexes.begin(), complexes.end(), complex_less<double>); // fine std::ranges::sort(complexes, complex_less<double>); // also fine std::ranges::sort(complexes, {}, [](const auto& c) { return std::abs(c); }); // still fine std::ranges::sort(complexes, {}, [](const auto& c) { return c.real(); }); // fine for (const auto& e: complexes) std::cout << e << " "; std::cout << "\n"; return EXIT_SUCCESS; }
71,035,341
71,035,654
Linked List insertion isn't working in for/while loop
I am learning DSA, and was trying to implement linked list but the insertion function that i wrote is not working in a for or while loop, its not the same when i call that function outside the loop, it works that way. I am not able to figure it out, please someone help me. #include <iostream> class Node { public: int data; Node *next; Node(int &num) { this->data = num; next = NULL; } }; class LinkedList { Node *head = NULL; public: void insert(int num) { Node *tmp; if (head == NULL) { head = new Node(num); tmp = head; } else { tmp->next = new Node(num); tmp = tmp->next; } } void printList() { Node *tmp = head; while (tmp) { std::cout << tmp->data << " "; tmp = tmp->next; } std::cout << std::endl; } void reverseList() { Node *curr = head, *prev = NULL, *nextNode; while (curr) { nextNode = curr->next; curr->next = prev; prev = curr; curr = nextNode; } head = prev; } }; int main() { LinkedList list1; // This is not working int num; while (num != -1) { std::cin >> num; list1.insert(num); } // This is working // list1.insert(1); // list1.insert(2); // list1.insert(3); // list1.insert(4); // list1.insert(5); list1.printList(); list1.reverseList(); list1.printList(); return 0; } I expect this after insertion Edit: although @Roberto Montalti solved this for me, but before that I tried passing incrementing value using a for loop which worked but as soon as I pull that cin out it crashes. can someone tell me what's happening under the hood? for (int i = 1; i <= 10; i++) { list1.insert(i); }
When inserting the nth item (1st excluded) tmp is a null pointer, i don't understand what you are doing there, you are assigning to next of some memory then you make that pointer point to another location, losing the pointer next you assigned before, you must keep track of the last item if you want optimal insertion. This way you are only assigning to some *tmp then going out of scope loses all your data... The best way is to just keep a pointer to the last inserted item, no need to use *tmp. class LinkedList { Node *head = NULL; Node *tail = NULL; public: void insert(int num) { if (head == NULL) { head = new Node(num); tail = head; } else { tail->next = new Node(num); tail = tail->next; } } ... }
71,035,511
71,039,860
Disabling specific test instance defined from a dataset
Let's say I have the following test code: struct MyData { MyData( int in_, double out_ ) : m_in{ in_ } , m_out{ out_ } {} int m_in; double m_out; }; std::ostream& operator<<( std::ostream& os_, MyData data_ ) { os_ << data_.m_in << " " << data_.m_out << std::endl; return os_; } std::vector< MyData > DataSetGet() { return { { 1, 1.0 }, { 2, 2.0 }, // I would like to disable this... { 3, 3.0 }, }; } BOOST_DATA_TEST_CASE( CastIntToDouble, DataSetGet() ) { BOOST_TEST( static_cast< double >( sample.m_in ) == sample.m_out ); } I would like to disable the second test instance. I could just comment out the second case, like this: std::vector< MyData > DataSetGet() { return { { 1, 1.0 }, //{ 2, 2.0 }, // I would like to disable this... { 3, 3.0 }, }; } but then this case would no longer be compiled, which is not what I am looking for. In my real scenario, test cases are more complex and I would like them compiled, but not run. I have searched the boost documentation on this topic and I came across the disable decorator, which looks like what I need. However, I have found no way to use it in data test cases. Is this possible?
You can supply a command line argument, like: ./sotest -l all -t "!*/*_1" Which outputs: More Advanced/Dynamic You could also supply your own decorator based on enable_if, which you could make to use your own custom command line options (you'll need to supply your own test_main to parse those). For an example of such custom decorator: https://www.boost.org/doc/libs/1_78_0/libs/test/doc/html/boost_test/tests_organization/enabling.html#boost_test.tests_organization.enabling.runtime_run_status Live Demo Live On Coliru #define BOOST_TEST_MODULE StackOverflow #include <boost/test/unit_test.hpp> #include <boost/test/data/dataset.hpp> #include <boost/test/data/test_case.hpp> #include <boost/test/unit_test_parameters.hpp> namespace but = boost::unit_test; namespace utf = boost::unit_test_framework; struct MyData { MyData(int in_, double out_) : m_in{in_}, m_out{out_} {} int m_in; double m_out; }; std::ostream& operator<<(std::ostream& os_, MyData data_) { return os_ << data_.m_in << " " << data_.m_out << std::endl; } std::vector<MyData> DataSetGet() { return { {1, 1.0}, {2, 2.0}, // I would like to disable this... {3, 3.0}, }; } BOOST_DATA_TEST_CASE(CastIntToDouble, DataSetGet()) { BOOST_TEST( static_cast< double >( sample.m_in ) == sample.m_out ); } Run with g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp -lboost_unit_test_framework ./a.out -l all -t "!*/*_1" --no_color_output Prints Running 2 test cases... Entering test module "StackOverflow" main.cpp(30): Entering test suite "CastIntToDouble" main.cpp(30): Entering test case "_0" main.cpp(32): info: check static_cast< double >( sample.m_in ) == sample.m_out has passed Assertion occurred in a following context: sample = 1 1 ; main.cpp(30): Leaving test case "_0"; testing time: 443us main.cpp(30): Test case "CastIntToDouble/_1" is skipped because disabled main.cpp(30): Entering test case "_2" main.cpp(32): info: check static_cast< double >( sample.m_in ) == sample.m_out has passed Assertion occurred in a following context: sample = 3 3 ; main.cpp(30): Leaving test case "_2"; testing time: 404us main.cpp(30): Leaving test suite "CastIntToDouble"; testing time: 967us Leaving test module "StackOverflow"; testing time: 1016us *** No errors detected
71,035,574
71,036,143
C++ pass by reference tricky situation
I'm trying to figure what happens to an "rvalue",temporary object, after the variable used to refer this object deleted from stack. Code example: #include<iostream> using namespace std; class Base { private: int &ref; public: Base(int &passed):ref(passed) { cout << "Value is " << ref << endl; } int getvalue(){ return ref; } }; int main() { Base *myobject; { int ref=10; myobject = new Base (ref); ref++; } //ref delete from stack. cout << myobject->getvalue() << endl; return 0; } I expected the second output(second cout) to give me some random garbage because ref deleted but instead I got the value of the current state of ref, I wander what happened after the ref got deleted is it pure luck? or myobject.ref stored the value of the ref he construct with? Edit: adding a visualizer to support my point that in the end myobject.ref pointing nowhere C++ visualizer
From Reference declaration documentation it is possible to create a program where the lifetime of the referred-to object ends, but the reference remains accessible (dangling). Accessing such a reference is undefined behavior. In your program the referred-to object ref ends at } after ref++. This means that the ref data member is now a dangling reference. And according to the above quoted statement, accessing that reference(which you do when you call getValue) is undefiend behavior. Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. For example, the output of the same program is different here and here. So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program. 1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
71,035,706
71,035,861
How to define configuration dependent properties in VS C++ project?
I'm really new to C++ and Visual Studio, I know there are ifdef and ifndef to do the conditional compilation. But my boss ask me to create 2 different configurations (similar to debug and release) to automate this. For example: #if $(some_configuration_dependent_flag) // I can do something specific for only config1 #endif I've already checked the configuration manager, but the dialog is only used to enable/disable the projects in the solution. Where and how to define the variable some_configuration_dependent_flag mentioned above?
Visual Studio allows per config pre-processor definitions. Use menu Project/Properties (on right click + Properties on the project) to open the Property Page dialog Then in C/C++ / Preprocessor, you find Preprocessor Definitions. You select the configuration you want to change, and can add or modify any definition.
71,036,436
71,037,226
How to use boost tests with SFML and cmake?
I'm writing a simple game in C++ with use of SFML. I want to use boost tests, but when i try to i get undefined reference in every place i use SFML features (the game itself works fine, it's just the test that don't). Sample test: #include <boost/test/unit_test.hpp> #include "Sentry.h" BOOST_AUTO_TEST_SUITE(BasicModelTestSuite) BOOST_AUTO_TEST_CASE(testLamp_10BulbsWithPower10_ExpectedPower) { sf::Texture projectileTexture; sf::Texture sentryTexture; std::vector<std::shared_ptr<Sentry>> foes; sentryTexture.loadFromFile("../GameResources/sentry_image.png"); projectileTexture.loadFromFile("../GameResources/projectile_animation.png"); foes.push_back(std::make_shared<Sentry>(Sentry(&sentryTexture, sf::Vector2u(1,2), 0.2f, sf::Vector2f(140,200), projectileTexture, true))); foes.push_back(std::make_shared<Sentry>(Sentry(&sentryTexture, sf::Vector2u(1,2), 0.2f, sf::Vector2f(200,200), projectileTexture, false))); BOOST_REQUIRE_EQUAL(foes.size(), 2); } BOOST_AUTO_TEST_SUITE_END() And the test portion of cmakelist.txt: ind_package(Boost 1.65 COMPONENTS "unit_test_framework" REQUIRED) include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/include ${Boost_INCLUDE_DIRS} ) set(SOURCE_TEST_FILES test/master.cpp test/master.cpp test/baseTest.cpp main.cpp src/Level.cpp include/Level.h src/Game.cpp include/Game.h src/Platform.cpp include/Platform.h src/Item.cpp include/Item.h src/Life.cpp include/Life.h src/Coin.cpp include/Coin.h src/Collider.cpp include/Collider.h src/Enemy.cpp include/Enemy.h src/MrStrawberry.cpp include/MrStrawberry.h src/Animation.cpp include/Animation.h src/MrBerry.cpp include/MrBerry.h src/Projectile.cpp include/Projectile.h src/Sentry.cpp include/Sentry.h) add_executable(TestProject ${SOURCE_TEST_FILES}) target_include_directories(TestProject PUBLIC include) target_link_libraries(TestProject ${Boost_UNIT_TEST_FRAMEWORK_LIBRARY}) enable_testing() add_test(NAME Test COMMAND TestProject --report_level=detailed --log_level=all --color_output=yes) add_custom_target(check ${CMAKE_COMMAND} -E env CTEST_OUTPUT_ON_FAILURE=1 BOOST_TEST_LOG_LEVEL=all ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> --verbose WORKING_DIRECTORY ${CMAKE_BINARY_DIR}) I have no clue why it throws undefined reference to everything, like this: /usr/bin/ld: /home/student/CLionProjects/oop21_ww2_14/BerryGame/src/Projectile.cpp:8: undefined reference to `sf::RectangleShape::setSize(sf::Vector2<float> const&)' /usr/bin/ld: /home/student/CLionProjects/oop21_ww2_14/BerryGame/src/Projectile.cpp:9: undefined reference to `sf::Shape::setTexture(sf::Texture const*, bool)'
TestProject is missing the SFML library in the link options (see also What is an undefined reference/unresolved external symbol error and how do I fix it?). Your main executable apparently does have it, but you don't show it. Look for something like LINK_LIBRARIES(sfml-system sfml-window sfml-graphics sfml-audio) Or target_link_libraries instead. If LINK_LIBRARIES is used, I suppose the target might need to be defined after that point.
71,036,571
71,036,861
Why does "L.insert(it--, i);" behave differently from "L.insert(it, i); it--;"?
These are two pieces of code that I ran under the C++11 standard. I expected the post-decrement of the iterator to produce the same effect, but these two pieces of code produce completely different results. Where is my understanding off? list<int> L; int main() { L.push_back(0); L.push_front(1); auto it = L.begin(); for (int i = 2; i <= 5; i++) { L.insert(it--, i); } for (auto num : L) { printf("%d ", num); } // 2 5 0 4 1 3 } list<int> L; int main() { L.push_back(0); L.push_front(1); auto it = L.begin(); for (int i = 2; i <= 5; i++) { L.insert(it, i); it--; } for (auto num : L) { printf("%d ", num); } // 5 4 3 2 1 0 }
Consider exactly when the post-decrement happens. In the second case, obviously the insert happens, modifying the list itself. The iterator is still valid, pointing now at the second entry. Then the decrement is computed, moving the iterator to the first entry. In the first case, however, the post-decrement "makes a copy" of the iterator, performs the decrement, and returns the previous version. That means that the new value of the iterator is computed before the insert happens, which is invalid since it already points at the first element. Note that the insert still happens correctly, because the post-decrement returns the original and still-valid iterator. This is not about post- vs. pre- decrement behavior. It's about when the side-effect of the decrement actually happens. See https://en.cppreference.com/w/cpp/language/eval_order, specifically When calling a function (whether or not the function is inline, and whether or not explicit function call syntax is used), every value computation and side effect associated with any argument expression, or with the postfix expression designating the called function, is sequenced before execution of every expression or statement in the body of the called function.
71,037,134
71,040,133
Accessing QObject subclasses from other threads
I need some help understanding the details of accessing QObject subclasses from other threads. From Qt documentation: "If you are calling a function on an QObject subclass that doesn't live in the current thread and the object might receive events, you must protect all access to your QObject subclass's internal data with a mutex; otherwise, you may experience crashes or other undesired behavior." Consider the following classes: // Created on stack in main() => thread affinity = main thread class Model : public QObject { Q_OBJECT public: int getValue() const { return m_value; } signals: void error(QString err); public slots: void incrementValue() { m_value++; }; void threadError(QString err) { emit error(err); } private: std::atomic<int> m_value = 0; } class Thread : public QThread { Q_OBJECT public: Thread(Model* model) : QThread(), m_model(model) {} signals: void incrementValue(); void error(QString err); private: void run() override; // calls m_model->getValue(), emits incrementValue() Model* m_model; }; Also assume that there is a Widget class with a QPushButton that when clicked calls the incrementValue() slot. Thread also occasionally emits the incrementValue signal and this is connected to the incrementValue() slot. There is a potential data race: incrementValue() may be called simultaneously from the main thread by the user clicking the QPushButton as getValue() from a non main thread by Thread::run(). However since the m_value variable is atomic this is safe? I guess it comes down to what constitutes the "QObject subclass's internal data". In my example m_value clearly is internal data. What else? Does the Q_OBJECT macro expand to variables that I need to mutex protect? There is nothing in the above that is specific to QObject. In other words I have the same potential problems with multiple threads as if Model did not inherit from QObject. Qt does not fix my multithread problems in this case for me, but do not either introduce any new problems. Is this correct? To simplify the discussion: both Model and Thread are as pure C++ as possible. I do not use QTimer, QTcpSocket, event loop inside Thread or anything else Qt. Nor do I call moveToThread. The only thing I use Qt for in this context is its signal/slot mechanism (and QString). One possible, but cumbersome, solution that I see is: rewrite Model to NOT subclass QObject. Introduce: class Gui2Model : public QObject { Q_OBJECT public: Gui2Model(Model* model) : m_model(model) {} signals: void error(QString err); public slots: void incrementValue() { m_model->incrementValue(); } void errorSlot(QString err) { emit error(err); } private: Model* m_model; }; Connect the increment QPushButton clicked signal to the Gui2Model::incrementValue() slot. Signal errors from Thread by calling: void Model::error(QString err) { QMetaObject::invokeMethod(m_gui2model, "errorSlot", Qt::QueuedConnection, Q_ARG(QString, err)); } That way I take the full burden of synchronizing Model, but at least it happens according to rules which I (should) know from standard C++.
Is it sufficient to rewrite the m_value variable to be std::atomic? Assuming you join the thread before the model is destroyed, I think yes. There is nothing in the above that is specific to QObject. I think they wanted to stress "the object might receive events" part, which may not be a direct call in your code, but a signal/slot connection. And signal/slot connections would be specific to QObject. In a very twisted scenario, you could have both a signal from you thread and a direct call from your thread, which would create a race condition :-) As a rule it may perhaps be OK to pass const Model* to the Thread object. It should be safe to call const methods on the Model since these do not change the state of the Model? If the model is created const, then yes. Actually, there wouldn't be much choice in such case. But if the model is created non-const, and the value could change from the main thread while accessing it from your thread, then the access to it would still need to be synchronized.
71,037,506
71,037,877
How to assign .editorconfig to a Visual Studio 2019 C++ solution?
I am editing a VS solution that has a different coding style than the one I normally use. I found in the docs that VS 2019 supports EditorConfig: https://learn.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2019 I created .editorconfig file in the root of my solution: I put this in the file: root = true [*.{cpp,hpp,h}] indent_style = space indent_size = 4 I then went to the solution, right clicked the solution Botcraft in the solution explorer, selected Add an existing item... and added the aforementioned file. I can now see the item in the solution: However, when I write if(true) and press enter, I still get two spaces as per my VS settings instead of four as per the editorconfig settings. How to link .editorconfig to visual studio solution and make it respect the settings inside?
EditorConfig files are only applied to the directory they are in and its sub-directories you need to put the file in the same folder as your source code (or a folder above it) not in the same folder as your solution/project files.
71,037,508
71,037,520
C++ macros generating and error which I can't identify
Here I was just practicing on macros and I tried this but it's generating an error, says expecting and ; but it seems right from me. #include <iostream> using namespace std; #define REP(i, a, b) for(int i = a, i <= b; i++) int main() { int i; //REP showing an error REP(i, 0, 6){ cout << "Hello"<< " "; } return 0; }
replace for(int i = a, i <= b; i++) with for(int i = a; i <= b; i++) the ',' symbol after "= a" is wrong, should be semi-colon.
71,037,756
71,074,708
Unrecognized Token C/C++(7) Error in Visual Studio Code
Unrecognized Token C/C++(7) Error in Visual Studio Code I am unsure why I am receiving these error messages; I am trying to compile c++11 code on VSC. Please help? Thank you see code here For example, on Line 7 there is an "Unrecognized Token C/C++(7) Error" : string str = “fine”;
Yes, you are using fancy unicode quotes. It may happen when you copy code from some messenger. Messengers often replace original quotes to that type of quotes.
71,037,914
71,038,321
Serialize array char, int8_t and int16_t in protobuf for C++
In protobuf, how would you serialize an array of char's, (u)int8_t or (u)int16_t? Should the message look like this: message ArrayWithNotSupportedTypes { int32 type = 1; string byte_stream = 2; } where type could store some unique id of the element type stored in the array. And then the byte_stream is populated with contents of an array, where values are of one of the types above? Also,I have seen that there is a type called bytes in protobuf, that is translated to an std::string in the corresponding grpc.pb.h files. Is there any advantage of choosing bytes ahead of string?
If the array size is not big, you can waste some space to make the interface simpler. message ArrayWithNotSupportedTypes { repeated int32 data = 1; // one data entry per one element } If the array size is big, you can use your solution to indicate the type message ArrayWithNotSupportedTypes { enum Type { CHAR = 0; INT8 = 1; INT16 = 2; } optional Type type = 1; optional bytes data = 2; } bytes and string are similar in C++: why protocol buffer bytes is string in c++? Reference: https://developers.google.com/protocol-buffers/docs/proto3#scalar
71,038,331
71,046,789
dyld: Library not loaded despite correct rpath
I am debugging a problem where I am trying to link against a dylib, and set the program's rpath to a directory containing the library. I have narrowed this to the following MWE: > ls deps/include/spinnaker/ AVIRecorder.h Camera.h CameraPtr.h Exception.h …bunch of headers > ls deps/lib/libSpinnaker.dylib* deps/lib/libSpinnaker.dylib deps/lib/libSpinnaker.dylib.1.24.0.60 > cat test.cpp #include <cstddef> #include <Event.h> // for CameraList #include <CameraList.h> // for CameraList #include <CameraPtr.h> // for CameraPtr #include <ImagePtr.h> // for ImagePtr #include <SystemPtr.h> // for SystemPtr int main() { const auto system_ptr = Spinnaker::System::GetInstance(); } I compile this with clang++ -std=c++14 -o wat -I deps/include/spinnaker/ -L deps/lib/ -lSpinnaker -Wl,-rpath,./deps/lib test.cpp And thus libSpinnaker gets referenced as shown by […] Load command 9 cmd LC_UUID cmdsize 24 uuid B4498482-D872-3270-AC47-102914DDBCBE Load command 10 cmd LC_BUILD_VERSION cmdsize 32 platform 1 minos 10.15 sdk 10.15.6 ntools 1 tool 3 version 609.8 Load command 11 cmd LC_SOURCE_VERSION cmdsize 16 version 0.0 Load command 12 cmd LC_MAIN cmdsize 24 entryoff 16224 stacksize 0 Load command 13 cmd LC_LOAD_DYLIB cmdsize 56 name libSpinnaker.dylib.1.24.0.60 (offset 24) time stamp 2 Thu Jan 1 01:00:02 1970 current version 0.0.0 compatibility version 0.0.0 Load command 14 cmd LC_LOAD_DYLIB cmdsize 48 name /usr/lib/libc++.1.dylib (offset 24) time stamp 2 Thu Jan 1 01:00:02 1970 current version 902.1.0 compatibility version 1.0.0 Load command 15 cmd LC_LOAD_DYLIB cmdsize 56 name /usr/lib/libSystem.B.dylib (offset 24) time stamp 2 Thu Jan 1 01:00:02 1970 current version 1281.100.1 compatibility version 1.0.0 Load command 16 cmd LC_RPATH cmdsize 24 path ./deps/lib (offset 12) Load command 17 cmd LC_FUNCTION_STARTS cmdsize 16 dataoff 49312 datasize 8 Load command 18 cmd LC_DATA_IN_CODE cmdsize 16 dataoff 49320 datasize 0 So the LC_RPATH is included, the library is present at the specified path, but still I get dyld: Library not loaded: libSpinnaker.dylib.1.24.0.60 Referenced from: <binary-path> Reason: image not found Abort trap: 6 when running it. Now my observation is that @rpath is missing before the reference to libSpinnaker in the otool output – for other libraries its always there when I look at my larger cmake-based project. I would expect the line name @rpath/libSpinnaker.dylib.1.24.0.60 (offset 24) instead of what i am seeing. I can set DYLD_LIBRARY_PATH and that'll work, but I want to bake this into the binary with the rpath mechanism. Question: Is the fact that @rpath is missing here indicative of a problem? And if so, how can I get it added with the compiler or CMake? If this is not the problem, what is it?
install_name_tool -id @rpath/libSpinnaker.dylib.1.24.0.60 deps/lib/libSpinnaker.dylib.1.24.0.60 install_name_tool -change libSpinnaker.dylib.1.24.0.60 @rpath/libSpinnaker.dylib.1.24.0.60 wat You noticed that the @rpath was missing from the installed name of the library. install_name_tool is the command which allows you to change the installed pathnames, add or remove @rpaths, etc. Because of the modifications, install_name_tool should be used before codesign. Apple documentation has an example of how to setup this type of relative structure.
71,038,566
71,055,711
Does Tuxedo XA transaction manager support ActiveMQ as resource manager for C++ applications?
I am looking for examples or resources to prove support for ActiveMQ as one of the resource managers with Tuxedo as the XA transaction manager. I am working on building a C++ Application to do the same. I am unable to find any documentation on Tuxedo community or Google for the same.
No, it does not support it out of the box. There is a list of resource managers supported in $TUXDIR/udataobj/RM. To support ActiveMQ, you should add an entry in the RM file with the resource manager name, a symbol name that contains pointers to XA functions, and a list of libraries for linking the resource manager. After that, you should be able to build a transaction manager server, see the manual for buildtms command.
71,038,939
71,039,747
Why can't I add or remove a QListWidgetItem?
I have two ListWidget at my ui and I want to move one QListWidgetItem from availableMeasurementsListWidget to selectedMeasurementListWidget But this won't work for me. Nothing adds into selectedMeasurementListWidget and the item does not removes from availableMeasurementsListWidget. Why? That only who works is displaying the text of the qDebug() << item->text(); void ChartSettingsWindow::on_availableMeasurementsListWidget_doubleClicked(const QModelIndex &index) { Q_UNUSED(index); QListWidgetItem *item = ui->availableMeasurementsListWidget->currentItem(); qDebug() << item->text(); ui->selectedMeasurementListWidget->addItem(item); ui->availableMeasurementsListWidget->removeItemWidget(item); }
Note that QListWidget:: removeItemWidget doesn't remove the QListWidgetItem from the QListWidget: it only... Removes the widget set on the given item. To remove an item (row) from the list entirely, either delete the item or use takeItem(). So you probably want something like... auto *available = ui->availableMeasurementsListWidget; auto *selected = ui->selectedMeasurementListWidget; auto *item = available->currentItem(); selected->addItem(available->takeItem(available->indexFromItem(item).row()));
71,039,870
71,040,002
How can I print an array via pointer
Our teacher gave this code and we need to get this code operational. How can I print the values inside of array? cout << wizardsCollection->birthYear; is returns what I gave but wizardsCollection->nameSurname returns empty value. Here's the rest of the code: struct Wizard { string nameSurname; int birthYear; string hairColour; }; struct Wizard *createWizards() { Wizard wizardsCollection[3]; for (int index = 0; index < *(&wizardsCollection + 1) - wizardsCollection; index = index + 1) { wizardsCollection[index].nameSurname = "Name and surname of " + index; wizardsCollection[index].birthYear = 0; wizardsCollection[index].hairColour = "Hair colour of " + index; } return wizardsCollection; } int main() { Wizard *wizardsCollection = createWizards(); cout << wizardsCollection->nameSurname; }
You have a huge problem here. wizardsCollection is created on the stack. As soon as the function returns, that stack memory goes away. Your pointer will be pointing into empty space. You need to use a std::vector for this, to manage the memory. #include <iostream> #include <string> #include <vector> struct Wizard { std::string nameSurname; int birthYear; std::string hairColour; }; void createWizards(std::vector<Wizard> & wizardsCollection) { wizardsCollection.clear(); for (int index = 0; index < 3; index++ ) { wizardsCollection.push_back(Wizard({ "Name and surname of " + std::to_string(index), 0, "Hair colour of " + std::to_string(index) })); } } int main() { std::vector<Wizard> wizardsCollection; createWizards(wizardsCollection); std::cout << wizardsCollection[0].nameSurname << "\n"; } There are other ways to do it, but this models what you had.
71,039,897
71,039,984
How do I explicitely initialize the copy constructor for a class that inherits from std::enable_shared_from_this
Consider the following test code: #include <memory> class C : public std::enable_shared_from_this<C> { public: C(C const& c){} }; int main() { } Compiling this with -Wextra will generate the following warning warning: base class 'class std::enable_shared_from_this' should be explicitly initialized in the copy constructor [-Wextra] How do I do this correctly? Is there anything that I could trip over in more complicated classes?
You can explicitly initialize it by calling its default constructor like this: C(C const& c) : enable_shared_from_this() {} You can also do it by calling its copy constructor like this: C(C const& c) : enable_shared_from_this(c) {} The copy constructor actually does the same thing as the default constructor (it marks the current object as not being owned by a shared_ptr) This ensures that the following will do the sensible thing: C(C const& c) = default; // also calls the copy constructor of the enable_shared_from_this base When an object is copied, you get a new object, so, obviously, it's not owned by the same shared_ptr that the other object is.
71,039,947
71,040,343
Is if(A | B) always faster than if(A || B)?
I am reading this book by Fedor Pikus and he has some very very interesting examples which for me were a surprise. Particularly this benchmark caught me, where the only difference is that in one of them we use || in if and in another we use |. void BM_misspredict(benchmark::State& state) { std::srand(1); const unsigned int N = 10000;; std::vector<unsigned long> v1(N), v2(N); std::vector<int> c1(N), c2(N); for (int i = 0; i < N; ++i) { v1[i] = rand(); v2[i] = rand(); c1[i] = rand() & 0x1; c2[i] = !c1[i]; } unsigned long* p1 = v1.data(); unsigned long* p2 = v2.data(); int* b1 = c1.data(); int* b2 = c2.data(); for (auto _ : state) { unsigned long a1 = 0, a2 = 0; for (size_t i = 0; i < N; ++i) { if (b1[i] || b2[i]) // Only difference { a1 += p1[i]; } else { a2 *= p2[i]; } } benchmark::DoNotOptimize(a1); benchmark::DoNotOptimize(a2); benchmark::ClobberMemory(); } state.SetItemsProcessed(state.iterations()); } void BM_predict(benchmark::State& state) { std::srand(1); const unsigned int N = 10000;; std::vector<unsigned long> v1(N), v2(N); std::vector<int> c1(N), c2(N); for (int i = 0; i < N; ++i) { v1[i] = rand(); v2[i] = rand(); c1[i] = rand() & 0x1; c2[i] = !c1[i]; } unsigned long* p1 = v1.data(); unsigned long* p2 = v2.data(); int* b1 = c1.data(); int* b2 = c2.data(); for (auto _ : state) { unsigned long a1 = 0, a2 = 0; for (size_t i = 0; i < N; ++i) { if (b1[i] | b2[i]) // Only difference { a1 += p1[i]; } else { a2 *= p2[i]; } } benchmark::DoNotOptimize(a1); benchmark::DoNotOptimize(a2); benchmark::ClobberMemory(); } state.SetItemsProcessed(state.iterations()); } I will not go in all the details explained in the book why the latter is faster, but the idea is that hardware branch predictor is given 2 chances to misspredict in slower version and in the | (bitwise or) version. See the benchmark results below. So the question is why don't we always use | instead of || in branches?
Is if(A | B) always faster than if(A || B)? No, if(A | B) is not always faster than if(A || B). Consider a case where A is true and the B expression is a very expensive operation. Not doing the operation can save that expense. So the question is why don't we always use | instead of || in branches? Besides the cases where the logical or is more efficient, the efficiency is not the only concern. There are often operations that have pre-conditions, and there are cases where the result of the left hand operation signals whether the pre-condition is satisfied for the right hand operation. In such case, we must use the logical operator. if (b1[i]) // maybe this exists somewhere in the program b2 = nullptr; if(b1[i] || b2[i]) // OK if(b1[i] | b2[i]) // NOT OK; indirection through null pointer It is this possibility that is typically the problem when the optimiser is unable to replace logical with bitwise. In the example of if(b1[i] || b2[i]), the optimiser can do such replacement only if it can prove that b2 is valid at least when b1[i] != 0. That condition might not exist in your example, but that doesn't mean that it would necessarily be easy or - sometimes even possible - for the optimiser to prove that it doesn't exist. Furthermore, there can be a dependency on the order of the operations, for example if one operand modifies a value read by the other operation: if(a || (a = b)) // OK if(a | (a = b)) // NOT OK; undefined behaviour Also, there are types that are convertible to bool and thus are valid operands for ||, but are not valid operators for |: if(ptr1 || ptr2) // OK if(ptr1 | ptr2) // NOT OK; no bitwise or for pointers TL;DR If we could always use bitwise or instead of logical operators, then there would be no need for logical operators and they probably wouldn't be in the language. But such replacement is not always a possibility, which is the reason why we use logical operators, and also the reason why optimiser sometimes cannot use the faster option.
71,040,175
71,040,950
CMake nested OBJECT library dependencies
I created a project with some nested library dependencies using the OBJECT library type. The motivation for this is to avoid link order issues with static libraries. I have a simple directory structure as follows: ├── bar │ ├── bar.c │ └── bar.h ├── foo │ ├── foo.c │ └── foo.h ├── main.c └── CMakeLists.txt foo depends on bar, and main depends on foo. For example, bar.c #include "bar.h" #include <stdio.h> void bar(void) { printf("woot woot\n"); } foo.c #include "foo.h" #include "bar.h" void foo(void) { bar(); } main.c #include "foo.h" int main() { foo(); return 0; } The CMakeLists.txt cmake_minimum_required(VERSION 3.18) project(myproj) enable_language(C ASM) set(CMAKE_C_STANDARD 11) set(CMAKE_C_STANDARD_REQUIRED ON) set(CMAKE_C_EXTENSIONS OFF) # build bar add_library(bar OBJECT ${PROJECT_SOURCE_DIR}/bar/bar.c) target_include_directories(bar PUBLIC ${PROJECT_SOURCE_DIR}/bar) # build foo, depends on bar add_library(foo OBJECT ${PROJECT_SOURCE_DIR}/foo/foo.c) target_include_directories(foo PUBLIC ${PROJECT_SOURCE_DIR}/foo) target_link_libraries(foo PUBLIC bar) # build executable, depends on foo add_executable(myexe ${PROJECT_SOURCE_DIR}/main.c) target_link_libraries(myexe PUBLIC foo) My expectation is that myexe would inherit the bar dependency from foo when it links to it. However, this is not the case it seems. When the code is compiled, main.o only links to foo.o, and thus there is an undefined reference to bar. However, if I change the library types from OBJECT to STATIC everything works fine. Why does this happen?
Object libraries cannot be chained this way. You must link directly (not transitively) to an object library to acquire its object files. As it says in the documentation, Object Libraries may "link" to other object libraries to get usage requirements, but since they do not have a link step nothing is done with their object files. [...] In other words, when Object Libraries appear in a target's INTERFACE_LINK_LIBRARIES property they will be treated as Interface Libraries, but when they appear in a target's LINK_LIBRARIES property their object files will be included in the link too. I agree it defies all reason, though. However, you can manually propagate the object files via target_link_libraries(INTERFACE) and the $<TARGET_OBJECTS> generator expression as of 3.21 (doing so was buggy in earlier versions, and the even-hacker target_sources may be used in earlier versions, too). Do note that this is a bit of a hack, since there are some cases that will break. Notably, if a library target links to such a target publicly, then the object files will propagate again. So... be careful. Still, here's a corrected version of your example build: cmake_minimum_required(VERSION 3.21) project(myproj LANGUAGES C ASM) set(CMAKE_C_STANDARD 11 CACHE STRING "The C standard to use") option(CMAKE_C_STANDARD_REQUIRED "Enforce strict C standard selection" ON) option(CMAKE_C_EXTENSIONS "Allow compiler-specific C extensions" OFF) # build bar add_library(bar OBJECT bar/bar.c) target_include_directories( bar PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/bar>" ) # build foo, depends on bar add_library(foo OBJECT foo/foo.c) target_include_directories( foo PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/foo>" ) target_link_libraries(foo PUBLIC bar "$<TARGET_OBJECTS:bar>") # build executable, depends on foo add_executable(myexe main.c) target_link_libraries(myexe PRIVATE foo) At the command line: $ cmake -G Ninja -S . -B build ... $ cmake --build build -- -nv [1/4] /usr/bin/cc -I/path/to/bar -std=c11 -MD -MT CMakeFiles/bar.dir/bar/bar.c.o -MF CMakeFiles/bar.dir/bar/bar.c.o.d -o CMakeFiles/bar.dir/bar/bar.c.o -c /path/to/bar/bar.c [2/4] /usr/bin/cc -I/path/to/foo -I/path/to/bar -std=c11 -MD -MT CMakeFiles/foo.dir/foo/foo.c.o -MF CMakeFiles/foo.dir/foo/foo.c.o.d -o CMakeFiles/foo.dir/foo/foo.c.o -c /path/to/foo/foo.c [3/4] /usr/bin/cc -I/path/to/foo -I/path/to/bar -std=c11 -MD -MT CMakeFiles/myexe.dir/main.c.o -MF CMakeFiles/myexe.dir/main.c.o.d -o CMakeFiles/myexe.dir/main.c.o -c /path/to/main.c [4/4] : && /usr/bin/cc CMakeFiles/foo.dir/foo/foo.c.o CMakeFiles/myexe.dir/main.c.o -o myexe CMakeFiles/bar.dir/./bar/bar.c.o && :
71,040,243
71,040,693
Which memory barriers are minimally needed for updating array elements with greater values?
What would be the minimally needed memory barriers in the following scenario? Several threads update the elements of an array int a[n] in parallel. All elements are initially set to zero. Each thread computes a new value for each element; then, it compares the computed new value to the existing value stored in the array, and writes the new value only if it is greater than the stored value. For example, if a thread computes for a[0] a new value 5, but a[0] is already 10, then the thread should not update a[0]. But if the thread computes a new value 10, and a[0] is 5, then the thread must update a[0]. The computation of the new values involves some shared read-only data; it does not involve the array at all. While the above-mentioned threads are running, no other thread accesses the array. The array is consumed later, after all the threads are guaranteed to finish their updates. The implementation uses a compare-and-swap loop, wrapping the elements into atomic_ref (either from Boost or from C++20): for (int k = 0; k != n; ++k) // For each element of the array { // Locally in this thread, compute the new value for a[k]. int new_value = ComputeTheNewValue(k); // Establish atomic access to a[k]. atomic_ref<int> memory(a[k]); // [Barrier_0]: Read the existing value. int existing_value = memory.load(memory_order_relaxed); while (true) // The compare-and-swap loop. { // Overwrite only with higher values. if (new_value <= existing_value) break; // Need to update a[k] with the higher value "new_value", but // only if a[k] still stores the "existing_value". if (memory.compare_exchange_weak(existing_value, new_value, /*Barrier_1*/ memory_order_relaxed, /*Barrier_2*/ memory_order_relaxed)) { // a[k] was still storing "existing_value", and it has been // successfully updated with the higher "new_value". // We're done, and we may exit the compare-and-swap loop. break; } else { // We get here in two cases: // 1. a[k] was found to store a value different from "existing_value", or // 2. the compare-and-swap operation has failed spuriously. // In the first case, the new value stored in a[k] has been loaded // by compare_exchange_weak() function into the "existing_value" variable. // Then, we need to compare the "new_value" produced by this thread // with the newly loaded "existing_value". This is achieved by simply continuing the loop. // The second case (the spurious failure) is also handled by continuing the loop, // although in that case the "new_value <= existing_value" comparison is redundant. continue; } } } This code involves three memory barriers: Barrier_0 in memory.load(). Barrier_1, to use in read-modify-write when compare_exchange_weak() succeeds. Barrier_2, to use in load operation when compare_exchange_weak() fails. In this scenario, is the code guaranteed to update only with higher values when all three bariers are set to relaxed? If not, what minimal barriers are needed to guarantee the corrrect behavior?
Relaxed is fine, you don't need any ordering wrt. access to any other elements during the process of updating. And for accesses to the same location, ISO C++ guarantees that a "modification order" exists for each location separately, and that even relaxed operations will only see the same or later values in the modification order of the location between loaded or RMWed. You're just building an atomic fetch_max primitive out of a CAS retry loop. Since the other writers are doing the same thing, the value of each location is monotonically increasing. So it's totally safe to bail out any time you see a value greater than the new_value. For the main thread to collect the results at the end, you do need release/acquire synchronization like thread.join or some kind of flag. (e.g. maybe fetch_sub(1, release) of a counter of how many threads still have work left to do, or an array of done flags so you can just do a pure store.) BTW, this seems likely to be slow, with lots of time spent waiting for cache lines to bounce between cores. (Lots of false-sharing.) Ideally you you can efficiently change this to have each thread work on different parts of the array (e.g. computing multiple candidates for the same index so it doesn't need any atomic stuff). I cannot guarantee that the computed indices do not overlap. In practice, the overlapping is usually small, but it cannot be eliminated. So apparently that's a no. And if the indices touched by different threads are in different cache lines (chunk of 16 int32_t) then there won't be too much false sharing. (Also, if computation is expensive so you aren't producing values very fast, that's good so atomic updates aren't what your code is spending most of its time on.) But if there is significant contention and the array isn't huge, you could give each thread its own output array, and collect the results at the end. e.g. have one thread do a[i] = max(a[i], b[i], c[i], d[i]) for 4 to 8 arrays per loop. (Not too many read streams at once, and not a variable number of inputs because that probably couldn't compile efficiently). This should benefit from SIMD, e.g. SSE4.1 pmaxsd doing 4 parallel max operations, so this should be limited mostly by L3 cache bandwidth. Or divide the max work between threads as a second parallel phase, with each thread doing the above over part of the output array. Or have the thread_id % 4 == 0 reduce results from itself and the next 3 threads, so you have a tree of reductions if you have a system with many threads.
71,040,349
71,069,950
Location of the error token always starts at 0
I'm writing a parser with error handling. I would like to output to the user the exact location of the parts of the input that couldn't be parsed. However, the location of the error token always starts at 0, even if before it were parts that were parsed successfully. Here's a heavily simplified example of what I did. (The problematic part is probably in the parser.yy.) Location.hh: #pragma once #include <string> // The full version tracks position in bytes, line number and offset in the current line. // Here however, I've shortened it to line number only. struct Location { int beginning, ending; operator std::string() const { return std::to_string(beginning) + '-' + std::to_string(ending); } }; LexerClass.hh: #pragma once #include <istream> #include <string> #if ! defined(yyFlexLexerOnce) #include <FlexLexer.h> #endif #include "Location.hh" class LexerClass : public yyFlexLexer { int currentPosition = 0; protected: std::string *yylval = nullptr; Location *yylloc = nullptr; public: LexerClass(std::istream &in) : yyFlexLexer(&in) {} [[nodiscard]] int yylex(std::string *const lval, Location *const lloc); void onNewLine() { yylloc->beginning = yylloc->ending = ++currentPosition; } }; lexer.ll: %{ #include "./parser.hh" #include "./LexerClass.hh" #undef YY_DECL #define YY_DECL int LexerClass::yylex(std::string *const lval, Location *const lloc) %} %option c++ noyywrap %option yyclass="LexerClass" %% %{ yylval = lval; yylloc = lloc; %} [[:blank:]] ; \n { onNewLine(); } [0-9] { return yy::Parser::token::DIGIT; } . { return yytext[0]; } parser.yy: %language "c++" %code requires { #include "LexerClass.hh" #include "Location.hh" } %define api.parser.class {Parser} %define api.value.type {std::string} %define api.location.type {Location} %parse-param {LexerClass &lexer} %defines %code { template<typename RHS> void calcLocation(Location &current, const RHS &rhs, const int n); #define YYLLOC_DEFAULT(Cur, Rhs, N) calcLocation(Cur, Rhs, N) #define yylex lexer.yylex } %token DIGIT %% numbers: %empty | numbers number ';' { std::cout << std::string(@number) << "\tnumber" << std::endl; } | error ';' { yyerrok; std::cerr << std::string(@error) << "\terror context" << std::endl; } ; number: DIGIT {} | number DIGIT {} ; %% #include <iostream> template<typename RHS> inline void calcLocation(Location &current, const RHS &rhs, const int n) { current = (n <= 1) ? YYRHSLOC(rhs, n) : Location{YYRHSLOC(rhs, 1).beginning, YYRHSLOC(rhs, n).ending}; } void yy::Parser::error(const Location &location, const std::string &message) { std::cout << std::string(location) << "\terror: " << message << std::endl; } int main() { LexerClass lexer(std::cin); yy::Parser parser(lexer); return parser(); } For the input: 123 456 789; 123; 089 xxx 123; 765 432; expected output: 0-2 number 3-3 number 5-5 error: syntax error 4-6 error context 7-8 number actual output: 0-2 number 3-3 number 5-5 error: syntax error 0-6 error context 7-8 number
I'm building upon the rici's answer, so read that one first. Let's consider the rule: numbers: %empty | numbers number ';' | error ';' { yyerrok; } ; This means the nonterminal numbers can be one of these three things: It may be empty. It may be a number preceded by any valid numbers. It may be an error. Do you see the problem yet? The whole numbers has to be an error, from the beginning; there is no rule saying that anything else allowed before it. Of course Bison obediently complies to your wishes and makes the error start at the very beginning of the nonterminal numbers. It can do that because error is a jack of all trades and there can be no rule about what can be included inside of it. Bison, to fulfill your rule, needs to extend the error over all previous numbers. When you understand the problem, fixing it is rather easy. You just need to tell Bison that numbers are allowed before the error: numbers: %empty | numbers number ';' | numbers error ';' { yyerrok; } ; This is IMO the best solution. There is another approach, though. You can move the error token to the number: numbers: %empty | numbers number ';' { yyerrok; } ; number: DIGIT | number DIGIT | error ; Notice that yyerrok needs to stay in numbers because the parser would enter an infinite loop if you place it next to a rule that ends with token error. A disadvantage of this approach is that if you place an action next to this error, it will be triggered multiple times (more or less once per every illegal terminal). Maybe in some situations this is preferable but generally I suggest using the first way of solving the issue.
71,040,425
71,040,567
SFINAE not working with member function of template class
I have a template class where I would like to remove a member function if the type satisfies some condition, that, as far as I understand, should be a very basic usage of SFINAE, for example: template<class T> class A { public: template<typename = typename std::enable_if<std::is_floating_point<T>::value>::type> T foo () { return 1.23; } }; However, this is results in an error "no type named 'type'", like SFINAE was not going on. This however works if foo is a function not member of a class. What is wrong with this implementation?
You're missing a dependent name for the compiler to use for SFINAE. Try something like this instead: #include <type_traits> template<class T> class A { public: template<typename Tp = T> typename std::enable_if<std::is_floating_point<Tp>::value, Tp>::type foo () { return 1.23; } }; int main() { A<double> a; a.foo(); } If the type T is not floating point, the declaration would be malformed (no return type) and the function would not be considered for the overload set. See it on godbolt.
71,040,975
71,144,383
Build and run a Qt application on macOS via Bazel
I tried to build and run a Qt5 (5.15.2) application on macOS (10.15.7) using Bazel 5.0.0. Unfortunately, I run into some problems. The building part seems to work, but not the run part. I installed Qt5 on my machine using Homebrew: brew install qt@5 brew link qt@5 I adapted https://github.com/justbuchanan/bazel_rules_qt/ to my needs. See this PR. When I try to run: bazel run --cxxopt=-std=c++17 //tests/qt_resource:main I receive the runtime error: dyld: Symbol not found: __ZN10QByteArray6_emptyE Steps to reproduce the issue: # brew install bazel # Install Bazel # brew install qt@5 # Install Qt5 git clone https://github.com/Vertexwahn/bazel_rules_qt.git cd bazel_rules_qt git checkout add-macos-support bazel build --cxxopt=-std=c++17 //... # should work bazel run --cxxopt=-std=c++17 //tests/qt_resource:main # should give you the error message Nevertheless, building everything using bazel build --cxxopt=-std=c++17 //... seems to work. I am not 100% sure if the link options -F/usr/local/opt/qt5/Frameworks and -framework QtCore, etc. are correct. Maybe someone can confirm this. Did I use the correct link options? For me, it is a bit unclear what dependencies the main binary expects. I tried to copy QtCore.framework to the location of the main binary manually but this does not change the error message. What files does the main binary expect? If I try to run macdeployqt on my main binary I get also some errors. I do within my workspace root dir a cd bazel-bin/tests/qt_resource and run then /usr/local/opt/qt5/bin/macdeployqt main: ERROR: Could not find bundle binary for "main" ERROR: "error: /Library/Developer/CommandLineTools/usr/bin/otool-classic: can't open file: (No such file or directory)\n" ERROR: "error: /Library/Developer/CommandLineTools/usr/bin/otool-classic: can't open file: (No such file or directory)\n" ERROR: "error: /Library/Developer/CommandLineTools/usr/bin/otool-classic: can't open file: (No such file or directory)\n" WARNING: WARNING: Could not find any external Qt frameworks to deploy in "main" WARNING: Perhaps macdeployqt was already used on "main" ? WARNING: If so, you will need to rebuild "main" before trying again. ERROR: Could not find bundle binary for "main" ERROR: "error: /Library/Developer/CommandLineTools/usr/bin/strip: can't open file: (No such file or directory)\n" ERROR: "" My hope was that macdeployqt would collect all needed resources for me. Any idea why this is not working? How can macdeployqt be used to collect all needed dependencies for the main binary? If I convert my main to an app via lipo -create -output universall_app main and do then a /usr/local/opt/qt5/bin/macdeployqt universall_app I get the same error message. The CMake approach To make sure that there is no general problem with my system setup I tried to use CMake to build a Qt5 application: git clone https://github.com/euler0/mini-cmake-qt.git cmake -DCMAKE_PREFIX_PATH=/usr/local/opt/qt5 . make -j This produces an example.app. With a double click on this application bundle, the application can be started. This worked on my system. Future directions It seems that rules_apple can be used to create an application bundle. I am not sure if I need to transform my Qt application binary to an app bundle to be able to execute it. One could use --sandbox_debugto identify what Bazel is doing and dtruss for the CMake version to compare the differences. I am currently not sure what trying to do next and hope for an easy solution. I am also fine with a Qt6 solution. Update: Alternative Answer It would also be helpful if someone can point out how to build a minimal Qt application using make only on macOS and a brew installed Qt5 or tell me what the linker and compiler options must look like.
I followed your steps with Mac OSX 10.15.7, Qt (installed by homebrew) 5.15.1 and both bazel 4.2.2-homebrew and 5.0.0-homebrew and initially I could not build the project from git: * 3fe5f6c - (4 weeks ago) Add macOS support — Vertexwahn (HEAD -> add-macos-support, origin/add-macos-support) This is the result that I get when building: % bazel build --cxxopt=-std=c++17 //... DEBUG: /private/var/tmp/_bazel_home/761aafaa2237a9607dd915f1f52bca3e/external/com_justbuchanan_rules_qt/qt_configure.bzl:43:14: Installation available on the default path: /usr/local/opt/qt5 INFO: Analyzed 14 targets (0 packages loaded, 0 targets configured). INFO: Found 14 targets... ERROR: /Users/home/Git/my_repo/bazel_rules_qt/tests/qt_qml/BUILD:4:10: Compiling tests/qt_qml/main.cc failed: (Aborted): wrapped_clang failed: error executing command external/local_config_cc/wrapped_clang '-D_FORTIFY_SOURCE=1' -fstack-protector -fcolor-diagnostics -Wall -Wthread-safety -Wself-assign -fno-omit-frame-pointer -O0 -DDEBUG '-std=c++11' ... (remaining 38 argument(s) skipped) Use --sandbox_debug to see verbose messages from the sandbox tests/qt_qml/main.cc:1:10: fatal error: 'QtQml/QQmlApplicationEngine' file not found #include <QtQml/QQmlApplicationEngine> ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1 error generated. Error in child process '/usr/bin/xcrun'. 1 INFO: Elapsed time: 0,594s, Critical Path: 0,32s INFO: 3 processes: 3 internal. FAILED: Build did NOT complete successfully After playing around with headers and include paths in qt.BUILD: diff --git a/qt.BUILD b/qt.BUILD index 517c8db..8f110b5 100644 --- a/qt.BUILD +++ b/qt.BUILD @@ -28,11 +28,12 @@ QT_LIBRARIES = [ cc_library( name = "qt_%s_osx" % name, # When being on Windows this glob will be empty - hdrs = glob(["%s/**" % include_folder], allow_empty = True), + hdrs = glob(["include/%s/**" % include_folder], allow_empty = True), includes = ["."], linkopts = ["-F/usr/local/opt/qt5/lib"] + [ "-framework %s" % library_name.replace("5", "") # macOS qt libs do not contain a 5 - e.g. instead of Qt5Core the lib is called QtCore ], + strip_include_prefix= "include" # Available from Bazel 4.0.0 # target_compatible_with = ["@platforms//os:osx"], ) I could build and run the project: % bazel build --cxxopt=-std=c++17 //... DEBUG: /private/var/tmp/_bazel_home/761aafaa2237a9607dd915f1f52bca3e/external/com_justbuchanan_rules_qt/qt_configure.bzl:43:14: Installation available on the default path: /usr/local/opt/qt5 INFO: Analyzed 14 targets (1 packages loaded, 7422 targets configured). INFO: Found 14 targets... INFO: Elapsed time: 11,761s, Critical Path: 7,23s INFO: 3 processes: 1 internal, 2 darwin-sandbox. INFO: Build completed successfully, 3 total actions % bazel run --cxxopt=-std=c++17 //tests/qt_resource:main DEBUG: /private/var/tmp/_bazel_home/761aafaa2237a9607dd915f1f52bca3e/external/com_justbuchanan_rules_qt/qt_configure.bzl:43:14: Installation available on the default path: /usr/local/opt/qt5 INFO: Analyzed target //tests/qt_resource:main (0 packages loaded, 0 targets configured). INFO: Found 1 target... Target //tests/qt_resource:main up-to-date: bazel-bin/tests/qt_resource/main INFO: Elapsed time: 3,657s, Critical Path: 0,00s INFO: 1 process: 1 internal. INFO: Build completed successfully, 1 total action INFO: Build completed successfully, 1 total action opened resource file file1 Related to your question whether the linker options are correct -F/usr/local/opt/qt5/Frameworks -framework QtCore Yes they are correct, you could alternatively use -F/usr/local/opt/qt5/lib (as you are already using in qt.BUILD) as all the files under the Frameworks folder are links to the lib folder. With macdeployqt and lipo I get the same results as in the OP even after the test is running successfully.
71,040,977
71,041,026
Differrent results in different compilers c++
I have created the following program: #include <iostream> int main(){ int a,b,mod, a1,b1; std::cin >> a >> b; if(a >= b){ mod = a % b; } else { mod = b % a; } if(mod == 0){ std::cout << a; } else { while(a1 != 0 && b1 != 0){ a1 = a % mod; b1 = b % mod; --mod; } std::cout << mod + 1; } return 0; } I have tested with the following input: 25 27 and got result 1 (as expected). But in another compiler I got result 3 and unfortunately I don't have an access to testing with another compiler(only the final result). I don't know why and where the behaviour of my program is inconsistent.
a1 and b1 is not initialized by correct numbers. If you set correct initial version, you should get consistent behavior.
71,040,986
71,041,166
Upgrade from VS2015 to VS2022: Error LNK1104 cannot open file 'msvcprtd.lib'
I am trying to upgrade a project from VS2015 to VS2022 and getting the following error: Error LNK1104 cannot open file 'msvcprtd.lib' When I compile it as 2015 project, it works, but once I switch it to 2022, it fails.
In my case, I needed to select the checkmark 'Inherit from parent or project defaults' in library directories I created a new empty project and compared the library settings with my older project to see what was the difference.
71,041,077
71,041,529
CMAKE_CXX_SOURCE_FILE_EXTENSIONS not working with thrust/cuda
Thrust allows for one to specify different backends at cmake configure time via the THRUST_DEVICE_SYSTEM flag. My problem is that I have a bunch of .cu files that I want to be compiled as regular c++ files when a user runs cmake with -DTHRUST_DEVICE_SYSTEM=OMP (for example). If I change the extension of the .cu files to .cpp they compile fine (indicating that I just need tell cmake to use the c++ compiler on the .cu files). But if I add .cu to CMAKE_CXX_SOURCE_FILE_EXTENSIONS then I get a CMake Error: Cannot determine link language for target "cuda_kernels". Here's a minimal cmake example: cmake_minimum_required(VERSION 3.19) project(kernels LANGUAGES C CXX Fortran) set(KERNELS_USE_OMP OFF) if ("${THRUST_DEVICE_SYSTEM}" STREQUAL "OMP") set(KERNELS_USE_OMP ON) endif() # verify CUDA support include(CheckLanguage) check_language(CUDA) if (CMAKE_CUDA_COMPILER AND NOT KERNELS_USE_OMP) enable_language(CUDA) else() list(PREPEND CMAKE_CXX_SOURCE_FILE_EXTENSIONS "cu;CU") endif() message(STATUS "${CMAKE_CXX_SOURCE_FILE_EXTENSIONS}") find_package(Thrust REQUIRED CONFIG) thrust_create_target(Thrust FROM_OPTIONS) add_library(cuda_kernels my_kernels.cu) target_link_libraries(cuda_kernels Thrust) The output of the message command on my system is: -- cu;CU;C;M;c++;cc;cpp;cxx;mm;mpp;CPP;ixx;cppm Why is cmake not respecting my CMAKE_CXX_SOURCE_FILE_EXTENSIONS changes?
Why is cmake not respecting my CMAKE_CXX_SOURCE_FILE_EXTENSIONS changes? The extension-to-language for <LANG> is set as soon as <LANG> is enabled by inspecting the value of the CMAKE_<LANG>_SOURCE_FILE_EXTENSIONS variable when the language detection module exits. Unfortunately, there is no blessed way to override this list for CXX as it is hard-coded in Modules/CMakeCXXCompiler.cmake.in. Perhaps the best way of working around the actual error would be to use the LANGUAGE source file property to tell CMake how to compile the individual CUDA files, like so: cmake_minimum_required(VERSION 3.19) project(kernels LANGUAGES CXX) find_package(Thrust REQUIRED) thrust_create_target(Thrust FROM_OPTIONS) thrust_is_cuda_system_found(USE_CUDA) if (USE_CUDA) enable_language(CUDA) endif() set(cuda_kernel_sources my_kernels.cu) add_library(cuda_kernels ${cuda_kernel_sources}) target_link_libraries(cuda_kernels PRIVATE Thrust) if (NOT USE_CUDA) set_source_files_properties( ${cuda_kernel_sources} PROPERTIES LANGUAGE CXX ) endif () This will certainly be friendlier to other projects that might try to add_subdirectory yours. However, if we want to be very naughty, we can do this: cmake_minimum_required(VERSION 3.19) project(kernels LANGUAGES NONE) ### # Hacky language extension override function(add_cuda_extensions variable access value current_list_file stack) if (NOT cu IN_LIST value) list(PREPEND "${variable}" "cu" "CU") set("${variable}" "${${variable}}" PARENT_SCOPE) endif () endfunction() # verify CUDA support include(CheckLanguage) check_language(CUDA) if (CMAKE_CUDA_COMPILER AND NOT THRUST_DEVICE_SYSTEM STREQUAL "OMP") enable_language(CUDA) enable_language(CXX) else() variable_watch(CMAKE_CXX_SOURCE_FILE_EXTENSIONS add_cuda_extensions) enable_language(CXX) endif() ### # Normal project code starts here message(STATUS "${CMAKE_CXX_SOURCE_FILE_EXTENSIONS}") find_package(Thrust REQUIRED) thrust_create_target(Thrust FROM_OPTIONS) add_library(cuda_kernels my_kernels.cu) target_link_libraries(cuda_kernels PRIVATE Thrust) This waits for the platform module to try to write CMAKE_CXX_SOURCE_FILE_EXTENSIONS and then any time it's accessed, quickly inserts the cu and CU extensions to the list.
71,041,135
71,041,227
Why does this test fail if someone else runs it at the same time?
I was watching a conference talk (No need to watch it to understand my question but if you're curious it's from 35m28s to 36m28s). The following test was shown: TEST(Foo, StorageTest){ StorageServer* server = GetStorageServerHandle(); auto my_val = rand(); server -> Store("testKey", my_val); EXPECT_EQ(my_val, server->Load("testKey")); } One of the speakers said: "you can only expect that storing data to a production service works if only one copy of that test is running at a time." The other speaker said: "Once you add continuous integration in the mix, the test starts failing". I don't know a lot about CI/CD. I am having some trouble understanding both claims 1. and 2. Any help?
One of the speakers said: "you can only expect that storing data to a production service works if only one copy of that test is running at a time." Right. Imagine if two instances of this code are running. If both Store operations execute before either Load operation takes place, the one whose Store executed first will load the wrong value. Consider this pattern where the two instances are called "first" and "second": First Store executes, stores first random value. Second Store starts executing, starts storing second random value. First Load is blocked on the second Store completing due to a lock internal to the database Second Load is blocked on the Store completing due to a local internal to the database. Second Store finishes and release the internal lock. First Load can now execute, it gets second random value. EXPECT_EQ fails as the first and second random values are different. The other speaker said: "Once you add continuous integration in the mix, the test starts failing". If a CI system is testing multiple instances of the code at the same time, race conditions like the example above can occur and cause tests to fail as the multiple instances race with each other.
71,041,528
71,043,428
How to make external dependencies on a shared items project in VS?
I am in need of sharing some header files between two different projects. So I created a shared items project, and now I can't figure out how to add external dependencies to it, so I could use includes from the WDK 10 shared folder. Did anyone run into this problem before? I can still add external dependencies on a library project, but somehow not on shared items.
As the article says These “shared items” projects don’t participate in build but they can contain any number of C++ headers and sources. And you need to add the dependencies to the actual build project.
71,041,798
71,041,854
How to convert from any type to std::string in C++
I'm making a LinkedList class using template, since I want to use it for whatever type I need afterwards template <typename T> class LinkedList {} I'm trying to make a function that adds all the elements of a list into a string: std::string join(const char *seperator) { std::string str; auto curr = this->head; while (curr) { str += std::to_string(curr->value); if (curr->next) str += seperator; curr = curr->next; } return str; } It works with the types I tested (int, double, float...) but doesn't work with std::string, the to_string() function generates an error Error C2665 'std::to_string': none of the 9 overloads could convert all the argument types I assume it doesn't work with other types. so, can you provide a general method to convert from any type to std::string.
There is no universal way to convert an object of arbitrary type to a string in C++. But the most commonly supported facility for outputting data as strings are output streams. So, you could use std::ostringstream like this: std::string join(const char *seperator) { std::ostringstream strm; auto curr = this->head; while (curr) { strm << curr->value; if (curr->next) strm << seperator; curr = curr->next; } return strm.str(); } Note that for this to work the type T should provide an operator<< overload that takes std::ostream& as the first argument. All arithmetic types, C-style strings and std::string are supported by this facility, but not all user-defined types may be.
71,042,002
71,042,061
Confusion about this pointer and callback functions
Let's say I have the following scenario where I define a callback function m_deleter. class B { public: B() = default; ~B(){ if (m_deleter) { m_deleter(); } } std::function<void()> m_deleter = nullptr; }; class A { public: void createB(B& b) { auto func = [this]() { this->printMessage(); }; b.m_deleter = func; } void printMessage() { std::cout << "Here is the message!" << std::endl; } }; And here is our main function: int main() { B b; { A a; a.createB(b); } // a falls out of scope. } Here is my confusion. When the stack instance a falls out of scope, is the memory not deallocated? How can the this pointer, used here in the callback: this->printMessage(); still point to a valid object? When I run the above program, it prints: Here is the message! Edit: Follow up question, is there any way for b to know that a has fallen out of scope and is no longer a valid object, and therefore should not call the callback?
It doesn't. But due to the fact that in the method printMessage you don't reference any fields from the class A, there is no crush. This is an UB however. Here is the code that avoids this issue but demonstrates the correct behavior: class A { public: void createB(B& b) { auto func = []() { A::printMessage(); }; b.m_deleter = func; } static void printMessage() { std::cout << "Here is the message!" << std::endl; } }; No pointer, no references to any field, no need to track whether the instance is valid, no UB. If you need to access the data from A, you need a valid instance.
71,042,135
71,042,176
Is `-ftree-slp-vectorize` not enabled by `-O2` in GCC?
From https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html It says "-ftree-slp-vectorize: Perform basic block vectorization on trees. This flag is enabled by default at -O2 and by -ftree-vectorize, -fprofile-use, and -fauto-profile." However it seems I have to pass a flag explicitly to turn on SIMD. Did I mis undertand something here? It is enabled at -O3 though. https://www.godbolt.org/z/1ffzdqMoT
Is -ftree-slp-vectorize not enabled by -O2 in GCC? Yes and no. It depends on the version of the compiler. From https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html You have linked to the latest version of documentation. It applies to the version that is currently under development, which at the moment is version 12. However it seems I have to pass a flag explicitly to turn on SIMD. https://www.godbolt.org/z/1ffzdqMoT Your example uses GCC version 11. Did I mis undertand something here? You read the wrong version of documentation, or used wrong version of compiler and hence your assumption didn't hold.
71,042,377
71,042,568
What is the proper design pattern for a callback in destructor which uses a pointer which may or may not point to valid object?
Let's say we have the following scenario. We have a ImageManager class which is used to internally store and manage image data. The ImageManager class has a public member populateImage, which will read an image into memory, then return a populated MyImage which is a std::shared_ptr around an Image object. This object will contain a uuid which maps to the image data which is managed by ImageManager. Finally, we define a callback function which gets called in the Image destructor and properly cleans up the image data stored by the ImageManager. Here is the example: #include <functional> #include <vector> #include <unordered_map> #include <memory> class Image { public: Image() = default; ~Image(){ if (m_deleter) { m_deleter(); } } private: friend class ImageManager; std::function<void()> m_deleter = nullptr; unsigned int m_uuid; }; using MyImage = std::shared_ptr<Image>; class ImageManager { public: void removeImage(unsigned int uuid) { auto iter = m_imageMap.find(uuid); if (iter == m_imageMap.end()) { throw std::runtime_error("Unable to find image for UUID: " + std::to_string(uuid)); } m_imageMap.erase(iter); } void populateImage(MyImage& image) { image = std::make_shared<Image>(); static unsigned int uuid = 0; ++uuid; image->m_uuid = uuid; auto img = std::vector<uint8_t>(1000, 0); m_imageMap[uuid] = img; unsigned int currentUUID = uuid; auto callbackFunc = [this, currentUUID]() { this->removeImage(currentUUID); }; image->m_deleter = callbackFunc; } private: std::unordered_map<unsigned int, std::vector<uint8_t>> m_imageMap; }; The issues arise when our instance of the ImageManager falls out of scope before our instances of Image, for example in the following driver code: int main() { MyImage img1, img2; { ImageManager manager; manager.populateImage(img1); manager.populateImage(img2); } } Running this program prints: terminate called after throwing an instance of 'std::runtime_error' what(): Unable to find image for UUID: 2 But ultimately I understand that this is undefined behavior as the this pointer in m_deleter no longer points to a valid object. What is the proper design pattern in order to avoid this problem?
Overall the design smells. If the ImageManager is a local object, and MyImage are outside of the scope, why do you need to delete the items in the map? Anyway, I promised you to show the shared/weak idiom. Wrap the map into a shared_ptr. That would mean that the map will be destroyed together with the ImageManager (if you wouldn't copy this shared pointer): std::shared_ptr<std::unordered_map<unsigned int, cv::Mat>> m_imageMap; Store a weak pointer in the lambda: std::weak_ptr<std::unordered_map<unsigned int, cv::Mat>> weakPtr = m_imageMap; auto callbackFunc = [weakPtr, uuid]() { auto imageMap = weakPtr.lock(); if (imageMap) auto iter = imageMap.find(uuid); if (iter == imageMap.end()) { throw std::runtime_error("Unable to find image for UUID: " + std::to_string(uuid)); } imageMap.erase(iter); } }; image->m_deleter = callbackFunc; Weak pointer will know whether the shared pointer counterpart is destroyed or not. Keep in mind that you shouldn't use std::make_shared in this case: otherwise the memory associated with the map will be freed only when the last image is destroyed.
71,042,417
71,042,450
"Undefined symbol" error with my functions when using classes
I'm writing a program that calculates the area and diameter using classes and functions. My issue is that I'm getting an undefined symbol error with my functions. I'm sure it's probably an easy fix ... I just can't figure it out. (Writing the code on a mac) Here's the code: #include<iostream> using namespace std; class Circle { public: int radius; void printArea(); void printDiameter(); }; void Circle::printArea() { double area; area = radius * radius * 3.14159; cout<<"A circle with radius "<<radius<<" has an area of "<<area<<endl; } void Circle::printDiameter() { int diam; diam = radius * 2; cout<<"A circle with radius "<<radius<<" has a diameter of "<<diam<<endl; } int main() { void printArea(Circle); void printDiameter(Circle); Circle aBigCircle, aLittleCircle; aBigCircle.radius = 50; aLittleCircle.radius = 4; printArea(aBigCircle); printDiameter(aBigCircle); printArea(aLittleCircle); printDiameter(aLittleCircle); }
int main() { // delete printArea() and printDiameter() lines // void printArea(Circle); // void printDiameter(Circle); Circle aBigCircle, aLittleCircle; aBigCircle.radius = 50; aLittleCircle.radius = 4; aBigCircle.printArea(); aBigCircle.printDiameter(); aLittleCircle.printArea(); aLittleCircle.printDiameter(); } Delete printArea() and printDiameter() declare in main(). It should fix your problem.
71,042,424
71,042,584
c++ getservbyport returning wrong information
When I run this code: #include <iostream> #include <netdb.h> int main(){ struct servent* serv = getservbyport(22, "tcp"); if(serv != NULL){ std::cout<<"name: "<<serv->s_name<<" type: "<<serv->s_proto<<std::endl; } return 0; } The result is: name: pcanywherestat type: tcp If I were to run getservbyport(21, "tcp"); the variable serv would return NULL. When I go to the the /etc/services file, it includes these lines: ssh 22/udp # SSH Remote Login Protocol ssh 22/tcp # SSH Remote Login Protocol ftp 21/tcp # File Transfer [Control] If I search the file for pcanywherestat it doesn't exist within the file. Why am I getting this result from running that code?
getservbyport(3) and family store numeric values in Big Endian (aka, network byte order). As a result, you need to convert any int's, in this case with htons(), thusly: struct servent* serv = getservbyport(htons(22), "tcp"); hton*(3) convert values between host and network byte order Edit: the functions htons, htonl, htonll convert from host to short int, long int, and long long int, respectively.
71,042,765
71,044,776
Why are there no monadic operations in std::expected?
In C++23, monadic operations in std::optional was adopted, and later on std::expected. Why were monadic operations like and_then, transform, and or_else not included in the main paper?
The std::expected proposal is very old. The adopted revision is P0323R12, which already suggests a long life, but that paper even predates the P-numbering system and started out as N4015, dated May 2014. I bring this up because std::expected, even by itself, has taken a very long time to wind its way through the process. In contrast, the monadic operations for std::optional paper only first appeared in October 2017. And since then it was just a long slog just to get std::expected at all. There is a paper proposing monadic operations for std::expected, that's P2505R0, but at this point it's very incomplete and needs a lot of work. The design window for new C++23 features is closed, but I wouldn't be surprised if there were an NB comment requesting it in later anyway. At least we finally have std::expected.
71,042,923
71,043,248
Can't make my example using std::ranges::copy_if(R&& r, O result, Pred pred, Proj proj = {}) compile
I've reduced the code failing to compile to the one below: [Demo] #include <algorithm> // copy_if #include <iostream> // cout #include <iterator> // back_inserter #include <ranges> #include <string> #include <vector> struct A { std::string p{}; std::string d{}; }; int main() { std::vector<A> v{{"/usr/bin/cat", "blah"}, {"/usr/lib", "foo"}}; std::vector<std::string> o{}; std::ranges::copy_if( v, std::back_inserter(o), [](std::string& p){ return (p.size() > 10); }, &A::p); } Visual Studio's error output is quite short: error C7602: 'std::ranges::_Copy_if_fn::operator ()': the associated constraints are not satisfied. It basically points you to check the constraints of copy_if at the algorithm header. gcc and clang are more detailed. Having a look at a bit of both outputs: First, the copy_if overload with a range, an output iterator, a predicate, and a projection, is considered. But then, the expression *__o = (std::forward<_Tp>(__t) is evaluated as invalid; where: '_Out&& __o', '_Tp&& __t' [with _Tp = A&; _Out = std::back_insert_iterator<std::vector<std::string>>] Since we are using a projection (from A& to std::string&), why is it trying to copy an A& instead of a std::string& to o? The full error output is accessible through the Demo link above.
The projection applies only to the predicate, not to the result. There's already a way to transform the data entirely—std::views::transform: std::ranges::copy_if( v | std::views::transform(&A::p), std::back_inserter(o), [](const std::string& p){ return (p.size() > 10); }); (This compiles in GCC and MSVC, but not Clang. I'm not 100% confident saying it's correct, but it should be close if nothing else, and it illustrates the point.) Projections are for when you want to test a transformation (projection) of the data while carrying the originals through. In this example, that would mean you'd output to std::vector<A>, yet test a std::string in the predicate. Not super useful here since you could just return (a.p.size() > 10);, but useful if passing a pre-written function instead of using a lambda. Also useful for some other cases such as easily sorting by a member—simply use the default comparator and pass &A::p as the projection.
71,043,035
71,043,142
How to understand the requirement of `std::lower_bound`?
As per the document about std::lower_bound, which says that: The range [first, last) must be partitioned with respect to the expression element < value or comp(element, value), i.e., all elements for which the expression is true must precede all elements for which the expression is false. A fully-sorted range meets this criterion. I have a little difficulty to fully understand it. 1.What's element < value? It seems that element (or value) is never mentioned before this paragraph in the aforementioned document. Does the said element mean the elements before the current element, and the said value means the value of the current element? UPDATED: 2.Since whether a specific sequence is valid(i.e. suits the requirement) or not depends the value, the requirement for a specific sequence could not be always be guaranteed when the value is different. I think it's meaningless to define such a requirement. It's seems that a fully sorted seuqence is more reliable and practical.
What's element < value value is the parameter to lower_bound, see at the beginning of that page: template< class ForwardIt, class T > ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value ); The value in question is mentioned right here, the last parameter to the template. And element, references to some element and every element in the sequence. This is rather a terse way to define the following: take every element in the sequence, one element at a time. When you do that, all elements for which the expression element < value returns true must appear in the sequence before all other elements, for which the same expression is false. It is explicitly intentional for the requirements to be defined in this manner, here's the explanation: For example, if value is 4, and we're talking about natural integers, here's one such sequence: 1, 2, 3, 4, 5, 6 Here, all the elements for which this expression is true (1, 2, and 3), appear before all the elements for which this expression is false (4, 5, and 6). The following sequence is also a valid sequence, in this case: 3, 2, 1, 6, 5, 4 Here, same thing: 3, 2, and 1, for which the expression element < 4 is true, appears before value 4, 5 and 6 for which the expression element < 4 would be false. So, yes, this would also be a valid sequence for a call to lower_bound for the value of 4. The following sequence will NOT be a valid sequence for this specific case of using std::lower_bound: 1, 2, 4, 3, 5, 6 And as far as why is this lower_bound requirement specified in such an strange manner, well, that would be a different question. But this is what it means.
71,043,055
71,043,327
Linked list c++ insertback
I am really new to data structures. I am trying to figure out why my insertback() function doesn't work. The first print does 3,2,1 but the second doesn't print anything. I think it has something to do with head, but I'm not really sure. Please help. #include <iostream> using namespace std; struct Node { int data; Node* next; }; class lst { public: void Insertfron(int x); void Print(); void Insertback(int x); private: Node* head; }; void lst::Insertfron(int x) { Node* temp = new Node; temp->data = x; temp->next = head; head = temp; } void lst::Print() { Node* temp = head; while(temp->next!=NULL) { cout<<temp->data<<' '; temp=temp->next; } cout<< endl; } void lst::Insertback(int x) { Node* backinst = new Node; backinst->data = x; backinst->next = NULL; Node* temp = head; while(temp->next!=NULL) { temp = temp->next; } temp->next = backinst; } int main() { lst listt; listt.Insertfron(1); listt.Insertfron(2); listt.Insertfron(3); listt.Print(); listt.Insertback(4); listt.Print(); return 0; }
You are not initializing head to NULL to indicate an empty list, so ``head` will have a random garbage value, and thus all of your methods exhibit undefined behavior. Once that is fixed, your while loops in both Print() and Insertback() are buggy, as they are not account for head being NULL when the list is empty. Also, you are leaking every node you create. You need to add a destructor to free the nodes when you are done using the list. With that said, try something more like this instead: #include <iostream> using namespace std; struct Node { int data; Node* next; }; class lst { public: lst(); ~lst(); void Insertfron(int x); void Print(); void Insertback(int x); private: Node* head; }; lst::lst() : head(NULL) { } lst::~lst() { while (head != NULL) { Node *next = head->next; delete head; head = next; } } void lst::Insertfron(int x) { Node* temp = new Node; temp->data = x; temp->next = head; head = temp; } void lst::Print() { Node* temp = head; while (temp != NULL) { cout << temp->data << ' '; temp = temp->next; } cout << endl; } void lst::Insertback(int x) { Node* backinst = new Node; backinst->data = x; backinst->next = NULL; if (head == NULL) { head = backinst; } else { Node* temp = head; while (temp->next != NULL) { temp = temp->next; } temp->next = backinst; } } int main() { lst listt; listt.Insertfron(1); listt.Insertfron(2); listt.Insertfron(3); listt.Print(); listt.Insertback(4); listt.Print(); return 0; } That being said, Insertback() can be simplified to avoid the extra if by using an extra level of pointer indirection: void lst::Insertback(int x) { Node **temp = &head; while (*temp != NULL) { temp = &((*temp)->next); } Node* backinst = new Node; backinst->data = x; backinst->next = NULL; *temp = backinst; }
71,043,203
71,131,937
Is template metaprogramming fully able to be substituted in C++20?
Although the idea of template metaprogramming - calculate something at compile time when possible - is wonderful,I wonder if current C++20 features allow us to avoid the TMP fully by using constexpr, consteval, if constexpr,concept, and other C++20 features. Is this true? Or some functionality that TMP offer is not able to be substituted?
No, template metaprogramming cannot be fully replaced by C++20 language utilities; though a large amount can. constexpr, consteval, etc. all certainly help lighten the load off of things that are traditionally done with TMP (as has been increasingly the case over the years), but templates still serve an orthogonal purpose of type-determination and, more importantly, type-generation. constexpr/consteval/etc are limited in their expressiveness, since the parameters to such functions are not, themselves, constant expressions. This is true even in consteval functions, despite the fact that this can only run at compile-time. This means that the following is not legal C++: template <typename T> consteval auto make_array(std::size_t n) { return std::array<T,n>{}; // ^ - error, 'n' is not a constant expression } Live example This limitation means that more complex generation still requires conventional template-metaprogramming techniques. This especially becomes necessary when trying to produce variadic expansion. (As stated in the comments, this would also prevent generating an appropriate type when parsing a string). As an example, consider what the implementation of std::index_sequence would look like without using intrinsics. The naive implementation of make_index_sequence<N> which expands into index_sequence<0, 1, 2, ..., N-1>, would look something like this: template <std::size_t... Ints> struct index_sequence { static constexpr std::size_t size() noexcept { return sizeof...(Ints); } }; namespace detail { template <bool End, std::size_t N, std::size_t...Tails> struct make_index_sequence_impl : make_index_sequence_impl<((N-1) == 0u), N-1, N-1, Tails...>{}; template <std::size_t N, std::size_t...Tails> struct make_index_sequence_impl<true, N, Tails...> : std::type_identity<index_sequence<Tails...>>{}; } // namespace detail template <std::size_t N> using make_index_sequence = typename detail::make_index_sequence_impl<(N==0u), N>::type; Live Example Technically the index_sequence example can be written in C++20 with recursive consteval functions that return an instance of the index_sequence -- but this only works because we can pass in a value to a template-deduced function. More complex type examples would not have this luxury at compile-time. In general, more complex type-generation like this will require some level of TMP, especially if the type has restrictions on default-constructibility, or can't itself be a constant expression. In such a case, this would require partial template specializations which start to fall under general template-metaprogramming practices.
71,043,552
71,052,909
How to use a C/C++ library (like NCurses) in Haxe
I have a cli written in Haxe and compiled to a binary via C++ (hxcpp). I would like to use ncurses in it. I have worked with ncurses in C and I've worked with JS externs in Haxe but I'm can't figure out the Haxe/C++ documentation to connection the two together. I haven't used much more of the HXCPP compiler than the basic haxe command (ie not build files etc), à la: haxe -lib somelib -cp src --cpp bin/cpp path.to.Main Basically, I can work with all custom code, but am struggling on externals. So I'm not entirely sure how many steps I am missing towards my goal. But I can see a few major obstacles. How to include ncurses in the build? ie. cc -lncurses -o out [etc...] in a Makefile. How to include the proper externs to allow Haxe to compile at all without error. All the extern examples I see involve a class/namespace but NCurses functions don't have a class or namespace. I haven't found any documentation for a bare extern function. Then of course the basics of including the headers properly (or the haxe compilation equivalent) in my actual Haxe code. I know this is basically asking for a mini-tutorial, but I can't find examples or documentation that I can put together to accomplish this specific goal. Thanks for any help you can lend.
HXCPP uses an xml-based build system. When you launch haxe -cp src --cpp bin/cpp path.to.Main: Haxe files are transpiled to C++ and a Build.xml is produced in the output directory, i.e. bin/cpp/Build.xml; everything is then built by HXCPP, merging the newly generated project Build.xml with the global default xml definitions and then calling the compiler toolchain(s). You can inject compiler flags, libraries to link, includes directories, etc., through the @:buildXml metadata, as described on the manual: @:buildXml(" <target id='haxe'> <lib name='-lncurses' if='linux'/> <lib name='ncurses.lib' if='windows'/> </target> ") class Main{ ... These tags will be appended to the project Build.xml. The haxe target is the default target. Keep in mind that every toolchain (MSVC, gcc, Xcode, etc.) has its own syntax. You can see examples in the build.xml of cross-platform low-level projects like Systools or Lime. You can add -D HXCPP_VERBOSE to the haxe command line to see which commands are actually launched: haxe -D HXCPP_VERBOSE -cp src --cpp bin/cpp path.to.Main. As for externs, the simpler case is: you write your C++ code, with #includes and everything needed, inside a @:cppFileCode() block; everything you write here is pasted as-is in the generated cpp file; you mark one of your haxe functions, defined on one of the haxe classes, as @:native("nameOfTheCppFunction"), and the build system will join them together. @:cppFileCode(" #include <ncurses.h> void nativeCppTest(){ /* here goes your ncurses code */ return; } ") class Main{ public static function main() { myCppTest(); } @:native("nativeCppTest") extern static function myCppTest():Void; } If you open the generated file (in this case bin/cpp/src/Main.cpp) you'll see that the haxe myCppTest() call is changed to its native version nativeCppTest(). If you would like to pass function arguments, and receive return values, you'll have to wrap those using the cpp.* standard library types. For example: @:cppFileCode(" #include <ncurses.h> void nativeCppTest(const char* myString){ /* here goes your ncurses code */ return; } ") class Main{ public static function main() { myCppTest("print this"); } @:native("nativeCppTest") extern static function myCppTest(myString:cpp.ConstCharStar):Void; } Some of the conversions will be automatic (like, in this case, from a constant string to ConstCharStar), some will require an explicit cast; if you need to pass pointers to the C++ code, you can get it via cpp.RawConstPointer.addressOf(<haxe object>) (or RawPointer if not const): public static function main() { var myString:String = "print this"; myCppTest(cast cpp.RawConstPointer.addressOf(myString)); } Useful references: C++ Magic by Hugh Sanderson C++ extern example, everything in one file (MiniMP3 project)
71,043,619
71,043,645
Bazel: submodule in project does not use bazel , pushing to git doesnt include locally added BUILD file in submodule, how do i build?
I am just starting to learn how to use bazel following this tutorial One thing I am unsure how to do is how to use a submodule, from my own repo for example. where I do not use bazel. The repo just has some c/h files that I need to pull in. To make things work locally I added a BUILD file in folder pulled in from submodules. However after I commit and push my changes the BUILD file is obviously not there. How do I add the c/h files from the submodule folder to my build. Bazel seems to be looking for a BUILD folder in that directory and there will be none, if for example someone else clones this repo. currently my "main" Directory has this build file: cc_library( name = "uCShell-main", srcs = ["main.c"], deps = ["//uCShell:uCShell-lib" ], ) cc_binary( name = "uCShell-bin", deps = [":uCShell-main" , "//uCShell:uCShell-lib" ] ) and the folder with the pulled in submodule has this locally added BUILD file: cc_library( name = "uCShell-lib", srcs = glob(["*.c"]), hdrs = glob(["*.h"]), visibility = ["//visibility:public"], ) This works and compiles just fine. However do correct any issues or misuse of Bazel you see here, I'd like to learn. Ultimately to reiterate the issue, when I push this project the locally added BUILD file will not be in the project because it is not in the original submodule. So how can I inlcude the c/h files in that submodule in order to build my main. And I would like to leave it as a submodule. Ultimately I can just add a BUILD file for the submodule's repo, but would like to find a better way, for example what if this was not my repo where I can just add a BUILD file.
If you use new_local_repository with a relative path to import the submodule, you can set build_file or build_file_content to add the BUILD file. You should be able to use that same BUILD file as-is. Because it will be in a different external repository, you'll need to access it via the corresponding label. For example, if you put the BUILD file at build/BUILD.my_lib.bazel and this in WORKSPACE: new_local_repository( name = "my_lib", path = "submodules/my_lib", build_file = "@//build:BUILD.my_lib.bazel", ) then you can put @my_lib//:uCShell-lib in deps of any other target and it will all work.
71,043,905
71,044,793
C++ template what does this class assignment in template mean?
template<classT> class MyClass { using KeyType = int; using MapType = std::map<KeyType, int64_t>; MapType map_; template <class T1 = T, class = std::enable_if_t<std::is_same<T1, int>{}>> IndexValueType LowerBound(KeyType k) const { auto it = map_.lower_bound(k); if (it == map_.end()) { return NOT_FOUND; } return it->second; } }; What does these 2 assignments do in this context? class T1 = T class = std::enable_if_t<std::is_same<T1, int>{}>
LowerBound is a member template function declared inside the class template MyClass. It's similar to a function template but it is enclosed in a class (template). The code can be simplified as template <typename T> class MyClass { template <typename T1 = T, typename = std::enable_if_t<std::is_same<T1, int>{}>> IndexValueType LowerBound(KeyType k) const {} }; The first assignment T1 = T means the default argument for the first template parameter is the same type of T. If you are not explicitly specified, T1 will be T. You could of course explicitly specify other types. The second assignment here is an usage of std::enable_if. Also pointed in the comments, it's a simple way to apply SFINAE. Here it will disable(ignore) templates when T1 is not the same as int. Since the second parameter is only to restrict the first parameter and has no usage in the definition, its name is ignored. MyClass<int> mc1; // T is int mc1.LowerBound(...) // T1 is int, when not specified explicitly mc1.LowerBound<std::int32_t>(...) // T1 is std::int32_t here MyClass<double> mc2; // T is double mc2.LowerBound<int>(...) // OK, T1 is int mc2.LowerBound(...) // T1 is substitued with double here and will cause compile error since is not int
71,044,230
71,044,297
Can't get Boost C++ Libraries to work in an AWS Linux Environment
I am trying to transfer a C++ project started by a colleague to a AWS Cloud9 environment.The project was originally developed on Mac and makes use of the Boost library. I've set up the AWS Cloud9 environment to use Amazon Linux. Once the environment created I import the project using the "Upload Local Folder" function. The project is uploaded in the environment/projectName path. I think try to install boost on the environment. I run the following commands to download boost sudo yum install boost sudo yum install boost-devel I checked and boost is present at the following filepath: /usr/include/boost However, when I try to compile my code, I get a series of errors along the line of: lib/Category.h:12:10: fatal error: boost/container_hash/hash.hpp: No such file or directory #include <boost/container_hash/hash.hpp> The makefile used has the -Ilib and -lboost_program_option flags. I've been looking for what they mean to no success. I use g++. I've tried including the -I and pointing to the boost path to no success. I have the feeling it can be due to an include path. Thanks!
Amazon Linux 2 has boost 1.53. This is too old, and container_hash has not been yet available. You have to manually build newer version of boost.
71,045,477
71,048,868
Is there a way to enumerate interfaces using NI Daqmx
I have a C++ application interfacing with a NI DAQ card, however the name of the device is hard coded and if changed in the NI Max app it would stop working, so is there a way to enumerate connected devices to know the name of the cards that are connected ?
List of all devices can be retrieved with DAQmxGetSysDevNames(). The names are separated by commas. Once you have the list of all names, you can use the product type to find the correct device. const std::string expectedProductType = "1234"; constexpr size_t bufferSize = 1000; char buffer[bufferSize] = {}; if (!DAQmxFailed(DAQmxGetSysDevNames(buffer, bufferSize))) { std::string allNames(buffer); std::vector<std::string> names; boost::split(names, allNames, boost::is_any_of(",")); for (auto name : names) { char buffer2[bufferSize] = {}; if (!DAQmxFailed(DAQmxGetDevProductType(name.c_str(), buffer2, bufferSize))) { if (expectedProductType == std::string(buffer2)) { // match found } } } }
71,045,603
71,045,787
Multiple override-methods in inheritance each have multiple possible implementations
Let me introduce the following three classes: AbstractProcessor and these two child classes. The code below is not complex because there are only two child classes, but what if procedures1 and procedure2 both has many N candidate implementation? In such case, there are NxN child classes and a lot of duplication will be made by hand-coding. In the code below for example, each procedure can either be fast one or accurate one. So there are 2x2 possible child classes. I would ask about technique/design pattern to reduce duplication. More precisely, is there any technique to reduce that NxN hand-coding to 2N hand-coding? Noting that procedure1 and procedure2 both have to share the same var_ (in my case it is measurement value of physical world of robot) and the common function foo(), procedure1 and procudure2 can hardly be composed by a has-a relationship. Actually in my application, there are lot of var_ because the robot access to many type of sensors. class AbstractProcessor { virtual void procedure1() = 0; virtual void procedure2() = 0; Something foo(){ // ... } double var_; void run(){ procedure1(); procedure2(); } }; class FastProcessor : public AbstractProcessor { void procedure1() override {// ... fast procedure ( use foo and var_ inside) } void procedure2() override {// ... fast procedure ( use foo and var_ inside) } }; class AccurateProcessor : public AbstractProcessor { void procedure1() override {// ... accurate procedure ( use foo and var_ inside) } void procedure2() override {// ... accurate procedure ( use foo and var_ inside) } };
Inheritance is not the solution to everything. Sometimes all the problems are gone once you don't use inheritance. There are many different ways to do what you want. One is to store the callables as members: #include <functional> #include <iostream> struct Processor { std::function<void(Processor*)> procedure1; std::function<void(Processor*)> procedure2; double var_ = 42.0; void foo() { std::cout << "hello foo\n"; } void run(){ procedure1(this); procedure2(this); } }; int main() { Processor proc{ [](auto p) { std::cout << p->var_ << "\n";}, [](auto p) { p->foo(); } }; proc.run(); } Instead of lambdas the parameters to the constructor could be free functions so they can be more easily be reused. Note that I hade to make everything public in the class, in your example everything is private (it cannot work like that). As you are asking for a technique/design pattern, the term "composition over inheritance" fits best here I think. Dependency injection and other related design patterns might also help you to get into a different way of thinking about your design.
71,045,789
71,073,316
How to check memory leaks using memory usages of a process?
int ParseLine(char* line){ int i = strlen(line); const char* p = line; while(*p < '0' || *p > '9') p++; // Search until a number is found. line[i - 3] = '\0'; // Remove " kB" i = atoi(p); return i; } int GetCurrentVirtualMem(){ std::string cur_proc; cur_proc = "/proc/" + std::to_string((int)getpid()) + "/status"; FILE* fs = fopen(cur_proc.c_str(), "r"); int result = -1; char line[128]; while(fgets(line, 128, fs) != NULL){ if(strncmp(line, "VmSize:", 7) == 0){ result = ParseLine(line); break; } } fclose(fs); fs = NULL; //garly modify, for test memory problem return result; } int GetCurrentMem(){ std::string cur_proc; cur_proc = "/proc/" + std::to_string((int)getpid()) + "/status"; FILE* fs = fopen(cur_proc.c_str(), "r"); int result = -1; char line[128]; while(fgets(line, 128, fs) != NULL){ if(strncmp(line, "VmRSS:", 6) == 0){ result = ParseLine(line); break; } } fclose(fs); fs = NULL; //garly modify, for test memory problem return result; } I'm trying to check memory leaks but I don't understand physical memory and virtual memory clearly. So I just printed both using the functions above. float curr_mem = (float)GetCurrentMem() / 1000; float curr_vir_mem = (float)GetCurrentVirtualMem() / 1000; std::cout << "Using memory(" << std::to_string((int)getpid()) << "): " << curr_mem << ", " << curr_vir_mem << std::endl; If I check the changes of physical memory or virtual memory, which one should I take a look at? Both? or one of them? And I found that even if there are no memory leaks the memory values are changed. int main(int argc, char *argv[]) { QApplication a(argc, argv); float prev_mem = 0; float prev_vir_mem = 0; while(true){ int* mem_leak = new int[100]; float curr_mem = (float)GetCurrentMem() / 1000; float curr_vir_mem = (float)GetCurrentVirtualMem() / 1000; if(prev_mem != curr_mem || prev_vir_mem != curr_vir_mem){ prev_mem = curr_mem ; prev_vir_mem = curr_vir_mem; std::cout << "Using memory(" << std::to_string((int)getpid()) << "): " << curr_mem << ", " << curr_vir_mem << std::endl; } delete[] mem_leak; } return 0; } After an hour of running the code above, it showed the changes in the memory Using memory(3303): 28.296, 250.788 Using memory(3303): 28.652, 250.788 Using memory(3303): 28.916, 250.788 So is this method fine to check memory leak or not? I used "Valgrind" but it didn't show any memory leak message from my code(not the above code. It is too huge to upload here. It is over 30000 lines.). But it showed memory changes in the long-term running test(about 1-week). Please let me know how to check memory leaks correctly without using other software(such as Valgrind).
If I understand you correctly you want to check for memory leaks on Linux using a process image from an process that has not been instrumented in any way. https://github.com/vmware/chap (free open source) does this. First you gather a core: echo 0x37 > /proc/<pid-of-your-process>/coredump_filter gcore <pid-of-your-process> Then you open the core in chap: chap <core-just-created-by-gcore> To check for the classic kind of leak (objects that can no longer be reached) you can use the following commands from the chap prompt: count leaked That tells you how many objects were leaked. describe leaked /showUpTo 100 That describes each leaked object, gives a hex dump of up to 0x100 bytes of each object and gives you the count at the end. Various other commands are available but I don't want to repeat the user's manual.
71,045,918
71,047,638
How to print a X with two letters inside a square
I am trying to make the this shape but stuck at here. I tried with counters more than one but failed again. P p p p p p Q p P p p p Q q p p P p Q q q p p p Q q q q p p Q q Q q q p Q q q q Q q Q q q q q q Q int main() { int loopLimit = 7; int upperCharacter = 0; do { int loopCounter = 0; do { if (loopCounter == upperCharacter) std::cout << "P "; else std::cout << "p "; loopCounter = loopCounter + 1; } while (loopCounter < loopLimit); upperCharacter = upperCharacter + 1; loopLimit = loopLimit - 1; std::cout << "\n"; } while (loopLimit > 0); } My code currently outputs: P p p p p p p p P p p p p p p P p p p p p P p p p p p p
A pen and a paper solved this question. Here's the solution: for (int satirSayaci = 1; satirSayaci < 8; satirSayaci++) { for (int karakterSayaci = 1; karakterSayaci < 8; karakterSayaci++) { if (karakterSayaci >= 8 - satirSayaci) { if (karakterSayaci == 8 - satirSayaci || karakterSayaci == satirSayaci) std::cout << "X "; else std::cout << "x "; } else { if (karakterSayaci == satirSayaci) std::cout << "P "; else std::cout << "p "; } } // Yeni bir satir yazdir std::cout << std::endl; }
71,046,011
71,046,265
Send UWP Object from C++ to C#
I have code in C++ that generates a SpatialCoordinateSystem instance and wish to send this over for my C# code to use. I saw here that a I can simply create such an instance in C# if I have a native pointer to said object, so this was my initial approach. Unfortunately, I am not able to get this to work as I keep encountering access violation errors when trying to pass the pointer from C++ to C#. Any help would be highly appreciated (Note: using the native microsoft function that creates my object in C# is not requires, it was just what made the most sense to me). C++ (coords is a global variable defined in my header file): void* getCoords() { if (coords == nullptr) { SpatialLocator loc = SpatialLocator::GetDefault(); coords = loc.CreateStationaryFrameOfReferenceAtCurrentLocation().CoordinateSystem(); } return &coords; } C#: [System.Runtime.InteropServices.DllImport("MyDLL.dll", EntryPoint = "getCoords"] public static extern IntPtr getCoords(); public static SpatialCoordinateSystem GetCoordinateSystem() { IntPtr ptr = getCoords(); return SpatialCoordinateSystem.FromNativePtr(ptr); }
You can use COM to transfer data from C++ to C#. What you have to do is create similar structure (COORD in your case) in C# code. Then create an interface in C# code and implement one function inside that interface that will accept the argument of type of that structure (COORD). Now, you just have to make a tlb file from the CMD prompt. For making the tlb file, what you have to do is you have to make an empty .bat file (You can name it RegisterTlb.bat) in your working directory (where you have placed your C# code project) and open it with notepad and write following command inside that .bat file: "C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\regasm.exe" "your_C++_exe_name.exe" /tlb your_C#_interface_name.tlb" Here the interface name is that in which you have just implemented you function. Now just open a command prompt with admin mode and change your directory (with cd command in command prompt) to your c# project directory where your bat file is placed and simply write your bat file name in command prompt (with .bat extension). It will show you the message that type registered successfully. Now you will see that new file with .tlb is been generated automatically in your c# project directory. Copy that .tlb file, paste it in c++ project directory and build the c++ project again. You will see that one smart pointer will be generated in your c++ code the the same name as your interface name (interface that you have created in C# code) but with Ptr suffix like "interface_namePtr". Now you can just call your C# function in C++ as: interface_namePtr->functionName(structureParamenter (COORD) with data) And this will transfer your data automatically. Do one thing for simplicity (even I got confused here). Make your interface name and your c# project name the same.
71,046,440
71,046,582
In C++ How can I read in different types of data in one instream of the same cin object
I wrote a custom class CMyistream_iterator. Its constructor has an argument of an istream object. template <class T> class CMyistream_iterator { private: T valArray[100]; int pos; public: CMyistream_iterator(istream& in):pos(0){ T n; int i=0; while(in>>n){ *(valArray+i) = n; ++i; } } T operator*(); }; But I meet some problems when I enter the data. int main(){ CMyistream_iterator<int> inputInt(cin); //...somecode... CMyistream_iterator<string> inputStr(cin); //...somecode... } Data is entered like this: 22 33 44 tom jack+'\n' The second class can't be constructed as it can't read in the next two strings. It seems that when the integer iterator comes to the character 't', it was converted into EOF. How can I solve this problem?
It seems that when the integer iterator comes to the character 't', it was converted into EOF. That is not what happens. When cin >> n in the int iterator encounters the character 't', it fails to read in an int value, and thus puts cin into an error state that you need to explicitly reset with cin.clear() before you can continue reading from cin. Also, your iterator is not allocating memory for valArray to point at. You should consider using std::vector and let it manage the memory for you.
71,047,000
71,047,081
error: no matching function for call to 'Node::Node()' - second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...)
I've defined a structure like this: struct Node { int32_t a; int32_t b; double c; double d; Node (int32_t a, int32_t b, double c) { this->a = a; this->b = b; this->c = c; this->d = 0.0; } }; I'm implementing a map of map like this: unordered_map<UInt32,unordered_map<int32_t,Node>> data; Upon using the below code. I'm receiving error error: no matching function for call to 'Node::Node()' second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...) data[instId][id].d += (value); Please help out why I'm receiving error. I've also tried using auto& tree = data[instId]; tree[id].d += (value); (PS: Pseudo code is mentioned)
It is because that unordered_map<int32_t,Node> tries to call the constructor Node() with no argument, and because you defined the constructor with three argument, Node() is deleted. Consider adding Node()=default; inside the class definition.
71,047,085
71,047,681
Can't find error in my merge sort implementation, getting wrong output?
In the code below I was given unsorted array had to find kth smallest Given an array arr[] and an integer K where K is smaller than size of array, the task is to find the Kth smallest element in the given array. It is given that all array elements are distinct. #include<bits/stdc++.h> using namespace std; Merge function: void merge(int arr[],int l,int m,int r){ int marr[(r-l)+1]; int i=l,j=m+1,k=0; for(k;k<=(r-l);k++){ if(i==(m+1)){ marr[k]=arr[j]; j++; } else if(j==(r+1)){ marr[k]=arr[i]; i++; } else if(arr[i]<=arr[j]){ marr[k]=arr[i]; i++; } else if(arr[i]>arr[j]){ marr[k]=arr[j]; j++; } } //Below assignment was creating wrong output but cant figure out why? for(k=0;k<=(r-l);k++,l++){ arr[l]=marr[k]; } //However below code worked instead, in spite tracing same no. of values //for(int x=l,k=0;x<=r;x++,k++){ // arr[x]=marr[k]; //} Mergesort: void mergesort(int arr[], int l,int r){ if(r<=l) return; int mid=l+(r-l)/2; mergesort(arr,l,mid); mergesort(arr,mid+1,r); merge(arr,l,mid,r); } class Solution{ public: // arr : given array // l : starting index of the array i.e 0 // r : ending index of the array i.e size-1 // k : find kth smallest element and return using this function int kthSmallest(int arr[], int l, int r, int k) { mergesort(arr,l,r); return arr[k-1]; } }; Driver Code starts int main() { int test_case; cin>>test_case; while(test_case--) { int number_of_elements; cin>>number_of_elements; int a[number_of_elements]; for(int i=0;i<number_of_elements;i++) cin>>a[i]; int k; cin>>k; Solution ob; cout<<ob.kthSmallest(a, 0, number_of_elements-1, k)<<endl; } return 0; } Driver Code ends
The non-standard variable length arrays and other considerations notwithstanding (seriously, get a good reference book and reputable tutorial guide), the problem is in your merge algorithm: At the end of merge you're trying to put the sorted marr data back into arr. That is done here: for(k=0;k<=(r-l);k++,l++) { arr[l]=marr[k]; } The problem is the increment of l, which has the effect of shortening the merge because it causes (r-l) to collapse toward k, while k is ascending upward. This means you don't copy all your data, and you're left not-only with partial sorting, you're left with potential duplicate junk in arr (in fact, it is highly likely). Replacing that with this: for (i=0; i<=(r-l); ++i) { arr[i+l] = marr[i]; } should fix it for you. This runs i from 0..segment length inclusive, drops the results into the adjusted offset i+l location. Everything either wrong or poor in this code has been deftly mentioned in comments, so I'll leave that for you to address (and believe me, you want to address all of it).
71,047,307
71,047,522
Call different constructors from different structs based on input parameter value
recently I'm working on an problem like that struct A { A() {/* Constructor A */ } void method() { /* method A */ } }; struct B { B() {/* Constructor B */ } void method() { /* method B */ } }; struct C : public A, public B { C(int which) :A() {} C() :B() {} static C ConstructIt(int which) { if (which == 1) { return C(which); } else { return C(); } } }; int main(int argc, char** argv) { const int a = 1, b = 0; C examp_A = C::ConstructIt(a); C examp_B = C::ConstructIt(b); examp_A.method(); //use method A examp_B.method(); //use method B } I need to create a interface to call different method struct A or B based on dynamic input parameter value, since it's determined in runtime I do not want to use template partial specialization. I try to use multiple inherit to see struct A and B as bases, and conditionally select the constructors A or B, it failed caused by multiple inheritance construct the base and derived classes automatically. With my current knowledge of C++ I don't know how to realize it (maybe it's a stupid question), thanks for help in advance. EDIT: Thanks the solution provided by Jarod42. It seems ok for me if I can modify the struct A which is fully developed. Is there a way that I could realize the above feature without modify the existed struct A? Struct B is free to change.
It seems you want polymorphism. There are several ways. One common way is with interface and virtual functions: struct C { virtual ~C() = default; virtual void method() = 0; }; struct A : C { A() {/* Constructor A */ } void method() override { /* method A */ } }; struct B : C { B() {/* Constructor B */ } void method() override { /* method B */ } }; std::unique_ptr<C> ConstructC(int which) { switch (which) { case 1: return std::make_unique<A>(); case 2: return std::make_unique<B>(); // ... } return nullptr; } And then int main() { const int a = 1, b = 0; auto examp_A = ConstructC(a); auto examp_B = ConstructC(b); examp_A->method(); //use method A examp_B->method(); //use method B }
71,047,430
71,048,077
Why I can't pass string literals to const char* const& in this specialized function template
Why pass a string literal to const char* const& in a specialized function template is illegal, while to const char* is legal? Here's the thing. There are two excercises about template specialization in C++ Primer: Exercise 16.63: Define a function template to count the number of occurrences of a given value in a vector. Test your program by passing it a vector of doubles, a vector of ints, and a vector of strings. Exercise 16.64: Write a specialized version of the template from the previous exercise to handle vector<const char*> and a program that uses this specialization. The code below is my answer, the compile error appears when I pass the string literal to this specialized count function. // Count the number of occurrences of a given value in a vector template <typename T> std::size_t count(const std::vector<T>& vec, const T& value) { std::size_t i = 0; for (const auto& v : vec) { if (v == value) ++i; } return i; } // A specialized version where T = const char* template <> std::size_t count(const std::vector<const char*>& vec, const char* const& value) { std::size_t i = 0; for (const auto& v : vec) { if (!strcmp(v, value)) ++i; } return i; } int main() { std::vector<const char*> sVec{ "cpp", "primer", "cpp", "fifth", "edition", "Cpp", "cpp" }; // Error message: no instance of function template "count" matches the argument list, // argument types are: (std::vector<const char *, std::allocator<const char *>>, const char [4]) std::cout << count(sVec, "cpp") << std::endl; return 0; } Besides, it's perfectly ok to pass a string literal to const char* const& in a nontemplate function, which makes me confused. void test(const char* const& str) { std::cout << str << std::endl; } int main() { test("cpp"); // Prints "cpp" as expected return 0; }
You don't "pass to a function template specialization". The call is deduced against the original template definition (regardless of any specialization), deducing a type if successful. Then if a specialization exists for the deduced type then that will be called. The error message is about type deduction failing . You should see the exact same error even if you delete the specialization. The type deduction fails because T occurs in two different parameters but the result of deduction differs for each parameter: Deducing vector<T>& vec against vector<const char *> produces T=const char * Deducing const T& value against "cpp" produces T=const char[4] . Deduction only succeeds if all instances of T being deduced produce the same type. There is no extra step of different types being reconciled by considering available conversions. One way to solve the problem would be to use overloading instead of specialization (i.e. delete the text template <>). Then there is an overload set consisting of the non-template function, and the result of deduction (if any). If deduction fails , as it does, it is not an error because the overload set still contains something.
71,047,476
71,048,213
What is the best way to tell the compiler to differentiate between two types which hold the same kind of data
Suppose we have two types which are basically ints: alias UserID = int; alias ItemID = int; And suppose we have two functions which take arguments of the two types: void add_user(UserID id) { std::cout << "Adding user with id " << id << '\n'; } void add_item(ItemID id) { std::cout << "Adding item with id " << id << '\n'; } The problem is that we can do: UserID uid {5}; add_item(uid); And the compiler will not be able to protect me from passing the wrong type because both types alias the same underlying type. What is the least boilerplate I need to add to make the compiler differentiate between the two types? My current solution is to define the types as structs like this: struct UserID { int val; operator int() { return val; } }; struct ItemID { int val; operator int() { return val; } }; The operator int() is to allow for an implicit conversion to the base type. One problem with this approach is that sometimes I need to do arithmetic operations on the types, like for example: UserID uid {5}; ++uid; Another problem is when these types are passed to a template and a template-argument deduction takes place where the correct type to deduce is int but the compiler is not able to see through the conversion operator. I'm wondering if there's a more elegant solution where both types would seamlessly convert to their base type when the base type is required but would still be different when the wrapping type is required. What I want is the following: add_user(UserID{1}); //compiles add_item(ItemID{2}); //compiles add_user(ItemID{3}); //doesn't compile UserID uid = UserID{4} + 1; //compiles ++uid; //compiles UserID uid2 = ItemID{5} + 1; //doesn't compile By 'the least boilerplate' I mean the total boilerplate code I need to write both in the definition of the types as well as in the user code.
You can use "shadow types" (they have names but no definition) and a template (or use some "strong typedef" library): template <typename> class Id { int val; operator int() const { return val; } }; using UserID = Id<struct user_tag_>; using ItemID = Id<struct item_tag_>; And you should provide operator overloads for the operations that make sense - you most likely don't want to divide or multiply these IDs by anything.
71,048,332
71,048,447
Does "auto" keyword always evaluates floating point value as double?
Continuing the question, which was closed: C++: "auto" keyword affects math calculations? As people suggested I modified the code by adding "f" suffix to floating-point values. #include <cmath> unsigned int nump=12u; auto inner=2.5f; auto outer=6.0f; auto single=2.f*3.14159265359f/nump; auto avg=0.5f*inner+0.5f*outer; for (auto i=0u;i<nump;++i){ auto theta=i*single; auto px=avg*sin(theta); auto py=avg*cos(theta); auto tw=17.f; int v1=std::round(1.f+px-tw/2.0f); int v2=std::round(2.f+py-tw/2.0f); std::cout<<"#"<<i<<":"<<v1<<";"<<v2<<std::endl; } versus #include <cmath> unsigned int nump=12u; float inner=2.5f; float outer=6.0f; float single=2.f*3.14159265359f/nump; float avg=0.5f*inner+0.5f*outer; for (unsigned int i=0u;i<nump;++i){ float theta=i*single; float px=avg*sin(theta); float py=avg*cos(theta); float tw=17.f; int v1=std::round(1.f+px-tw/2.0f); int v2=std::round(2.f+py-tw/2.0f); std::cout<<"#"<<i<<":"<<v1<<";"<<v2<<std::endl; } The result is exactly the same - output differs between two versions. So does it mean that "auto" always evaluates floating point value to "double" type?
The issue is that your code is using ::sin instead of std::sin (and the same for cos). That is, you’re using the sin function found in the global namespace. std::sin is overloaded for float. But ::sin isn’t, and it always returns a double (because ::sin is the legacy C function, and C doesn’t have function overloading). Use std::sin and std::cos in your code to fix the issue.
71,048,420
71,048,449
Multidimensional array printing wrong values in cpp
I've been struggling with a simple class representing a matrix in C++. Instead of using a multidimensional array, I've decided to use a flat array and access the values by calculating the index of the according cell by [row * x_dim + col]. I want to use 2D matrices only. Ideally, I would also create getter and setter functions, but as I am already having troubles I skipped those for now. The main problem is, that after setting values, those values seem to be corrupted somewhere along the way as when printing them out again, I'm reading different values then what I've actually stored. Here's the (simplified) header MyMatrix.h: class MyMatrix{ public: int x_dim, y_dim; float *my_matrix; MyMatrix(int x, int y); ~MyMatrix(); }; Here is MyMatrix.cpp: #include "MyMatrix.h" MyMatrix::MyMatrix(int x, int y){ x_dim = x; y_dim = y; my_matrix = new float[x * y]; } MyMatrix::~MyMatrix(){ delete[] my_matrix; } Now when creating a new instance of MyMatrix, filling the array with ascending numbers and then printing the values again, I am getting different values for some cells in the (flat) matrix. Here's what I did: #include "MyMatrix.h" #include <iostream> int main(){ MyMatrix test(3, 4); //filling the array in test with ascending numbers for(int row = 0; row < test.x_dim; row++){ for(int col = 0; col < test.y_dim; col++){ test.my_matrix[row * test.x_dim + col] = col+1; } } for(int row = 0; row < test.x_dim; row++){ std::cout << "Row " << row << ": "; for(int col = 0; col < test.y_dim; col++){ std::cout << test.my_matrix[row * test.x_dim + col] << " "; } std::cout << std::endl; } } So what my output should look like is this: Row 0: 1 2 3 4 Row 1: 1 2 3 4 Row 2: 1 2 3 4 But instead, it looks like this: Row 0: 1 2 3 1 Row 1: 1 2 3 1 Row 2: 1 2 3 4 As one can see, the first two rows have a 1 instead of a 4 in column 3. I've really been struggling with identifying the underlying issue here and I can't figure it out so I would appreciate any help! Thanks! I am using clang version 13.0.0 on an M1 Pro and the g++ compiler.
This is the wrong index: row * test.x_dim + col Suppose you are in the last iteration of the outer loop then row == x_dim-1 and you get: (x_dim-1) * x_dim + col while it should be (supposed x is rows): (y_dim-1) * x_dim + col Tip: Your variable naming col vs x_dim and row vs y_dim can be made better. x, x_dim and y, y_dim or col, num_columns and row, num_rows would be less errorprone.
71,048,555
71,055,458
Extract boost log attribute values of arbitrary type
There is a logging system with the number of attributes of arbitrary types. The attributes are added by external program(s) using public API (function template). The types aren't known beforehand. The typical way to print out an attribute's value looks like (simplified): void print(logging::attribute_value const& attr) { auto val = logging::extract<int>(attr); if (val) { std::cout << "value: " << val.get() << std::endl; } } In the example above it's already known that the attribute value type is int. What if the expected type isn't known? Of cource, I could write it like: typedef boost::mpl::vector<int, std::string> types; // Expected types logging::value_ref<types> val = logging::extract<types>(attr); [..] however in that case I have to define all possible types and handle them separately. Is there a way to print out (or convert to strings) all values regardless of their types, assuming the types overload streaming operator? UPDATE Here are some more details: // Add new attributes with arbitrary types template<typename T> void addProperty(const std::string &key, T && value) { auto attrs = boost::log::core::get()->get_thread_attributes(); attrs.erase(key); attrs.insert(key, boost::log::attributes::make_constant(std::move(value))); boost::log::core::get()->set_thread_attributes(attrs); } and another function that should print the properties' values void printProperties() { const auto &attrs = boost::log::core::get()->get_thread_attributes(); for (auto const &a : attrs) { // Print all values. Types aren't known. } }
Is there a way to print out (or convert to strings) all values regardless of their types, assuming the types overload streaming operator? No, Boost.Log doesn't support that, you must know the name and type of the attribute value in order to be able to extract or visit it. What you could do is maintain your own mapping between attribute names and formatting routines, such as this: std::map< logging::attribute_name, std::function< void(std::ostream&, logging::attribute_value const&) > > formatters; template< typename T > void formatter(std::ostream& strm, logging::attribute_value const& attr) { auto val = logging::extract< T >(attr); if (val) strm << val.get(); } template<typename T> void addProperty(const std::string &key, T && value) { typedef std::remove_cv_t< std::remove_reference_t< T > > value_type; logging::attribute_name name(key); formatters[name] = &formatter< value_type >; boost::log::core::get()->add_thread_attribute(name, boost::log::attributes::make_constant(std::forward< T >(value))); } void printProperties() { const auto &attrs = boost::log::core::get()->get_thread_attributes(); for (auto const &a : attrs) { auto it = formatters.find(a.first); if (it != formatters.end()) { std::cout << "value: "; it->second(std::cout, a.second.get_value()); std::cout << std::endl; } } }
71,048,946
71,052,900
Is there a way to check if a class is convertible to some template instantiation?
The question Here some code struct Base { int SomeMethod(const Base&); template <class T> int SomeMethod(const T&); }; template <class Tag> struct Derived : Base { using Base::SomeMethod; int SomeMethod(const Derived&); template <class OtherTag> std::enable_if_t<!std::is_same_v<Tag, OtherTag>> SomeMethod(Derived<OtherTag>) = delete; }; struct tag {}; struct another_tag {}; struct ImplicitOpToAnotherTagInstantiation { operator Derived<another_tag>() const; }; Is there something (Derived::SomeMethod overload) that i can write in Derived without touching the Base, that will cause a compiler error in the next code? Derived<tag>{}.SomeMethod(ImplicitOpToAnotherTagInstantiation {}); Next code should be correct struct ImplicitOpToBase { operator Base() const; }; Derived<tag>{}.SomeMethod(Derived<tag>{}); Derived<tag>{}.SomeMethod(Base{}); Derived<tag>{}.SomeMethod(ImplicitOpToBase{}); // Derived<tag>{}.SomeMethod(Derived<another_tag>{}); compiler error! What have I tried First thought was to do something like this: template <class Tag> struct Derived : Base { using Base::SomeMethod; int SomeMethod(const Derived&); template <class OtherTag> std::enable_if_t<!std::is_same_v<Tag, OtherTag>> SomeMethod(Derived<OtherTag>) = delete; template <class T, class OtherTag> std::enable_if_t<!std::is_same<Tag, OtherTag> && std::is_convertible<Tag, Derived<OtherTag>>> SomeMethod(T) = delete; }; But it doesn't work because there is no way for compiler to deduce OtherTag, without explicit instantiation like this Derived<tag>{}.SomeMethod<ImplicitOpToAnotherTagInstantiation, another_tag>(); // error: deleted function! Second thought: template <class Tag> struct Derived : Base { using Base::SomeMethod; int SomeMethod(const Derived&); template <class OtherTag> std::enable_if_t<!std::is_same_v<Tag, OtherTag>> SomeMethod(Derived<OtherTag>) = delete; template <class T> std::enable_if_t<!std::is_same<T, Derived> && std::is_convertible<T, Base>> SomeMethod(T) = delete; }; But next code results in compiler error, when shouldn't: Derived<tag>{}.SomeMethod(ImplicitOpToBase{}); Main usage I am trying to create some kind of a strong typedef for std::string where Base is std::string, Derived is my TaggedString, SomeMethod is std::string::assign. I want to disable assign method with types of another tag and I have some difficulties explained in the question. For the sake of the reader i am omitting the fact, that TaggedString is implicitly convertible to std::string_view. template <class Tag> struct TaggedString : std::string { using std::string::assign; TaggedString& assign(const TaggedString& other) { std::string::assign(other); return *this; } template <class OtherTag> std::enable_if_t<!std::is_same_v<Tag, OtherTag>> assign(TaggedString<OtherTag>) = delete; }; Here is something to play with.
No. There's an infinite set of possible conversions, even an infinite set of conversions to Derived<SomeUnknownType>. Your compiler cannot test every possible type T to see if ImplicitOpToAnotherTagInstantiation is perhaps convertible to Derived<T>. It could test a finite set, if you provide that. But you only have tag, a type to exclude. An infinite set of types minus one type is still an infinite set of types.
71,049,080
71,049,168
C++ how to add destructor to anonymous class?
how do you add a destructor to an anonymous class in C++? like in PHP if i want to run something when my class go out of scope it'd be $foo = new class() { public $i=0; public function __destruct() { echo "foo is going out of scope!\n"; } }; but in C++ with normal non-anonymous classes you specify the destructor with ~ClassName(){}, but anonymous classes doesn't have a name! so how do you add a destructor to class {public: int i=0; } foo; in c++? i tried using the variable name as the class name, but that didn't work: class { public: int i; ~foo(){std::cout << "foo is going out of scope!" << std::endl;} } foo; resulting in prog.cc: In function 'int main()': prog.cc:51:31: error: expected class-name before '(' token 51 | class {public: int i=0; ~foo(){std::cout << "foo is going out of scope!" << std::endl;};} foo; | ^ i also tried specifying just ~ but that didn't work either, class { public: int i=0; ~(){std::cout << "foo is going out of scope" << std::endl;} } foo; resulted in prog.cc:48:30: error: expected class-name before '(' token 48 | class {public: int i=0; ~(){std::cout << "foo is going out of scope" << std::endl;};} foo; | ^
This cannot be done in C++. However, the real C++ analogue of anonymous classes is called an anonymous namespace: namespace { struct foo { // ... whatever ~foo(); }; } // ... later in the same C++ source. foo bar; Now you can use and reference foos everywhere in this specific C++ source file. Other C++ source files may have their own anonymous namespace, with their own foos, without creating a conflict. The end result is pretty much the same thing as C-style anonymous structs (a.k.a. classes), except that they're not really anonymous, only their namespace is.
71,049,612
71,051,386
Overloading class name with integer variable
I am learning C++ using the books listed here. In particular, i read about overloading. So after reading i am trying out different examples to clear my concept further. One such example whose output i am unable to understand is given below: int Name = 0; class Name { int x[2]; }; void func() { std::cout << sizeof(Name) << std::endl; //My question is: Why here Name refers to the integer variable Name and not class named Name } int main() { func(); } When i call func, then in the statement std::cout << sizeof(Name) << std::endl;, Name refers to the int Name and not class named Name. Why is this so? I expected that this would give me ambiguity error because there are two(different) entities with the same name. But the program works without any error and sizeof is applied to int Name instead of class named Name. I have read about function overloading in the books. But not about this kind of overloading. What is it called and what is happening here. PS: I know that i can write std::cout<< sizeof(class Name); where sizeof will applied to the class named Name instead of variable int Name. Also, the example is for academic purposes. I know that use of global variable should be avoided. The question is not about how to solve this(say by not using same name for those two entities) but about what is happening.
Since you added the language-lawyer tag: When a class and a variable of the same name are declared in the same scope, then the variable name hides the class name whenever name lookup would find both of them, see [basic.scope.hiding]/2 of the post-C++20 standard draft. (Note that there was significant rework of the wording for name lookup in the current standard draft for C++23, but it should have the same effect.) I think this behavior, instead of making it an error to declare both a class and a variable of the same name in the same scope, was chosen for compatibility with C. In C the names of structs are in a separate namespace from variable names, so they are never ambiguous. For example with int Name = 0; struct Name { int x[2]; }; in C, whenever you write just Name it refers to the variable. If you want to refer to the type you must use struct Name. C++ eliminates the requirement to use the struct prefix to refer to unambiguous structs, but with the rules as they are, name lookup for both Name and struct Name will have the same results in C and C++.
71,050,254
71,050,564
OpenCV & C++: returned cv::Mat causes a Segmentation Fault
I'm writing a class that grabs frames from basler USB cameras using pylonAPI and converts them to openCV format. Here's the code of the grabbing method: std::pair<cv::Mat, cv::Mat> GrabPair() { int key; Pylon::CImageFormatConverter fmtConv; Pylon::CPylonImage pylonImg1, pylonImg2; fmtConv.OutputPixelFormat = Pylon::PixelType_BGR8packed; Pylon::CPylonImage pylonImgLeft, pylonImgRight; cv::Mat outImageL, outImageR; Pylon::CGrabResultPtr pResultLeft, pResultRight; if(cams.IsGrabbing()){ cams[leftCamIndex].RetrieveResult(1000, pResultLeft, Pylon::TimeoutHandling_ThrowException); cams[rightCamIndex].RetrieveResult(1000, pResultRight, Pylon::TimeoutHandling_ThrowException); if(pResultLeft->GrabSucceeded() && pResultRight->GrabSucceeded()){ fmtConv.Convert(pylonImgLeft, pResultLeft); outImageL = cv::Mat(pResultLeft->GetHeight(), pResultLeft->GetWidth(), CV_8UC3, (uint8_t*)pylonImgLeft.GetBuffer() ); fmtConv.Convert(pylonImgRight, pResultRight); outImageR = cv::Mat(pResultRight->GetHeight(), pResultRight->GetWidth(), CV_8UC3, (uint8_t*)pylonImgRight.GetBuffer() ); /*cv::namedWindow("OpenCV out L"); cv::namedWindow("OpenCV out R"); cv::imshow("OpenCV out L", outImageL); cv::imshow("OpenCV out R", outImageR); key = cv::waitKey(20);*/ } } return std::make_pair(outImageL, outImageR); } And this is the code fragment from main() where I try to acquire and show the grabbed frames int key; BslrCap bc(40146142, 40146151); //the grabber object bc.PrintDevicesInfo(); bc.Open(); cv::Mat raw_left, raw_right; while(1) { std::pair<cv::Mat, cv::Mat> images_pair = bc.GrabPair(); cv::Mat raw_left = images_pair.first; cv::Mat raw_right = images_pair.second; if(!raw_right.empty() && !raw_left.empty()){ cv::namedWindow("OpenCV out L"); cv::namedWindow("OpenCV out R"); cv::imshow("OpenCV out L", raw_left); cv::imshow("OpenCV out R", raw_right); key = cv::waitKey(20); } } But when I call cv::imshow I immediately receive SIGSEGV and my program crashes. If I uncomment these lines in GrabPair() code: pResultRight->GetWidth(), CV_8UC3, (uint8_t*)pylonImgRight.GetBuffer() ); /*cv::namedWindow("OpenCV out L"); cv::namedWindow("OpenCV out R"); cv::imshow("OpenCV out L", outImageL); cv::imshow("OpenCV out R", outImageR); key = cv::waitKey(20);*/ I can see two openCV windows on my screen with two captured frames. This means that both frames are captured without errors, and the problem is when I try to return std::pair from the method GrabPair() back to main() Any ideas what I'm doing wrong? Great thanks in advance!
the problem here is, that the Mat constructor using an external pointer is NOT refcounted. once you leave the GrabPair function, both Mat's are invalid (dangling pointer) you need to clone() them (deep copy of the data !) e.g. like: return std::make_pair(outImageL.clone(), outImageR.clone());
71,050,437
71,128,510
Adding elements to C++ vector
I want to learn more about C++ coding, especially to design and create a desktop application. To begin, I want to create a notification app where I can make a task by giving the task a name and content. For this, I use 2 vectors (name and content). I initialize the vectors like this: std::vector <LPWSTR> NameTask; std::vector <LPWSTR> ContentTask; After, I simply create a button to add the name and content into the vectors: if (wmId == ID_BUTTON) { //local variables (only for the Button event) int len_name = GetWindowTextLength(TextBox_Name) + 1; //give the lenght value of the text in the textbox int len_content = GetWindowTextLength(TextBox_content) + 1; //give the lenght value of the text in the textbox wchar_t Text_name[100] = L""; //Wchar is compatible with LPWSTR wchar_t Text_content[100] = L""; //Wchar is compatible with LPWSTR // get the text of the Text edit and put it in local variable name and content GetWindowText(TextBox_Name, Text_name, len_name); GetWindowText(TextBox_content, Text_content, len_content); //verify if the texts are empty if (wcslen(Text_name) == 0 || wcslen(Text_content) == 0) { MessageBox(hWnd, L"name and content can't be empty", L"MessageBox", MB_OK); } else { NameTask.push_back(Text_name); // set name of task in vector of NameTask ContentTask.push_back (Text_name); // set content of task in vector of ContentTask //ComboBox_AddString(Combobox, Text_name); // add the title of the task in the combotext //SetWindowText(TextBox_Name, L""); //empty the textbox SetWindowText(TextBox_content, NameTask.at(0)); // visualize first element of vector name } } The problem that I have is that, when I add a new element to the vector, and then I go to visualize it, it always shows me the last element added. Even when I use SetWindowText(TextBox_content, NameTask.at(0)); And when I use another button to visualize the name and content, it gives a strange output:
I change it and it work. it may not be the ideal and correct way but i will let it how it is. if (wmId == ID_BUTTON) { //local variables (only for the Button event) int len_name = GetWindowTextLength(TextBox_Name)+1; //give the lenght value of the text in the textbox int len_content = GetWindowTextLength(TextBox_content)+1; //give the lenght value of the text in the textbox wchar_t Text_name[len] = L""; //Wchar is compatible with LPWSTR wchar_t Text_content[len] = L""; //Wchar is compatible with LPWSTR // get the text of the Text edit and put it in local variable name and content GetWindowText(TextBox_Name, (LPWSTR) Text_name, len_name); GetWindowText(TextBox_content, (LPWSTR)Text_content, len_content); //verify if the texts are empty if (len_name == 1 || len_content == 1) { MessageBox(hWnd, L"name and content can't be empty", L"MessageBox", MB_OK); } else { NameTask.push_back(Text_name); // set name of task in vector of NameTask ContentTask.push_back(Text_content); // set content of task in vector of ContentTask ComboBox_AddString(Combobox,Text_name); //set name in combobox SetWindowText(TextBox_Name, L""); //empty the textbox SetWindowText(TextBox_content, L""); //empty the textbox } }
71,050,636
71,050,704
Unique_ptr with custom deleter
Here is a MRE of my code: #include <memory> struct Deleter { void operator() (A* a) {} }; class A { A(int a) {} }; int main() { std::unique_ptr<A, Deleter> unique = std::make_unique<A, Deleter>(5); } I get this error: error C2664: 'std::unique_ptr<A,std::default_delete<A>> std::make_unique<A,Deleter,0>(Deleter &&)': cannot convert argument 1 from 'int' to 'Deleter &&' How should I call A constructor with std::make_unique when I use a custom deleter like that?
You cannot use std::make_unique with a custom deleter. You’ll need to use the regular constructor instead: auto unique = std::unique_ptr<A, Deleter>(new A(5), Deleter()); Of course this will still require you to fix the rest of your code: make the constructor of A public, and declare A before Deleter. And you’d need to replace new A(…) by the proper construction that matches the custom Deleter. And it’s worth noting that this might leak memory if the Deleter constructor throws, so you need to make sure that it doesn’t do that.
71,050,669
71,050,758
C++ Polymorphic behaviour with global array of Base Class type
Why is the code below able to demonstrate polymorphic behaviour TwoDShapes* s2d[2]; int main() { Circle c1(/*parameter*/); Rectangle s1(/*parameter*/); s2d[0] = &c1; s2d[1] = &s1; for (int i = 0; i < 2; i++) cout << s2d[i]->toString() << endl; return 0; } BUT the code below throws an error void test(); TwoDShapes* s2d[2]; int main() { test(); for (int i = 0; i < 2; i++) cout << s2d[i]->toString() << endl; return 0; } void test() { Circle c1(/*parameter*/); Rectangle s1(/*parameter*/); s2d[0] = &c1; s2d[1] = &s1; } I noticed that when I try to initialise the contents of the array within another function other than main(), the Base class'(TwoDShapes) toString() method gets invoked instead of the Derived classes'(Circle and Rectangle) toString() method. But when I do the same thing within main(), it is able to display polymorphic behaviour. Below is my Base and Derived classes // Base Class class TwoDShapes { public: TwoDShapes(); virtual string toString(); string TwoDShapes::toString() { return "Inside Base Class toString method"; } // Derived classes class Circle : public TwoDShapes { public: Circle(/*parameter*/); string toString() override; }; string Circle::toString() { return "Inside Circle toString method"; } *Edit 1: Included a more complete code
c1 and s1 are local variables to function test. The moment it finishes, you can no longer access them. So, s2d[i] contains a pointer to some local variable of test function. By the time this code cout << s2d[i]->toString() << endl; runs, the test function already terminated. So all local variables are destroyed. Calling toString() function of a destroyed object has undefined behavior. You can no longer access them.
71,050,980
71,051,677
Python to .cpp and back again with ctypes via an .so
I'm doing something stupid, but not seeing what... I've reduced my problem to the below (absurd) example - but it highlights where my issue is - I'm clearly not able to pass data into and/or return from, c++, coherently. test.cpp extern "C" double reflect(double inp){ return inp; } The above is compiled with: g++ -c -Wall - Werror -fPIC test.cpp -o testO.o g++ -shared -o testSO.so testO.o Output file definitions are included only as I'd use them in real-problem .py import ctypes hdl = ctypes.cdll.LoadLibrary(r"C:\Windows\path\to\testSO.so") So, my returns hdl.reflect(1) >>> 1 (no ctypes conversion, but erm, OK) hdl.reflect(1.1) >>> Failure (this is expected) hdl.reflect(ctypes.c_int(1)) >>> 1 (right well, c_int to c_double looks like it could implicitly work) hdl.reflect(ctypes.c_float(1.1)) >>> 1006192077 (WTF?!?) hdl.reflect(ctypes.c_double(1.2)) >>> 858993459 (WTF?!?!) OS is windows 10, compiler is minGW-W64 8.1.0, python is 3.8 (anaconda) I've ran DLLs before and I've compiled my own .c into python modules before - but for the life of me I cannot see what I'm doing wrong here.....!?! edit: Corrected typo as pointed out by Topological Sort (path to .so was correct in code, was missing trailing " here)
Object files and shared libraries do not contain any information about the types of function parameters or return types, at least not for C linkage functions. Therefore ctypes has no way of knowing that the function is supposed to take a double argument and return a double. If you call it with anything else than ctypes.c_double as argument, you will have undefined behavior. But you can set the argument types up for automatic conversion to the correct ctypes type (see below). ctypes also assumes that the return type is int. If that is not the case, you are supposed to set the return types correctly before calling. In the following I also set up the argument types so that ctypes automatically uses the correct type in calls: reflect = hdl.reflect reflect.argtypes = [ctypes.c_double] reflect.restype = ctypes.c_double reflect(1.2)
71,051,289
71,051,442
Im trying to create a a code that count numbers divisible by 9 by putting numbers into an array and count the numbers in it
Im trying to create a a code that count numbers divisible by 9 by putting numbers into an array and count the numbers in it but it only prints 1 instead of the number of numbers divisible by 9 please help me i want to use array to count those numbers #include <iostream> using namespace std; int main(){ int a,b,i; int numbers[]={i}; cin >>a>>b; for (i=a; i<=b; i++) if (i%9==0){ cout << sizeof(numbers)/sizeof(numbers[0]); } }
Nowhere in your code are you adding numbers to the array. Anyhow, it is not possible to add elements to arrays, because they are of fixed size. Your array has a single element. Moreover, int numbers[]={i}; is undefined, because i has not been initialized. Further, it is not clear what is the purpose of sizeof(numbers)/sizeof(numbers[0]) in your code. sizeof(numbers) is the size of a single int because the array has a single element. sizeof(numbers[0]) is the size of a single int as well. Hence the result is 1 always. (Its a compile time constant btw.) If you want to count how many numbers fullfil some condition you best use a counter and print its value after the loop: #include <iostream> int main(){ int a,b; cin >> a >> b; unsigned counter = 0; for (int i=a; i<=b; i++) { if (i%9==0){ ++counter; } } std::cout << counter; } i want to use array for my learning porpuses please help me You chose the wrong example to train working with arrays, because as already mentioned, arrays have fixed size. It is an opportunity to learn about std::vector. You can add elements to a std::vector at runtime and query its size: #include <iostream> #include <vector> int main(){ int a,b; std::vector<int> by9divisables; std::cin >> a >> b; for (int i=a; i<=b; i++) { if (i%9==0) { by9divisables.push_back(i); } } std::cout << by9divisables.size(); } However, other than to see how std::vector is working, the vector has no place in this code. As you can see above, the result can be obtained without it.
71,051,368
71,053,082
Synchronizing between a local and remote GUI
Consider the following GUI: when the user press the + button the value is incremented to 6. However on another computer another user is running the same GUI. The two GUIs have to stay in sync. If one of the users press the + button the value should be updated for both GUIs. The remote GUI, the client, communicate with the local server via a simple protocol. The communication takes the form of a cmd sent from the client and a response sent from the server. There are two commands: 1. cmd:"GET_VALUE", response: "5" 2. cmd: "INCREMENT", response: "OK" Unfortunately the client has to poll GET_VALUE to be notified, but the protocol albeit flawed can not be changed. How can I implement this in Qt, C++? So far I have come up with the following classes (rough outline): class Model { public: std::atomic<int> m_value; }; class Widget : public QWidget { public slots: void incrementClickedLocally(); // must update Model::m_value somehow void valueChangedFromModel(int value); // will update the QLineEdit }; // Reads synchronously from TCP/IP using WinSocket and works on the Model class RemoteHandler : public QThread { private: void run override(); }; I would like to use signals/slots to communicate across the threads. However it seems that the RemoteHandler can not use signal/slots to get the Model::m_value since slots can not have return types? Further it would be convenient to emit a valueChanged signal from Model to notify Widget. However in order to do that Model must be a QObject. It seems that when Model becomes a QObject there are many potential thread problems I have to look out for? As it is Model is threadsafe. I can therefore request Model::m_value directly from the non main thread in RemoteHandler while the Widget may be accessing the same variable simultaneously from the main thread.
It cannot work with those commands. The logic is well-known from the design of multi-core CPU's. You need Compare-and-Swap (CAS), Load-Link/Store Conditional (LL/SC) or something equally powerful. With the weak protocol you have, it can be proven that the race conditions are unsolvable.
71,051,954
71,057,856
Converting Metal Shader texture type from 2D to 2D Multisample
I am following a tutorial by 2etime on YouTube about Apple's Metal graphics API. Everything works as intended, but when I try to change the view's sample count, I get a lot of errors. The errors, though, are easily fixed. So far, I've changed the sample count in every file, but I am stuck at the shaders. To change the view's sample count, you have to change the texture sample count (at least in my case), and to change the texture sample count, you have to change the texture type to multisample. This is easily done. However, after this change, I get errors from the shaders. It looks like the fragment shader uses texture2d, and I need to change it to texture2d_ms, but when I do so, I get error saying that 'sample' function is not valid. I will post the code and the error. I've tried searching on the internet, but I can't seem to find anything. FinalShaders.metal #include <metal_stdlib> #include "Shared.metal" using namespace metal; struct FinalRasterizerData { float4 position [[ position ]]; float2 textureCoordinate; }; vertex FinalRasterizerData final_vertex_shader(const VertexIn vIn [[ stage_in ]]) { FinalRasterizerData rd; rd.position = float4(vIn.position, 1.0); rd.textureCoordinate = vIn.textureCoordinate; return rd; } fragment half4 final_fragment_shader(const FinalRasterizerData rd [[ stage_in ]], texture2d_ms<float> baseTexture) { sampler s; float2 textureCoordinate = rd.textureCoordinate; textureCoordinate.y = 1 - textureCoordinate.y; float4 color = baseTexture.sample(s, textureCoordinate); return half4(color); } Shared.metal #ifndef SHARED_METAL #define SHARED_METAL #include <metal_stdlib> using namespace metal; struct VertexIn { float3 position [[ attribute(0) ]]; float4 color [[ attribute(1) ]]; float2 textureCoordinate [[ attribute(2) ]]; float3 normal [[ attribute(3) ]]; float3 tangent [[ attribute(4) ]]; float3 bitangent [[ attribute(5) ]]; }; struct RasterizerData{ float4 position [[ position ]]; float4 color; float2 textureCoordinate; float totalGameTime; float3 worldPosition; float3 toCameraVector; float3 surfaceNormal; float3 surfaceTangent; float3 surfaceBitangent; }; struct ModelConstants{ float4x4 modelMatrix; }; struct SceneConstants{ float totalGameTime; float4x4 viewMatrix; float4x4 skyViewMatrix; float4x4 projectionMatrix; float3 cameraPosition; }; struct Material { float4 color; bool isLit; bool useBaseTexture; bool useNormalMapTexture; float3 ambient; float3 diffuse; float3 specular; float shininess; }; struct LightData { float3 position; float3 color; float brightness; float ambientIntensity; float diffuseIntensity; float specularIntensity; }; #endif And the error: No member named 'sample' in 'metal::texture2d_ms<float, metal::access::read, void>' I know it clearly says that 'sample' is not existent, but I can't find any solution. When I removed it, and replaced the return with different value, I only see a lot of green/yellow lines, and no 3d objects. Thanks for any help! (the shader the error is happening in is the fragment one in final shaders.metal)
Sampling in a way that sample function means doesn't make sense for multisampled textures. What you are looking for instead is reading the exact sample value at a given texcoord. If you look in the Metal Shader Language specification, in section 6.12.8 it describes which functions exist for 2D multisampled textures. Those include: Tv read(uint2 coord, uint sample) const Tv read(ushort2 coord, ushort sample) const uint get_width() const uint get_height() const uint get_num_samples() const In read function, coord means pixel coordinates, so they would go from 0 to get_width() on X axis and from 0 to get_height() on Y axis. sample is the index of the sample, so it would be from 0 to get_num_samples()
71,052,051
71,052,119
Does move constructor only affect the memory space pointed to by the pointer member of the class?
For example, this Code: struct President { std::string name; std::string country; int year; President(std::string p_name, std::string p_country, int p_year) : name(std::move(p_name)), country(std::move(p_country)), year(p_year) { std::cout << "--constructed\n"; } /* President(const President& other) : name(std::move(other.name)), country(std::move(other.country)), year(other.year) */ President(const President& other) : name(other.name), country(other.country), year(other.year) { std::cout << "--copy constructed\n"; } President(President&& other) : name(std::move(other.name)), country(std::move(other.country)), year(other.year) { std::cout << "--moved\n"; } ~President() { cout << "\n"<< &name << " " << country << endl; std::cout << "--destruct\n"; } President& operator=(const President& other); }; Whether it is a move constructor or a copy constructor, they will cause the values of the three data members to be stored in the new memory, and the old memory will be released. And my meaning is right?
And my meaning is right? Sorry, no. Your move constructor will work as you describe, in that it will 'steal' the contents of the name and country member variables from other, but the copy constructor will not. std::move does nothing with a const object and you should remove it from your copy constructor. After all, the operative word is copy, right? It's worth noting that you don't need to write your own copy or move constructors at all here ('rule of zero'). The default constructors synthesized by the compiler will work just fine. Oh, and std::move on a primitive type such as an int also does nothing - the variable will just be copied whether you include it or not.
71,052,442
71,052,479
"lvalue required as left operand of assignment" for all of my if/else statements. What have I done wrong?
I'm making a basic calculator that uses if/else statements to select a sign to use in the equation. All of the else/if statements are reporting an error: error: lvalue required as left operand of assignment #include <iostream> using namespace std; int main() { //declare variables int num1; int num2; int sol; bool sign; //prompt for num1 cout << "Greetings! Please enter a number." << endl; cin >> num1; //prompt for num2 cout << "Great! Now, please enter the second number." << endl; cin >> num2; //prompt for sign cout << "Almost there! Now, please enter the sign you wish to use in the equation." << endl; cin >> sign; //arguments if (sign == '+') { num1 + num2 = sol; } else if (sign == '-') { num1 - num2 = sol; } else if (sign == '*') { num1 * num2 = sol; } else if (sign == '/') { num1 / num2 = sol; } else { cout << "Sorry, that is not a valid symbol." << endl; return 0; } //print results cout << "The solution is: " << sol << endl; return 0; }
You have your assignments reversed. = is not a commutative operator. They should all be of the form sol = num1 op num2 What you are trying to do is assign the (uninitialised) value of sol to the unnamed temporary that results from the calculation. Happily this is a hard error with fundamental types.
71,052,452
71,052,553
Aggregate initialization of a derived class with designator
From cppreference we can know: Since C++17 for derived types: If the initializer clause is a nested braced-init-list (which is not an expression), the corresponding array element/class member /public base (since C++17) is list-initialized from that clause: aggregate initialization is recursive. Since C++20 for aggregate types: Using .designator = arg to specify initialized members is no longer an extension to C, but is supported by the C++ standard. struct A { int a; int b; }; struct B : A { int c; }; void test() { A a{.a = 1, .b = 42}; // a.a = 1 && a.b = 42 B b{{.a = 1, .b = 2}, 42}; // b.a = 1 && b.b = 2 && b.c = 42 } Very simple and intuitive, right? But let's complicate things a bit. constexpr int a_very_very_special_value = 42; struct A { int a; int b; }; struct B : A { int c = a_very_very_special_value; int d; }; void test() { A a{.a = 1, .b = 42}; // a.a = 1 && a.b = 42 B b{{.a = 1, .b = 2}, .d = 9}; // Ouch! Mixture of designated and non-designated initializers in the same initializer list is a C99 extension. } The above situation should be very common, we want a member data to keep its default value, but the standard requires us that .designator = arg must be after all parameters without .designator, but, this is impossible, how do we give our base a name? Like .base_type_name = {.a = 1, .b = 2}? One might think that things like inheritance are totally unnecessary, we can do it like this. struct A { int a; int b; }; struct B { A base; int c = a_very_very_special_value; int d; }; void test() { A a{.a = 1, .b = 42}; // a.a = 1 && a.b = 42 B b{.base = {.a = 1, .b = 2}, .d = 9}; // b.base.a = 1 && b.base.b = 2 && b.c = a_very_very_special_value && b.d = 9 } Great, what else is unsatisfactory? Unless we have an interface like this. void test(A &a) { if (a.a + a.b > 42) { std::cout << "42\n"; } else { std::cout << "0\n"; } } void test() { A a{.a = 1, .b = 42}; B b{.base = {.a = 1, .b = 2}, .d = 9}; test(a); test(b); // No matching function for call to 'test' } Those who are familiar with the memory model will definitely think that it is very simple, just add a forced type cast, anyway, the data of the original base class is in the head of the data. void test() { A a{.a = 1, .b = 42}; B b{.base = {.a = 1, .b = 2}, .d = 9}; test(a); // test(b); test((A&)b); } However, one very important thing is that C++ supports multiple inheritance. If our original design idea is to form a complete type by inheriting multiple structures, what should we do? Further, if our interface is separate for each inherited type, then we need to give a type cast method for all base classes, and also know the offset of the data in the type, if the data from the base class is not completely placed at the head of the class, the result will absolutely be wrong.
As you've discovered, you can't use both designated initialization and also name the base class. In order to do that, the language needs to be extended to support that case. See P2287R1, which I have not finished yet. Unfortunately, won't make C++23. Until the language directly supports designated the base class (or directly designated members of the base class), if you want to use designated initializers your best bet is to have the base classes as members, as you've clearly documented.
71,052,584
71,053,275
Linux - Open socket for specific network adapter
The problem I have a computer that is supposed to connect to two machines (or rather sets of individual devices) via TCP. To make things tricky, these two machines share the same IP address range and also have partially identical addresses, only one is connected via one ethernet adapter and the other one via a second ethernet adapter. Note: The address ranges were not defined by me, but by the manufacturers of these machines. I unfortunately have to live with them, as they are. The program that should do that job is written in C/C++. The connections are outgoing from the program's point of view, so I can't just bind incoming connections and keep their id. Possible solution After some research (e.g. here: Problems with SO_BINDTODEVICE Linux socket option), I tried to bind the socket to a device using setsockopt(socket, SOL_SOCKET, SO_BINDTODEVICE, "adapter name", strlen("adapter name"); As it turns out, this would only work, if the program was run with superuser privileges, which I would try to avoid. Otherwise, the function returns an error code, which translates to permission denied (I forgot the exact phrase). Other solutions? Is there any other way, how I could achieve that?
Just pinning the sockets to a specific interface wouldn't do the job, since there are much more things going on... If you connect say to 192.168.0.3, the kernel looks into the routing table to find the right interface to send the packet over. You cannot have two entries in the routing table with the same subnet specification (192.168.0.0/24) if you want to use IP communication. There are two solutions that come into my mind: setup prerouting NATs for the adapters to map the addresses. For example you can map all source addesses from packages recieved by eth0 into the 192.168.0.0\24 range and all those recieved by eth1 to 192.168.1.0\24. If you add this address translation in the prerouting filter chain, the kernel won't even notice that the subnets internally use the same ip address range. If there are no duplicated ip addresses (like e.g. 192.168.0.2 in both the networks), you can setup a bridge interface. The bridge behaves like one interface, that is connected to both the networks. A bridge behaves just like a software switch. To the kernel (and to your program) it looks, as if there was only one adapter, where all the devices are plugged into. Both solutions require superuser priviledges to setup, but after you have setup them once, your program won't need them.
71,052,805
71,053,030
Error nested std::thread inside a thread throws an error
I'm trying to get this simple test to create a nested thread inside another thread, but it keeps failing. Tried removing this nested function and the code works fine on its own. Code example/test: #include <thread> #include <iostream> #include <vector> void simple() { std::cout << "\nNested Thread"; } void function(int number, int* sum, std::vector<std::thread>& thread_group) { *sum += number; // Starting this nested function simple() in a thread causes errors. // The problem occurs even when there's only a single iteration of the loop. // Without it the code works fine, even with 10000 iterations. std::thread ct(simple); thread_group.push_back(std::move(ct)); } int main(){ // Container for storing threads std::vector<std::thread> thread_group; int sum = 0; for (int n = 1; n <= 10; n++) { std::thread t(function, n, &sum, std::ref(r), std::ref(thread_group)); // Add the newly created thread to the container thread_group.push_back(std::move(t)); } // Wait for all threads to finish join_all(thread_group); return 0; } That being said, I need to find a way call an independent function that could run without blocking the execution of the rest of the code. Threading or some other way of multiprocessing is very important in my program because each function is recursive and keeps calling multiple copies of itself with different parameters untill a condition is satisfied. I don't know whether it's even possible in the std::thread library. Tried using Poco and boost, but was faced with other problems, so decided to stick to std::thread instead. I'm using Visual Studio 2022 on Windows 10.
You are reading and writing to sum and thread_group from multiple threads at the same time. A simple solution is you make sure that only one thread at a time has access to them by using a std::mutex and locking it while accessing those variables. You also need to make sure that all threads are finished working with thread_group before it gets destroyed. I added a counter and a std::condition_variable to take care of that. Example (using C++20 std::jthreads instead to not have to call the non-existing join_all function): #include <condition_variable> #include <iostream> #include <list> // using list instead of vector to avoid realloc #include <mutex> #include <thread> #include <vector> using container = std::list<std::jthread>; void simple() { std::cout << "Nested Thread\n"; } void function(int& counter, std::mutex& mtx, std::condition_variable& cv, container& thread_group) { std::lock_guard lock(mtx); thread_group.emplace_back(simple); ++counter; // so that main thread can check that all is done cv.notify_one(); // signal main that the work is done } int main(){ // Container for storing threads container thread_group; std::mutex mtx; std::condition_variable cv; int starting_threads = 10; int counter = 0; for (int n = 1; n <= starting_threads; n++) { std::lock_guard lock(mtx); // lock while adding thread // Add thread to the container thread_group.emplace_back(function, std::ref(counter), std::ref(mtx), std::ref(cv), std::ref(thread_group)); } std::unique_lock lock(mtx); // wait until all threads are done with thread_group // before letting thread_group go out of scope and get // destroyed while(counter < starting_threads) cv.wait(lock); std::cout << thread_group.size() << '\n'; // wait for all threads to finish (jthread's auto-join) } Possible output: Nested Thread Nested Thread Nested Thread Nested Thread Nested Thread Nested Thread Nested Thread Nested Thread Nested Thread 20 Nested Thread
71,052,971
71,085,072
How to store boost::hana::map inside a class?
I want to store boost::hana::map inside a class so that I can write code like this inside the class: if constexpr (boost::hana::contains(map_, "name"_s)){ std::cout << map_["name"_s] << std::endl; } But I am getting an error: note: implicit use of 'this' pointer is only allowed within the evaluation of a call to a 'constexpr' member function With this->map_: note: use of 'this' pointer is only allowed within the evaluation of a call to a 'constexpr' member function The most interesting thing is if I write like this: if (boost::hana::contains(map_, "name"_s)){ std::cout << map_["name"_s] << std::endl; } I get an error that there is no such field (it really may not exist, that's why there was an if constexpr). And yet, it works like this(WHY?!): auto map = map_; if constexpr (boost::hana::contains(map, "name"_s)){ std::cout << map["name"_s] << std::endl; } I absolutely don't understand how it works. How is boost::hana::map supposed to be used in this case? Full example Stupid workaround
Yes, using this here appears to be right out. Since the information you are trying to access should be accessible at compile-time, one simple workaround would be to use the type of the entire expression. void print_name() { if constexpr (decltype(boost::hana::contains(map, "name"_s)){}) { Print(map["name"_s]); } } Note that hana::contains returns an object derived from std::integral_constant so the contained value is static constexpr, and it implicitly converts to bool.
71,053,102
71,060,949
GDB issue when using enum with type definition in c++
I have an enum with an explicit underlying type definition like this: enum test : uint16_t { test_x = 0x7fff, // 0111 1111 1111 1111 test_y = 0x8000 // 1000 0000 0000 0000 }; And variables in my code that are assigned the enum values like this: test num1 = test_x; test num2 = test_y; When I try to look at the value using GDB, I get this kind of result: (gdb) print num1 $1 = test_x (gdb) print num2 $2 = (test_y | unknown: -65536) Why is num2 acting so strange? Its value is in the range of the type I declared, so what is wrong with this configuration? I will also point out that this happens not just with uint16_t but with uint32_t and the values test_x = 0x7fffffff, test_y = 0x80000000. Edit I am compiling with GNU GCC version: 9.3.0 on ARM processor platform and using GDB version 8.1.0.
I will answer my own question after getting some helpful pointers in the comments. This turned out to really be a bug in the GDB version I was using. upgrading to a newer version solves this issue. (I upgraded from 8.1 to 10.2) (gdb) print num1 $1 = test_x (gdb) print num2 $2 = test_y (gdb) show version GNU gdb (GDB; JetBrains IDE bundle; build 157) 10.2 ...
71,053,504
71,060,859
Strange behaviour insert_one mongocxx 3.6
Working with mongocxx I am trying to retrieve the object id assigned by mongodb when I insert a new object in a collection(insert_one method), and convert this id into a string. This is the code: const mongocxx::database& db = _pClient->database(_dbName.c_str()); mongocxx::collection& collection = db.collection(collectionName.c_str()); auto retval = collection.insert_one(view); bsoncxx::oid oid = retval->inserted_id().get_oid().value; std::string str = oid.to_string() Unfortunately it looks like when I try to convert the object id to a string the string is unreadable (corrupted like). I am using mongocxx version 3.4 and mongodb 4.0.28 (the two versions should be compatible according to the mongodb website). Do you know what could be the problem here? Here what I can see through the debugger: visual studio debugger Here what I can see thorugh the mongodb client: mongodb client
The debugger is showing you the individual bytes in decimal. I used the mongo shell to convert these to hex, you can see that it is indeed the ObjectID you were looking for, it just looks strange in decimal mongos> [98,3,-24,41,-88,89,0,0,-93,0,88,-78].map(n=>("0" +((n & 255).toString(16))).slice(-2)).join("") 6203e829a8590000a30058b2
71,053,575
71,056,261
vector::push_back using std::move for internal reallocations
A type X has a non-trivial move-constructor, which is not declared noexcept (ie. it can throw): #include <iostream> #include <vector> #include <memory> struct X { X()=default; X(X&&) { std::cout << "X move constructed\n"; } // not 'noexcept' X(const X&) { std::cout << "X copy constructed\n"; } }; struct test { X x; }; int main() { static_assert(std::is_nothrow_move_constructible_v<X> == false); static_assert(std::is_nothrow_move_constructible_v<test> == false); std::vector<test> v(1); v.push_back(test{}); // internal object re-allocation, uses copy-constructor } When calling push_back on a vector<test>, internal reallocations cause existing objects to be copied, which is expected. The output is: X move constructed X copy constructed Apparently, the second line is related to internal object reallocation. Now an unrelated std::unique_ptr<int> is added to test: struct test { std::unique_ptr<int> up; X x; }; The output becomes: X move constructed X move constructed Why is internal reallocation using the move-constructor this time ? Technically, X(X&&) can still throw an exception; wouldn't that violate the strong exception guarantee of push_back ? compiler is gcc 11.2.1 and/or clang 12.0.1
According to [vector.modifiers]/2 if the element type of std::vector is not copy-insertable and not nothrow-move-constructible, then an exception thrown from a move constructor of the element type results in an unspecified state of the container. std::vector must prefer the copy constructor if the type isn't nothrow-movable, so that the exception guarantees can be preserved, but if that isn't possible, it is impossible to give strong exception guarantees.
71,054,550
71,055,477
Boost multiprecision rounding towards 0
The code below compiles just fine on Windows using VC++: #include <boost/multiprecision/cpp_int.hpp> #include <boost/multiprecision/cpp_dec_float.hpp> #include <iostream> namespace mp = boost::multiprecision; using BigFloat = mp::cpp_dec_float_50; using BigInt = mp::uint256_t; template <int decimals = 0, typename T> T floorBI(T const& v) { static const T scale = pow(T(10), decimals); if (v.is_zero()) return v; // ceil/floor is found via ADL and uses expression templates for // optimization if (v < 0) return ceil(v * scale) / scale; else // floor is found via ADL and uses expression templates for optimization return floor(v * scale) / scale; } int main() { BigFloat A = 3; BigFloat B = 2; static_cast<BigInt>(floorBI<0>(static_cast<BigFloat>(A) / static_cast<BigFloat>(B))); return 0; } , however with GCC (for Android and iOS) there's a problem seemingly with templates. The particular error(s) for a template which 'should' be matched read(s) ..\boost/multiprecision/detail/default_ops.hpp:3745:18: note: candidate template ignored: could not match 'expression' against 'number' UNARY_OP_FUNCTOR(ceil, number_kind_floating_point) ^ ..\boost/multiprecision/detail/default_ops.hpp:3745:18: note: candidate template ignored: could not match 1 against 0 ..\boost/multiprecision/detail/default_ops.hpp:3745:18: note: candidate template ignored: requirement 'boost::multiprecision::number_category<boost::multiprecision::backends::cpp_int_backend<256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void> >::value == number_kind_floating_point' was not satisfied [with Backend = boost::multiprecision::backends::cpp_int_backend<256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>] ..\boost/multiprecision/detail/default_ops.hpp:3745:18: note: candidate template ignored: could not match 1 against 0 VC++ handles all of it 'just fine'. Waiting for @Sehe to come around;]
Like many people already suggested, expression templates are the culprit: T is deduced as boost::multiprecision::detail::expression< boost::multiprecision::detail::divides, boost::multiprecision::number< boost::multiprecision::backends::cpp_dec_float<50>>, boost::multiprecision::detail::expression< boost::multiprecision::detail::multiply_immediates, boost::multiprecision::number< boost::multiprecision::backends::cpp_dec_float<50>>, boost::multiprecision::number< boost::multiprecision::backends::cpp_dec_float<50>>, void, void>, void, void> Which is not constructible from int: T(10). Instead, either force the type: std::cout << floorBI<0>(BigFloat(A / (B * C))) << "\n"; Or be smarter about deducing the type. DEMONSTRUCTION Live On Coliru #include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/multiprecision/number.hpp> #include <iostream> namespace bmp = boost::multiprecision; using BigFloat = bmp::cpp_dec_float_50; template <int decimals = 0, typename T> std::enable_if_t<not bmp::is_number_expression<T>::value, T> floorBI(T const& v) { static const T scale = pow(T(10), decimals); if (v.is_zero()) return v; // ceil/floor is found via ADL and uses expression templates for // optimization if (v < 0) return ceil(v * scale) / scale; else // floor is found via ADL and uses expression templates for optimization return floor(v * scale) / scale; } template <int decimals = 0, typename Expr> auto floorBI(Expr const& expr, std::enable_if_t<bmp::is_number_expression<Expr>::value, void>* enable = nullptr) { return floorBI<decimals, typename Expr::result_type>(expr); } int main() { BigFloat A(3), B(2), C(2); std::cout << floorBI<1>(BigFloat(A / (B * C))) << "\n"; std::cout << floorBI<1>(A / (B * C)) << "\n"; std::cout << floorBI<2>(BigFloat(A / (B * C))) << "\n"; std::cout << floorBI<2>(A / (B * C)) << "\n"; B *= -1; std::cout << floorBI<1>(BigFloat(A / (B * C))) << "\n"; std::cout << floorBI<1>(A / (B * C)) << "\n"; std::cout << floorBI<2>(BigFloat(A / (B * C))) << "\n"; std::cout << floorBI<2>(A / (B * C)) << "\n"; } Prints 0.7 0.7 0.75 0.75 -0.7 -0.7 -0.75 -0.75
71,054,845
71,055,091
Partial deduction of template parameter using constructor
I have seen this asked before in several ways, and all the solutions are always the same: use a helper function or even use nested classes. For me, both of those solutions look clumpsy. So I wonder how come in the c++17/c++20 era there is not better solution to this problem: EDIT: The question here is if there is any method to use impl<int> i(b);, because currently compiler fails due to the lack of second template argument. template<class T1, class T2> struct impl { impl(const T2& _t2) : t2(_t2) {} T1 t1; const T2& t2; }; int main() { int a{}; double b{}; impl<int, double> i(b);//This works... impl<int> i(b);//... but this doesn't due to lack of 2nd template parameter!!! } I understand that partial spetialization can present problems in some cases, but it is not possible to use CTAD or any other method in this case??? If so, how?
I most often use a "type tag" to overcome this kind of problems. It also comes in handy for similar issues, like the lack of partial specialization of function templates. #include <type_traits> template<typename T> struct type_t{}; template<typename T> constexpr type_t<T> type; template<class T1, class T2> struct impl { impl(const T2& _t2, type_t<T1> = {}) : t2(_t2) {} T1 t1; const T2& t2; }; int main() { int a{}; double b{}; impl<int, double> i(b);//This works... impl j(b, type<int>); // This works as well static_assert(std::is_same_v<decltype(j),impl<int, double>>); }
71,055,422
71,056,251
C++ vector of vector conversion
I am fairly new to C++ and this might be a dumb question. If I have 2 vectors, vector<vector< double >> v1 , has values and const vector<vector< double> * > * v2, has no values . How would I go about storing the elements from v1 to v2 or would it be possible to cast v1 as const vector<vector< double> * > *
v1 is a vector of vectors, i.e. each element of v1 is a vector of type vector<double>. v2 is a pointer to a vector of pointers, that is it points to a vector, which has pointers (to other vectors) as elements. As you can see, v1 and v2 are completely different, in terms of types and binary layout, so no, you cannot cast one to another and have a valid program. Assuming that with v2 you want to pass a list of pointers to v1, e.g. as a function argument, the way to do this is to construct a vector of pointers, where each element would be a pointer to the corresponding element of v1: void foo(const vector<vector<double>*>* v2); void bar(vector<vector<double>> const& v1) { // Allocate a vector of pointers vector<vector<double>*> vp(v1.size(), nullptr); // Initialize the pointers to point to v1 elements for (std::size_t i = 0u, n = v1.size(); i < n; ++i) { vp[i] = &v1[i]; } // Pass the pointer to the vector of pointers to your destination foo(&vp); } It should be noted that this code is not cheap as it will have to allocate dynamic memory and initialize the vector of pointers. If your goal was to save performance on copying the data, you should pass a reference to the original vector instead (i.e. vector<vector<double>> const&).
71,055,837
71,060,671
Purposeful random memory allocations
For an experiment, I want to measure time it takes to find a given record with random memory access. The record is a simple class: template<class TKey, class TData> class Record { TKey key; TData data; public: Record(TKey key, TData data) { this->key = key; this->data = data; } }; Now I simply allocate memory and insert some records. (Please ignore some syntax mistakes...) const int size = 1_000_000; Record<int, int> ** data = new Record<int, int>*[size]; for (int i = 0; i < size; ++i) { // allocates sizeof(Record<int, int>) on heap data[i] = new Record<int, int>(i, i); } The issue is, when allocating these new Record objects, the are actually stored sequentially in memory. I want these memory locations to be random. Does C++ have any ways to accomplish this?
The best answers are commented under the question by UnholySheep and Fabian. See their comments for the correct answer.
71,055,963
71,056,056
Understanding SendMessage wparam
I am working on an MFC project, which has the following code: NMHDR pNMHDR; pNMHDR.hwndFrom = GetSafeHwnd(); pNMHDR.idFrom = GetDlgCtrlID(); pNMHDR.code = EN_CHANGE; GetParent()->SendMessage(WM_NOTIFY, (EN_CHANGE << 16) | GetDlgCtrlID(), ( LPARAM ) &pNMHDR); Please help me in understanding what (EN_CHANGE << 16) | GetDlgCtrlID() does.
Per the EN_CHANGE documentation for standard EDIT controls: wParam The LOWORD contains the identifier of the edit control. The HIWORD specifies the notification code. So, the code is taking the constant EN_CHANGE, shifting its bits to the left 16 places, and then OR'ing the bits of the control ID. Thus, EN_CHANGE ends up in bits 16-31, and the control ID ends up in bits 0-15: WPARAM ----------------------------------------------------------------- | EN_CHANGE | CtrlID | ----------------------------------------------------------------- 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 However, the code should be using the MAKEWPARAM() macro instead of shifting + OR'ing bits manually, eg: GetParent()->SendMessage(WM_NOTIFY, MAKEWPARAM(GetDlgCtrlID(), EN_CHANGE), (LPARAM) &pNMHDR); Now, that being said, a standard EDIT control sends EN_CHANGE via WM_COMMAND, not WM_NOTIFY. But a standard windowless RICHEDIT control sends EN_CHANGE via WM_NOTIFY, which carries only the control ID by itself in the wParam parameter. The command ID is carried in the NMHDR struct pointed at by the lParam parameter (except, RICHEDIT uses the CHANGENOTIFY struct, which is unrelated to NMHDR). So, this code's use of EN_CHANGE is clearly non-standard usage, using a customized parameter scheme.
71,056,992
71,057,087
Can't modify a string in C++ array
Trying to learn datastructures, I made this class for a stack. It works just fine with integers but it throws a mysterious error with strings. The class List is the API for my stack. Its meant to resize automatically when it reaches the limit. The whole code is just for the sake of learning but the error I get doesn't make any sense and it happens somewhere in some assembly code. #include <iostream> #include<string> using namespace std; class List { private: int N = 0; string* list = new string[1]; void resize(int sz) { max = sz; string* oldlist = list; string* list = new string[max]; for (int i = 0; i < N; i++) { list[i] = oldlist[i]; } } int max = 1; public: void push(string str) { if (N == max) { resize(2 * N); } cout << max << endl; list[N] = str; N++; } void pop() { cout << list[--N] << endl; } }; int main() { string in; List list; while (true) { cin >> in; if (in == "-") { list.pop(); } else { list.push(in); } } }
string* list = new string[max]; in the resize method defines a new variable named list that "shadows", replaces, the member variable list. The member list goes unchanged and the local variable list goes out of scope at the end of the function, losing all of the work. To fix: Change string* list = new string[max]; to list = new string[max]; so that the function will use the member variable. Don't forget to delete[] oldlist; when you're done with it to free up the storage it points at.
71,057,083
71,059,095
How to change the location of .pdb files for static libraries?
Now I found out I can change the .pdb file location for C++ executable projects in Linking -> Debugger in the project settings. How can I change the location for static library projects? As they do not have the Linker menu. I tried changing C/C++ -> Output files -> Program Database File Name, but without luck. They are still added to the same directory as the compiled executable.
After changing the Program Database File Name, pdb will be added to the specified directory. In addition, if the lib file directories are not changed, another pdb file will also be added aside the lib. This may be why you think it was unsuccessful, but in fact it has been done.
71,057,307
71,066,390
Drogon: how to use execSqlCoro? What headers to include?
I'm tryin to use the execSqlCoro function of Drogon. However, I am getting an error: error: unable to find the promise type for this coroutine 26 | auto municipalities = co_await db->execSqlCoro( What headers to I have to include to get the correct promise type? See tests here. I tried #include <drogon/orm/DbClient.h> #include <drogon/orm/CoroMapper.h> to no avail.
I'm the author of Drogon's coroutine subsystem. I'm sorry for the confusion. That error message shows up when you didn't mark the function that calls the coroutine having return type as Task<T> (or to be accurate, an awaitable type that is compatible with Drogon or cppcoro's coroutine concept). For example the following function: void test() { co_await drogon::sleepCoro(app().getLoop(), 1); } generates the error: error: unable to find the promise type for this coroutine 17 | co_await drogon::sleepCoro(app().getLoop(), 1); | ^~~~~~~~ This requirement is documented in Drogon's coroutine document. Just know that if you want the coroutine to yield something typed T. Then the return type will be Task<T>. Thus the the solution is to have a return type of Task<T> using namespace drogon; Task<void> test() { co_await sleepCoro(app().getLoop(), 1); } Now, why this is required. To put it very simply (and I'm forecasting C++ veterans will correct me). In C++, the coroutine body (the code that runs) has almost nothing to do with how the coroutine is executed (controlled by return_type::promise_type). Drogon provides 2 main execution modes. Task<T> and AsyncTask. Where Task<T> executes the coroutine body upon co_await while AsyncTask runs immediately, cannot be awaited and abort when exception escapes (so don't use AsyncTask unless you know what you are doing). For example, the coroutine foo always waits for 0.1 seconds then prints "hello". But we can when and how the coroutine is executed by changing the return type. template <typename Awaiter> Awaiter foo() { co_await sleepCoro(app().getLoop(), 0.1); std::cout << "hello" << std::endl; } // foo<Task<void>>(); // Nothing happens since we didn't await it. foo<AsyncTask>(); // Waits 0.1 second then print co_await foo<Task<void>>(); // Waits 0.1 second then print auto awaiter = foo<Task<void>>(); std::cout << "hi, "; co_await awaiter; // Prints "hi, ". Waits 0.1 second then print "hello" Thus the compiler complains when it can't find the promise_type to determine how to execute the coroutine.
71,058,520
71,058,879
Getting value of random address location without storing it in a variable
#include<iostream> using namespace std; struct node{ int data; node* l,*r; }; int main() { node* n1 = new node; cout<<(n1->l); return 0; } in the above code I didn't initialize struct data, l and r. so now the address stored in n1->l is CDCDCDCD. Now if I want to see the value stored in that address how to see that without storing the address in a variable.
In general, you can cast any integer to a pointer at your own risk. node* my_ptr = (node*)0xDEADBEEF; // Casting to a pointer node my_node = *(node*)0xDEADBEEF; // Casting to a pointer and dereferencing The second line is what I believe you want to do "without storing the address in a variable". However that's hacky and useful only in specific contexts, such as DLL injection.
71,058,628
71,058,689
Program gets frozen because of a loop
I'm making a program which calculates the date by giving the program a date and number of days to add to that date in input. In order to do this, I need to make a switch and make it repeat with a loop, but for some reasons, the program gets frozen and doesn't do anything after the user inserts the number of days to add. I've tried removing loop and the program works. Looking forward to someone who might help me fix this. Here's the part of the code from getting number of days to add to the end of loop: cin>>addDays; while (addDays > 0) { switch (month) { //months with 31 days case 1: case 3: case 5: case 7: case 8: case 10: { finalDay = day + addDays; if (finalDay > 31) { addDays = finalDay - 31; month++; day = 1; } break; } //months with 30 days case 4: case 6: case 9: case 11: { finalDay = day + addDays; if (finalDay > 30) { addDays = finalDay - 30; month++; day = 1; } break; } //december case 12: { finalDay = day + addDays; //oggi è 10. Voglio aggiungere 30 if (finalDay > 31) { //40 è maggiore di 31 addDays = finalDay - 31; //l'aggiunta 30 diventa 40 - 31 che fa 9 year++; day = 1; month = 1; } break; } //february case 2: { finalDay = day + addDays; if (year % 4 == 0) { if (finalDay > 29) { addDays = finalDay - 29; month++; day = 1; } } else { if (finalDay > 28) { addDays = finalDay - 28; month++; day = 1; } } break; } } }
Your loop runs until addDays falls to <= 0. The problem is, when you add addDays to day, if the resulting finalDay IS within the current month's number of days, you ARE NOT breaking the loop, and you ARE NOT adjusting the values of day or addDays either, so the loop iterates again with the same day and addDays values, calculating the same finalDay value, over and over, endlessly. That is why your program appears frozen. After fixing that, you are also not taking into account the possibility that addDays might span more than a full month's worth of days. The user could ask to add more than 1 month at a time. So you need to adjust addDays more granularly per month. Also, when the current month is 2 (February), your leap year calculation is incomplete. Being evenly divisible by 4 is not the only rule you need to check to know if the year is a leap year. A year that is evenly divisible by 4 and 100 but not evenly divisible by 400 is not a leap year. With that said, try something more like this instead: bool isLeapYear(int year) { return ((year % 4) == 0) && (((year % 100) != 0) || ((year % 400) == 0)); } int lastDayInMonth(int year, int month) { switch (month) { //months with 31 days case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31; //months with 30 days case 4: case 6: case 9: case 11: return 30; //month with 28 or 29 days case 2: return isLeapYear(year) ? 29 : 28; } return 0; } int year, month, day, addDays, lastDay; ... cin >> addDays; while (addDays > 0) { lastDay = lastDayInMonth(year, month); day += addDays; if (day <= lastDay) break; addDays -= (lastDay - day); if (++month == 13) { ++year; month = 1; } day = 1; } That being said, have a look at this answer, which wraps up this kind of logic in a reusable struct named Date that has an overloaded operator+= for adding days.
71,058,972
71,061,472
How do I clear a c variable after use to use it again?
If I send a message over serial the first time it receves the right code it works but after that it stops working. const unsigned int MAX_MESSAGE_LENGTH = 32; const char EMPTY[1] = {'\0'}; void setup() { Serial.begin(9600);//bPS } String readserial(){ char message[MAX_MESSAGE_LENGTH]; static unsigned int message_pos = 0; while (Serial.available() > 0 ){ char inbyte = Serial.read(); if(inbyte != '\n' && (message_pos < MAX_MESSAGE_LENGTH - 1)){ message[message_pos] = inbyte; message_pos += 1; } else { message[message_pos] = '\0'; //Serial.println(message); return message; } } return EMPTY; } void loop() { static String message; message = readserial(); if(message == "Hi"){ Serial.println("Hello"); }else{ //Serial.println(message); } } the output shows hello only if I say Hi first if I put anything else it just doesn't work. I have tried looking for an answer elsewhere but I am stuck.
Your message length message_posisn't being reset to zero. Whatever value it has, the value will be "kept" because you have declared it as static. If you remove the statickeyword, message_pos will be reset to zero every time you call readserial(). You can also, as pointed out, set message_posto zero as you return the string. However, because you don't actually use (or need) message_pos as static I suggest you simply remove the keyword.
71,059,078
71,061,199
Qt: Inherit QObject in parent and other QWidget subclass in child
I am writing a series of custom classes for Qt. What I need is to have a base class that has few custom signals and slots, and children classes will have it. However, I do know that inheriting from the same classes will be thrown an error. I have read the documentation but only dictates that I need to include QObject if I wish to use Q_OBJECT macro. This is the following sample code that I intend to do: class Base : public QObject { Q_OBJECT base signals here public base slots here } class Child : public QLabel, public Base { // Other codes here } Will it be possible this way? Since I only wish to use Qt to connect with all children inherits from the parent class.
Multiple inheritance from QObject will not work for several reasons. (Moc-Compiler does not work correctly and QObject has member variables which makes mutliple inheritance unsafe). You better work with composition instead of inheritance in case you want to provide the same behavious to several objects.
71,059,957
71,060,976
Clang and GCC has an inconsistent interpretation to the case where the parameter name appears as an unevaluated operand
#include <iostream> void fun(int a = sizeof(a)){ std::cout<< a<<std::endl; } int main(){ fun(); } Consider this case. Clang accepts it while GCC rejects it. According to [dcl.fct.default] p9 A default argument is evaluated each time the function is called with no argument for the corresponding parameter. A parameter shall not appear as a potentially-evaluated expression in a default argument. [basic.def.odr] p2 An expression or conversion is potentially evaluated unless it is an unevaluated operand sizeof is not a potentially-evaluated expression and a can be found at this point. I wonder which one is correct for this case?
GCC is wrong. It assumes that a is not yet in scope in the default argument, although generally the point of declaration is immediately after the declarator before the initializer and none of the exceptions apply here. [basic.scope.pdecl]/1 An older bug report for this is here. Note however, that the bug report has equivalent code to yours, but claims it should be ill-formed. That is because it was written before CWG 2082 which allowed the use of a parameter in an unevaluated context in the default argument. Related question regarding this GCC bug here.