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
69,260,764
69,261,121
Vulkan CommandBuffer in use after vkDeviceWait Idle
During initialization of my program I want to use some single time command buffers for image layout transitions and acceleration structure building etc. However, I can't seem to free the command buffer once it's finished. VkCommandBuffer AppContext::singleTimeCommandBuffer() const { VkCommandBuffer ret; auto allocInfo = vks::initializers::commandBufferAllocateInfo(vkCommandPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1); vkCheck(vkAllocateCommandBuffers(vkDevice, &allocInfo, &ret)); auto beginInfo = vks::initializers::commandBufferBeginInfo(); beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; vkCheck(vkBeginCommandBuffer(ret, &beginInfo)); return ret; } void AppContext::endSingleTimeCommands(VkCommandBuffer cmdBuffer) const { vkCheck(vkEndCommandBuffer(cmdBuffer)); auto submitInfo = vks::initializers::submitInfo(&cmdBuffer); vkQueueSubmit(queues.graphics, 1, &submitInfo, VK_NULL_HANDLE); vkQueueWaitIdle(queues.graphics); // Overkill, I know vkDeviceWaitIdle(vkDevice); vkFreeCommandBuffers(vkDevice, vkCommandPool, 1, &cmdBuffer); } Which produces the following validation error: VUID-vkFreeCommandBuffers-pCommandBuffers-00047(ERROR / SPEC): msgNum: 448332540 - Validation Error: [ VUID-vkFreeCommandBuffers-pCommandBuffers-00047 ] Object 0: handle = 0x5586acaeff78, type = VK_OBJECT_TYPE_COMMAND_BUFFER; | MessageID = 0x1ab902fc | Attempt to free VkCommandBuffer 0x5586acaeff78[] which is in use. The Vulkan spec states: All elements of pCommandBuffers must not be in the pending state (https://vulkan.lunarg.com/doc/view/1.2.182.0/linux/1.2-extensions/vkspec.html#VUID-vkFreeCommandBuffers-pCommandBuffers-00047) Objects: 1 [0] 0x5586acaeff78, type: 6, name: NULL I don't see how this makes sense since the VkQueueWaitIdle as well as the vkDeviceWaitIdle should ensure the command buffer to not be in the pending state. Am I misunderstanding the Vulkan specs or might I have stumbled upon a bug in the video driver, or perhaps the validation layer?
You aren't checking the return values of vkQueueSubmit(), vkQueueWaitIdle() or vkDeviceWaitIdle(). Are any of them failing? That could cause this error.
69,261,527
69,261,589
C++: Does the following code lead to dangling reference?
I'm studying the rvalue reference concept in C++. I want to understand if the following code can create a dangling reference. std::string&& s = std::move("test text"); std::cout << s << std::endl; From my understanding, s should be a dangling reference because its assignment it binds to a return value of std::move. And the correct usage should be std::string&& s = "test text". But when I tried it on here http://cpp.sh/ the program actually runs and prints "test text". Does this mean s is actually not a dangling reference? I found a similar stack overflow question here: int main() { string&& danger = std::move(middle_name()); // dangling reference ! return 0; } which confirms that this will lead to dangling reference. Can anyone give some hints? Thanks!
No it does not. From my understanding, s should be a dangling reference because its assignment it binds to a return value of std::move You have looked at the value categories, but not at the types. The type of "test text" is char const[10]. This array reside in const global data. You then pass it to move, which will return an rvalue reference to the array. The return type of this move cast expression is char const(&&)[10], an xvalue to a character array. Then, this is assigned to a std::string&&. But this is not a string, but a character array. A prvalue of type std::string must then be constructed. It is done by calling the constructor std::string::string(char const*), since the reference to array will decay into a pointer when passing it around. Since the reference is bound to a materialized temporary which is a prvalue, lifetime extension of the reference apply. The std::move is completely irrelevant and does absolutely nothing in this case. So in the end your code is functionally equivalent to this: std::string&& s = std::string{"test text"}; std::cout << s << std::endl; The answer would be difference if you would have used a std::string literal: // `"test text"s` is a `std::string` prvalue std::string&& s = std::move("test text"s); std::cout << s << std::endl; In this case, you have a prvalue that you send to std::move, which return an xvalue of type std::string, so std::string&&. In this case, no temporary is materialized from the xvalue return by std::move, and the reference simply bind to the result of std::move. No extension is applied here. This code would be UB, like the example you posted.
69,261,655
69,567,372
Issue linking and compiling C++ lib (Pcapplusplus) in SwiftUI project
I'm trying to utilize the C++ lib Pcapplusplus in my SwiftUI application through the use of objective C bridge classes. I've compiled a standalone C++ executable that makes very basic use of the pcpp library, but I'm lost on how to link and compile it in xcode. Here's the two makefiles I use to run the standalone executable in the terminal. Apologies if this is super simple, I'm just not sure how these makefiles would translate to xcode configuration options. Replies are appreciated! all: g++ $(PCAPPP_BUILD_FLAGS) $(PCAPPP_INCLUDES) -c -o main.o main.cpp g++ $(PCAPPP_LIBS_DIR) -o Tutorial-HelloWorld main.o $(PCAPPP_LIBS) # Clean Target clean: rm main.o rm Tutorial-HelloWorld # All Target all: g++ $(PCAPPP_BUILD_FLAGS) $(PCAPPP_INCLUDES) -c -o main.o main.cpp g++ $(PCAPPP_LIBS_DIR) -o Tutorial-HelloWorld main.o $(PCAPPP_LIBS) # Clean Target clean: rm main.o rm Tutorial-HelloWorld ### COMMON ### # includes PCAPPP_INCLUDES := -I/opt/homebrew/Cellar/pcapplusplus/21.05/include/pcapplusplus # libs PCAPPP_LIBS := /opt/homebrew/opt/pcapplusplus/lib/libPcap++.a /opt/homebrew/opt/pcapplusplus/lib/libPacket++.a /opt/homebrew/opt/pcapplusplus/lib/libCommon++.a # post build PCAPPP_POST_BUILD := # build flags PCAPPP_BUILD_FLAGS := -fPIC ifdef PCAPPP_ENABLE_CPP_FEATURE_DETECTION PCAPPP_BUILD_FLAGS += -DPCAPPP_CPP_FEATURE_DETECTION -std=c++11 endif ifndef CXXFLAGS CXXFLAGS := -O2 -g -Wall endif PCAPPP_BUILD_FLAGS += $(CXXFLAGS) ### MAC OS X ### # includes PCAPPP_INCLUDES += -I$(MACOS_SDK_HOME)/usr/include/netinet # libs PCAPPP_LIBS += -lpcap -lpthread -framework SystemConfiguration -framework CoreFoundation
Here are the steps to build PcapPlusPlus in a SwiftUI project: Run PcapPlusPlus configuration script for arm64: ./configure-mac_os_x.sh --arm64 Build PcapPlusPlus: make libs Go to the build settings, and under "header search paths" add the PcapPlusPlus include dir Under "other linker flags" add: -L/usr/local/lib -lpcap, -lpthread $(inherited) Under the build phases tab of the proj settings, in "Link Binary With libraries" add the SystemConfig framework, corefoundation, then libCommon++.a, libPacket++.a and libPcap++.a @publicstaticmain please let me know if anything is missing or inaccurate.
69,261,657
69,305,956
Querying a large dataset in-browser using webassembly
For argument's sake, let's say that a browser allows 4GB of memory in WebAssembly applications. Ignoring compression and other data-storage considerations, if a user had a 3GB local csv file, we could query that data entirely in-memory using webassembly (or javascript, of course). For example, if the user's data was of the following format: ID Country Amount 1 US 12 2 GB 11 3 DE 7 Then in a few lines of code we could do a basic algorithm to filter to ID=2, i.e., the SQL equivalent of SELECT * FROM table WHERE id=2. Now, my question is whether it's possible in any browser (and possibly with experimental flags and/or certain user preferences selected) such that a query could be done on a file that would not fit in memory, even if properly compressed. For example, in this blog post, a ~500GB file is loaded and then queried. I know that the 500GB of data is not loaded entirely in memory, and there's probably a column-oriented data structure so that only certain columns need to be read, but either way the OS has access to the file system and so files much larger than available memory can be used. Is this possible to do in any way within a webassembly browser application? If so, what would be an outline of how it could be done? I know this question might require some research, so when it's available for a bounty I can add a 500-point bounty to it to encourage answers. (Note that the underlying language being used is C++-compiled-to-wasm, but I don't think that should matter for this question.) I suppose one possibility might be along the lines of something like: https://rreverser.com/webassembly-shell-with-a-real-filesystem-access-in-a-browser/.
Javascript File API By studying the File API it turns out that when reading a file the browser will always handle you a Blob.This gives the impression that all the file is fetched by the browser to the RAM. The Blob has also a .stream() function that returns a ReadableStream to stream the very same Blob. It turns out (at least in Chrome) that the handled Blob is virtual and the underlying file is not loaded until requested. Nor file object slicing nor an instantiating a reader loads the entire file: file.slice(file.size - 100) (await reader.read()).value.slice(0, 100) Here is a test Sandbox and the sourcecode The example lets you select a file ad will display the last 100 characters (using .slice()) and the first 100 by using the ReadableStream (note that the stream function does not have seek functionality) I've tested this up to 10GB (the largest .csv I have laying around) and no RAM gets consumed by the browser This answers the first part of the question. With the capability to stream (or perform chunked access) a file without consuming RAM you can consume an arbitrarily large file and search for your content (binary search or a table scan). Webassembly In Rust using stdweb there is no .read() function (hence the content can not be streamed). But File does have .slice() function to slice the underlying blob (same as in javascript). This is a minimal working example: #[macro_use] extern crate stdweb; use stdweb::js_export; use std::convert::From; use stdweb::web::IBlob; use stdweb::web::File; use stdweb::web::FileReader; use stdweb::web::FileReaderResult; #[js_export] fn read_file(file: File) { let blob = file.slice(..2048); let len = stdweb::Number::from(blob.len() as f64); js! { var _len = @{len}; console.log("length=" + _len); var _blob = @{blob}; console.log(_blob); } } fn main() { } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>WASM</title> </head> <body> <input type="file" id="field" /> <script src="the_compiled_wasm_binding.js"></script> <script> async function onChange(e) { const files = e.target.files; if (files.length === 0) return; const file = files[0]; // Slice Rust.the_compiled_wasm_binding.then(module => { module.read_file(file); }) } document.getElementById("field").onchange = onChange; </script> </body> </html> The .slice() function is behaving the same as in javascript (the entire file is NOT loaded in RAM) hence you can load chunks of the file in WASM and perform a search. Please note that stdweb implementation of slice() uses slice_blob() which internally performs: js! ( return @{reference}.slice(@{start}, @{end}, @{content_type}); ).try_into().unwrap() As you can see it uses the javascript under the hood, so no optimization here. Conclusions IMHO the file reading implementation is more effective in javascript due to: stdweb::File API using raw javascript under the hood (hence not being faster) stdweb::File having less functionalities than the javascript counterpart (lack of streaming and few other functions). Then indeed the searching algorithm could/should be implemented in WASM. The algorithm can be handled directly a chunk (Blob) to be processed.
69,261,740
69,272,703
Serialize data to std::vector<uint8_t> - Protobuf C++
I'm stuck in a simple but hurting task: data parsing in C++. I need to serialize the data content from a Protobuf object to std::vector<uint8_t>. I've seen several examples to serialize the data to *void or char[] buffers using the SerializeToArray method, but not for what I need. I'd like to have a hand with this, thanks for your support. Note: I need std::vector<uint8_t>, not std::vector<uint8_t>& nor others.
The straight-forward solution is to presize the std::vector<uint8_t> to the correct size: size_t nbytes = std::vector<uint8_t> v(proto_object.ByteSizeLong()); /* The test is necessary becaue v.data could be NULL if nbytes is 0 */ if (nbytes) proto_object.SerializeToArray(v.data(), nbytes); The only problem here is that the contents of v are set to 0 by the constructor just before being overwritten by SerializeToArray. That's not a bug; the code will work fine. But it's an inefficiency. Being able to create vectors of uninitialised values is a long-standing discussion point. There are ways to do it, but the simple ones require using a type subtly different from std::vector<uint8_t>: one possibility is to use a vector with a custom allocator; another is to use a non-initialising data type based on uint8_t. Both of those are annoying because you can't change the allocator or value type of a vector without copying it, which defeats the purpose. So the easiest thing is to just accept the inefficiency, which is probably not so serious because the cost of sending the serialised data to wherever it is going is likely to dwarf the unnecessary initiliasation. In any event, clearing memory is certainly cheaper than copying from a temporary buffer, and it doesn't require creating the temporary buffer.
69,261,794
69,261,857
Output has one extra line c++
I am typing a program in c++ where it takes a number and does the following. If the number is a multiple of 3 but not 5, the output is Fizz. If the number is a multiple of 5 but not 3, the output is Buzz. If the number is a multiple of both 5 and 3, the output is FizzBuzz. If the number is neither a multiple of 3 or 5, it just prints out the a number. Whenever I compile the code with 15 as the test input, instead of getting the expected output: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz I instead get this FizzBuzz 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz My code is as follows: #include <bits/stdc++.h> #include <iostream> using namespace std; string ltrim(const string &); string rtrim(const string &); void fizzBuzz(int n) { for(int i = 0; i <= n; i++) { if(i % 3 == 0 && i % 5 != 0) { cout << "Fizz" << endl; } if (i % 3 != 0 && i % 5 == 0) { cout << "Buzz" << endl; } if (i % 3 != 0 && i % 5 != 0) { cout << i << endl; } if (i % 3 == 0 && i % 5 == 0) { cout << "FizzBuzz" << endl; } } } int main() { string n_temp; getline(cin, n_temp); int n = stoi(ltrim(rtrim(n_temp))); fizzBuzz(n); return 0; } string ltrim(const string &str) { string s(str); s.erase( s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace))) ); return s; } string rtrim(const string &str) { string s(str); s.erase( find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end() ); return s; } Would like to know what I'm doing wrong that's making the extra line in the output show up, any advice will be greatly appreciated!
For loop should start from 1. void fizzBuzz(int n) { for(int i = 1; i <= n; i++){ if(i % 3 == 0 && i % 5 != 0) cout << "Fizz" << endl; if (i % 3 != 0 && i % 5 == 0) cout << "Buzz" << endl; if (i % 3 != 0 && i % 5 != 0) cout << i << endl; if (i % 3 == 0 && i % 5 == 0) cout << "FizzBuzz" << endl; } }
69,261,797
69,307,696
List only files where compilation errors happened
I want a list of files where compilation errors happened without duplicates. Like so: /home/luizromario/project/src/foo.cpp /home/luizromario/project/src/bar.cpp I'm using Emacs's compilation mode to run gcc. Is there some way to achieve that either through gcc itself or through Emacs? Edit: I'm running make with the -k0 option, so the compilation process already keeps going as long as it can. My goal is to create a list of files I need to go through to make some small adjustments so that the compilation succeeds. I already know what the compilation error is (I marked one specific method as [[deprecated]]), so I don't need any diagnostics.
After looking for some ideas1, here's what I found works for me: more compilation-out | grep "error:" | sed 's/:.*//' | sort | uniq (There are several options to do this on Emacs2).
69,261,967
69,262,104
How can I remove the PERIOD before the number 1 in the output?
cin >> i >> e; while ( i <= e){ cout << "." << i; i = i + 1; } Example: INPUT: 1 5 OUTPUT: .1.2.3.4.5 EXPECTED OUTPUT: 1.2.3.4.5
I haven't tested it, but this should do what you're looking for. int main( ) { int input{ 0 }; int count{ 0 }; std::cin >> input >> count; std::cout << input; while( ++input <= count ) { std::cout << '.' << input; } std::cout << '\n'; }
69,262,027
69,262,320
Does CPath perform reference counting?
I was wondering whether ATL's CPath behaves like the underlying CString, in that an assignment will result in a ref count rather than a deep copy. I don't see anything in the docs about it, and I'm not sure how to test it. Here's some source that may be relevant, though I'm not sure: template< typename StringType > class CPathT { public: typedef typename StringType::XCHAR XCHAR; typedef typename StringType::PCXSTR PCXSTR; typedef typename StringType::PXSTR PXSTR; public: CPathT() throw() { } CPathT(_In_ const CPathT< StringType >& path) : m_strPath( path.m_strPath ) { } CPathT(_In_z_ PCXSTR pszPath) : m_strPath( pszPath ) { } operator const StringType& () const throw() { return m_strPath; } operator StringType& () throw() { return m_strPath; } operator PCXSTR() const throw() { return m_strPath; } ... public: StringType m_strPath; }; typedef CPathT< CString > CPath; Thank you very much for any info.
As you showed in the code above, the CPath is just a wrapper for CString, so it encapsulates all its properties and behavior. Logically, it uses CString reference counting.
69,262,332
69,262,394
program to find The number of prime numbers in array using cpp
this is the problem enter link description here the problem in function prime but it think it is true , and i can not find solution i submit it in codeforces but it give me .Wrong answer on test 5 :- the input : 39 81 46 4 5 2 71 66 97 51 84 50 64 68 99 58 45 64 86 14 44 7 49 45 72 94 19 33 68 83 12 89 88 39 36 51 11 57 9 54 the wrong !! #include <iostream> #include <math.h> using namespace std; int maximum(int arr[], int n) { int max = INT_MIN; for (int i = 0; i < n; i++) { if (max < arr[i]) { max = arr[i]; } } return max; } int minimum(int arr[], int n) { int min = INT_MAX; for (int i = 0; i < n; i++) { if (min > arr[i]) { min = arr[i]; } } return min; } int prime(int arr[], int n) { int con = 0; bool flag = true; for (int i = 0; i < n; i++) { if (arr[i] == 2) { con++; } else if (arr[i] > 2) { for (int j = 2; j < n; j++) { if (arr[i] % j == 0) { flag = false; break; } else { flag = true; } } if (flag == true) con++; } } return con; } int palindrome(int arr[], int n) { int i = 0, con = 0; while (n--) { int temp; temp = arr[i]; int reverseNumber = 0, rightDigit; while (temp != 0) { rightDigit = temp % 10; reverseNumber = (reverseNumber * 10) + rightDigit; temp = temp / 10; } if (reverseNumber == arr[i]) { con++; } i++; } return con; } int divisors(int arr[], int n) { int max = 0; int con = 0; int x = arr[0]; for (int i = 0; i < n; i++) { int temp = arr[i]; for (int j = 1; j <= arr[i]; j++) { if (arr[i] % j == 0) { con++; } } if (max < con) { max = con; x = arr[i]; } else if (max == con) { if (x < arr[i]) { x = arr[i]; } } con = 0; } return x; } int main() { int n; cin >> n; int arr[1001]; for (int i = 0; i < n; i++) cin >> arr[i]; cout << "The maximum number : " << maximum(arr, n) << endl; cout << "The minimum number : " << minimum(arr, n) << endl; cout << "The number of prime numbers : " << prime(arr, n) << endl; cout << "The number of palindrome numbers : " << palindrome(arr, n) << endl; cout << "The number that has the maximum number of divisors : " << divisors(arr, n) << endl; divisors(arr, n); return 0; }
This for loop for (int j = 2; j < n; j++) is incorrect. It seems you mean for (int j = 2; j < arr[i]; j++) Also you should declare the variable flag within the else statement where it is used. For example for (int i = 0; i < n; i++) { if (arr[i] == 2) { con++; } else if (arr[i] > 2) { bool flag = false; //...
69,262,474
69,262,566
Intersection of two `unordered_set`s in C++ "not working" when in a class method but works with `set`?
What I have here is two "maps", xs and ys, which I use to store "points" in a grid. I also have an array std::pair<int,int> arr, such that xs[x] returns all the indices in arr with x-coordinate x, and ys[y] returns all indices with y-coordinate y. Let us have the following: std::unordered_map<int, std::unordered_set<size_t>> xs { {3, {2, 0}}, {11, {1}} }; std::unordered_map<int, std::unordered_set<size_t>> ys { {2, {2 ,1}}, {10, {0}} }; std::unordered_set<size_t> intersection; std::set_intersection(xs[3].begin(), xs[3].end(), ys[2].begin(), ys[2].end(), std::inserter(intersection, intersection.begin())); std::cout << intersection.size() << std::endl; // should return 1 intersection.clear(); std::set_intersection(xs[11].begin(), xs[11].end(), ys[2].begin(), ys[2].end(), std::inserter(intersection, intersection.begin())); std::cout << intersection.size() << std::endl; // should return 1 They do return 1 and 1. No surprises there. Let us now isolate the intersection counter in a function: size_t count_intersection(const std::pair<int,int>& pt, const std::unordered_map<int, std::unordered_set<size_t>>& xs, const std::unordered_map<int, std::unordered_set<size_t>>& ys) { const int x = pt.first, y = pt.second; // Omitted some error checking std::unordered_set<size_t> intersection; std::set_intersection(xs.at(x).begin(), xs.at(x).end(), ys.at(y).begin(), ys.at(y).end(), std::inserter(intersection, intersection.begin())); return intersection.size(); } std::cout << count_intersection({3, 2}, xs, ys) << std::endl; std::cout << count_intersection({11, 2}, xs, ys) << std::endl; So far, so good. Now, let's isolate all of this in a class: class Counter { std::vector<std::pair<int,int>> _pts; std::unordered_map<int, std::unordered_set<size_t>> _xs; std::unordered_map<int, std::unordered_set<size_t>> _ys; public: void add(const std::pair<int,int>& pt) { const int x = pt.first, y = pt.second; const size_t ind = _pts.size(); _pts.push_back(pt); _xs[x].insert(ind); _ys[y].insert(ind); } size_t count(const std::pair<int,int>& pt) { std::unordered_set<size_t> intersection; const int x = pt.first, y = pt.second; std::set_intersection(_xs[x].begin(), _xs[x].end(), _ys[y].begin(), _ys[y].end(), std::inserter(intersection, intersection.begin())); return intersection.size(); } }; int main() { Counter c; c.add({3,10}); // ind == 0 c.add({11,2}); // ind == 1 c.add({3,2}); // ind == 2 // By this point, // _xs == {3: {0, 2}, 11: {1}} // _ys == {10: {0}, 2: {1,2}} std::cout << c.count({3,2}) << std::endl; // Should return 1 std::cout << c.count({11,2}) << std::endl; // Should return 1 } Instead, what I got is 1 0 However, when I replaced std::unordered_set with std::set, the result becomes expected. What's up with std::unordered_set? By the way, my command in compiling is g++ -Wall -Wextra -Werror -O3 -std=c++17 -pedantic -fsanitize=address -o main.out main.cpp && ./main.out and my g++ --version is g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0.
std::set_intersection requires ordered elements. unordered_map and _set does not provide ordered elements.
69,262,813
69,262,917
Why don't visual studio code throw error when handle with null value?
I have the code below: class A { public: int *b; }; int main() { A *a = new A(); a->b = new int(1); cout << *a->b; cout << "done"; return 0; } I run it and get the expected output 1done but when I comment the a->b = new int(1); It just print nothing. How to make it throw something for me to identify where the error is in my code. My VS Code version is 1.60.1. Thanks in advance.
It is not the fault of Visual Studio Code. Your code will have undefined behavior (it might throw a segmentation fault, or it might not) if you comment out a->b = new int(3) line. See I get a segmentation fault instead of an exception about how you cannot throw an exception (which VS Code can show) when a segmentation fault is happening. You could go to the terminal of VS Code and then run: g++ yourfile.cpp ./a.out That showed me a segmentation fault like so: ./a.out Segmentation fault (core dumped)
69,263,122
69,263,294
How to prefer calling const member function and fallback to non-const version?
Consider a class Bar in two versions of a library: /// v1 class Bar { void get_drink() { std::cout << "non-const get_drink() called" << std::endl; } }; /// v2 class Bar { void get_drink() { std::cout << "non-const get_drink() called" << std::endl; } void get_drink() const { std::cout << "const get_drink() called" << std::endl; } }; On the client side code, we own a Bar object and would like to get_drink. I want to be able to prefer calling the const version of get_drink() if it's available (when using v2 library) and fallback to the non-const version (when using v1 library). That is: Bar bar; bar.get_drink(); // this does not call the const version of v2 static_cast<const Bar&>(bar).get_drink(); // this does not compile against v1 library Unfortunately, the library is not versioned and there's no other way to distinguish between the two versions. I reckon some template magic has to be used. So the question is how?
This seems to work: #include <type_traits> #include <iostream> template<typename T, typename=void> struct find_a_drink { void operator()(T &t) const { t.get_drink(); } }; template<typename T> struct find_a_drink<T, std::void_t<decltype( std::declval<const T &>() .get_drink())> > { void operator()(T &t) const { static_cast<const T &>(t).get_drink(); } }; template<typename T> void drink_from(T &&t) { find_a_drink<std::remove_reference_t<T>>{}(t); } /// v1 class Bar1 { public: void get_drink() { std::cout << "non-const get_drink() called (Bar1)" << std::endl; } }; class Bar2 { public: void get_drink() { std::cout << "non-const get_drink() called (Bar2)" << std::endl; } void get_drink() const { std::cout << "const get_drink() called (Bar2)" << std::endl; } }; int main() { Bar1 b1; Bar2 b2; drink_from(b1); drink_from(b2); return 0; } Result: non-const get_drink() called (Bar1) const get_drink() called (Bar2)
69,263,774
69,264,137
Why does the first and last value in my code's output doubles?
int i = 0; int e = 0; cin >> i >> e; cout << i; while( ++i <= e ) { cout << "." << i; } while ( --i >= e ){ cout << '.' << i; } hello everyone, can I ask for some help regarding this. If I run my code and if I input for example: INPUT: 1 5 MY CODE OUTPUTS: 1.2.3.4.5.5 INPUT: 5 1 MY CODE OUTPUTS: 5.5.4.3.2.1 The output should be; INPUT: 1 5 OUTPUT SHOULD BE: 1.2.3.4.5 INPUT: 5 1 OUTPUT SHOULD BE: 5.4.3.2.1
Let's discuss the first input: 1 5. When you're reaching 5 by pre-incrementing the i, it prints the value of i which is 5. then it comes back to while loop again first increments the value of i (which gets to 6) then it checks the condition where 6<=e is false so the loop breaks. Then it goes to the second loop. it decreases the value first and make the value of i=5 and checks if i>=e which is true so it prints the i. after the first iteration value of i becomes less then e so it doesn't print anything after that.
69,263,921
69,263,958
Undefined reference to constructor problem
See the below-given code #include <iostream> using namespace std; class Number { int a; public: Number(); Number(int num_1) { a = num_1; } void print_number(void) { cout << "Value of a is " << a << endl; } }; int main() { Number num_1(33), num_3; Number num_2(num_1); num_2.print_number(); return 0; } In the above code, I am having 2 constructors in the same class but when compiling it,gives me the error ccnd0o9C.o:xx.cpp:(.text+0x30): undefined reference to `Number::Number()' collect2.exe: error: ld returned 1 exit status Can anyone solve this problem? and I still need the 2 constructors but without replacing num_3 with num_3() the main function.
In your class, you have declared the default constructor, but you have not defined it. You can default it (since C++11) and you will be good to go: Number() = default; Otherwise: Number() {} As from @TedLyngmo liked post, both will behave the same, but the class will get different meaning as per the standard, though. More reads here: The new syntax "= default" in C++11 @Jarod42's Comment as side notes: The default constructor make sense when it provide a default value to the member a. Otherwise it will be uninitialized (indeterminate value) and reading them will cause to UB.
69,264,430
69,264,833
Contradictory definitions about the Order of Constant Initialization and Zero Initialization in C++
I have been trying to understand how static variables are initialized. And noted a contradiction about the order of constant initialization and zero initialization at cppref and enseignement. At cppref it says: Constant initialization is performed instead of zero initialization of the static and thread-local (since C++11) objects and before all other initialization. Whereas at enseignement it says: Constant initialization is performed after zero initialization of the static and thread-local objects and before all other initialization. So as you can see cppref uses "instead" while the second site uses "after". Which of the two is correct? That is, does zero initialization always happen first and then if possible constant initialization as implied by the second site or the other way round. The example given there is as follows: #include <iostream> #include <array> struct S { static const int c; }; const int d = 10 * S::c; // not a constant expression: S::c has no preceding // initializer, this initialization happens after const const int S::c = 5; // constant initialization, guaranteed to happen first int main() { std::cout << "d = " << d << '\n'; std::array<int, S::c> a1; // OK: S::c is a constant expression // std::array<int, d> a2; // error: d is not a constant expression } This is my understanding of the initialization process so far: Static initialization happens first. This includes Constant initialization if possible Zero initialization only if constant initialization was not done Dynamic Initialization Now according to the above(my understanding) this is how the code above works: Step 1. When the control flow reaches the definition of const int d it sees that the initializer has a variable(namely S::c) that has not been already initialized. So the statement const int d = 10 * S::c; is a dynamic time(runtime) initialization. This means it can only happen after static initialization. And ofcourse d is not a constant expression. Step 2. The control flow reaches the definition of variable const int S::c; . In this case however the initializer is a constant expression and so constant initialization can happen. And there is no need for zero initialization. Step 3. But note that we(the compiler) still haven't initialized the variable d because it left its initialization because it has to be done dynamically. So now this will take place and d will get value 50. But note d still isn't a constant expression and hence we cannot use it where a constant expression is required. Is my analysis/understanding of the concept correct and the code behaves as described? Note: The order of constant initialization and zero initialization is also different at cppref-init and enseignement-init.
When in doubt, turn to the standard. As this question is tagged with C++11, we'll refer to N3337. [basic.start.init]/2: Variables with static storage duration ([basic.stc.static]) or thread storage duration ([basic.stc.thread]) shall be zero-initialized ([dcl.init]) before any other initialization takes place. Constant initialization is performed: [...] Together, zero-initialization and constant initialization are called static initialization; all other initialization is dynamic initialization. Static initialization shall be performed before any dynamic initialization takes place. Thus, with regard to the C++11 Standard, enseignement's description is accurate. Constant initialization is performed after zero initialization of the static and thread-local objects and before all other initialization. However, this was flagged as a defect as per CWG 2026: CWG agreed that constant initialization should be considered as happening instead of zero initialization in these cases, making the declarations ill-formed. And as of C++17 (N4659) this was changed, and henceforth governed by [basic.start.static]/2: [...] Constant initialization is performed if a variable or temporary object with static or thread storage duration is initialized by a constant initializer for the entity. If constant initialization is not performed, a variable with static storage duration or thread storage duration is zero-initialized. Together, zero-initialization and constant initialization are called static initialization; all other initialization is dynamic initialization. But as this was not just new standard feature update, but a defect, it backports to older standard, and in the end cppreference's description is accurate also for C++11 (in fact all the way back to C++98), whereas enseignement's has not taken into account neither modern C++ standard nor the DR CWG 2026. I have never visited enseignement's page myself, but after a quick glance at their reference page, it looks like a really old version of cppreference itself, either entirely unattributed to cppreference, or cppreference actually started as a collab with the enseignement authors. Short of the standard itself I consider cppreference to be a de facto reference, and given the old copy-pasta of enseignement I would recommend never to turn to those for pages reference again. And indeed, we may visit the actual up-to-date cppreference page on constant initialization, scroll to the very bottom and read: Defect reports The following behavior-changing defect reports were applied retroactively to previously published C++ standards. [...] CWG 2026 Applied to: C++98 Behavior as published: zero-init was specified to always occur first, even before constant-init Correct behavior: no zero-init if constant init applies
69,265,190
69,265,326
C++ Create an object with array simultaneously with the constructor
So, I've been exploring on how to create a dynamical array with a custom template class that I made. #include <iostream> #include <vector> //HOW TO SET CLASS INTO DYNAMICAL ARRAY WITH VECTOR //CREATE A CLASS class User{ std::string name; public: User(){ } User(std::string name){ this->name = name; } void set_name(std::string name){ this->name = name; } std::string get_name(){ return name; } }; int main(){ //SET A NORMAL ARRAY THAT CAN CONTAIN AN OBJECT User user[1]; //DO WHATEVER WITH THE USER[0] TO SET EVERYTHING THAT LATER WILL BE PUT IN VECTOR user[0].set_name("Meilianto"); std::cout << "user[0]: " << user[0].get_name() << std::endl; //CREATE A DYNAMICAL ARRAY WHICH IS VECTOR std::vector<User> vuser; //PUSHBACK TO THE VECTOR AS "FIRST ELEMENT" BY PUTTING "USER[0]" AS AN ARGUMENT vuser.push_back(user[0]); std::cout << "vuser[0]: " << vuser[0].get_name() << std::endl; //YOU CAN "MODIFIED" THE "USER[0]" AND ADD AGAIN AS THE "SECOND ELEMENT" OF VECTOR user[0].set_name("Meilianto1"); vuser.push_back(user[0]); std::cout << "vuser[1]: " << vuser[1].get_name() << std::endl; //YOU CAN EVEN "MODIFIED" THE "FIRST ELEMENT" BY CALLING THE "METHOD" OF IT vuser[0].set_name("Hantu"); std::cout << "vuser[0]: " << vuser[0].get_name() << std::endl; //THE QUESTION HERE, CAN I DECLARE ARRAY TOGETHER WITH THE CONSTRUCTOR? User user1[1]("Bebek"); //AND AFTER THAT I CAN ADD THAT OBJECT STRAIGHT AWAY TO VECTOR WITHOUT ASSIGNING ALL THE //MEMBERS ONE BY ONE return 0; } If you have read my comments in my code, what I am trying to do is maybe it will be faster if I just construct right away when I create the object instead of assigning all the members one by one that will cost more code. I imagine if in the future there will be an object with a lot of members and need to assign it one by one. It won't be efficient. EDIT: I edit the User user[0] into User user[1], Thanks
Yes, you can! User users[]{ User{ "one" }, User{ "two" } }; // Construct vector from iterator-pair: std::vector<User> users_vector{ std::cbegin(users), std::cend(users) };
69,265,233
69,266,219
Order a vector according to weights stored in another vector using STL algorithms
I have a vector containing instances of a class, let's say std::vector<A> a. I want to order this vector according to weights stored in a std::vector<float> weights, with weights[i] being the weight associated to a[i]; after sorting, a elements must be ordered by increasing weight. I know how to do this explicitly, but I'd like to use C++14 STL algorithms in order to benefit from an eventual optimal implementation. Up to now, I haven't been able to figure how to use weights in a lambda comparison expression for std::sort, nor how to keep a and weights aligned every time two elements of a are swapped by std::sort, so I'm beginning to think that it might be not possible. Thanks in advance for any help.
Sort an index vector, then rearrange according to the result: void my_sort(std::vector<A>& a, std::vector<float>& weights) { std::vector<int> idx(a.size()); std::iota(idx.begin(), idx.end(), 0); sort(idx.begin(), idx.end(), [&](int a, int b) { return weights[a] < weights[b]; }); auto reorder = [&](const auto& o) { decltype(o) n(o.size()); std::transform(idx.begin(), idx.end(), n.begin(), [&](int i) { return o[i]; }); return n; }; a = reorder(a); weights = reorder(weights); }
69,265,275
69,265,549
How could I check If a variable is a certain number multiple times while changing what to do if It matches?
I want to check what the variable "num" is from 0 - 15 How can I check if it is one of those numbers and what number it is so far I've got. #include <iostream> using namespace std; int num = 0; int main() { cout << "Number to check:"; cin >> num; { if num = 0; cout << "0000"; { if num = 2; cout << "0010"; { if num = 1; cout << "0001"; { if num = 3; cout << "0011"; { if num = 4; cout << "0100"; { if num = 7; cout << "0111"; { if num = 5; cout << "0101"; { if num = 6; cout << "0110"; { if num = 8; cout << "1000"; { if num = 9; cout << "1001"; { if num = 10; cout << "1010"; { if num = 11; cout << "1011"; { if num = 12; cout << "1100"; { if num = 13; cout << "1101"; { if num = 14; cout << "1110"; { if num = 15; cout << "1111"; } } } } } } } } } } } } } } } } } return 0; How may I be able to do this If I can't, how can I convert a number to a 4-bit Binary byte? And if possible how can I make sure the number inputted is in the range of 0 - 15 and that there isn't letters in the inputted string
The program below does what you want. #include<iostream> #include <bitset> int main() { int num = 0; std::cout << "Number to check: "; std::cin >> num; while (std::cin.fail() || num > 15 || num < 0) { std::cout << "Error! Invalid Input \n"; std::cin.clear(); std::cin.ignore(256, '\n'); std::cout << "Number to check: "; std::cin >> num; } std::bitset<4> value; value = { static_cast<unsigned long>(num) }; std::cout << value.to_string() << "\n"; return 0; }
69,265,335
69,269,907
Disable mouse / cursor detection
I'm making a simple Pong game. When I ran the program, all the moves are perfect (the moving are not too fast nor too slow). However, when I move my cursor around, the movement are faster which making the game much harder. while (enable_loop) { Ticks = SDL_GetTicks(); while (SDL_PollEvent(&any_event)) { if (any_event.type == SDL_QUIT) { enable_loop = false; } // Process keyboard event keyPressed = SDL_GetKeyboardState(NULL); if (keyPressed[SDL_SCANCODE_ESCAPE]) { enable_loop = false; } if (keyPressed[SDL_SCANCODE_UP] ) { player2.Update(25); } if (keyPressed[SDL_SCANCODE_DOWN]) { player2.Update(-25); } if (keyPressed[SDL_SCANCODE_W]) { player1.Update(20); } if (keyPressed[SDL_SCANCODE_S]) { player1.Update(-20); } } Grouping.update(surface, background); SDL_UpdateWindowSurface(window); limitFPS(Ticks); } } Note : I've tried SDL_Delay(5) but the movement are too junky and jumping around, not usable :/ This game does not require mouse and I just may plug out my mouse, but I'm asking this for my experience and knowledge purposes. I've used SDL_ShowCursor(SDL_DISABLE), SDL_CaptureMouse(SDL_FALSE) and limit my FPS to 60. The effect is lessen but still noticeable. How do I disable mouse detection or any code that will stop the effect?
Move the keyPressed checks outside the SDL_PollEvent() loop: while (enable_loop) { Ticks = SDL_GetTicks(); while (SDL_PollEvent(&any_event)) { if (any_event.type == SDL_QUIT) { enable_loop = false; } } // Process keyboard event keyPressed = SDL_GetKeyboardState(NULL); if (keyPressed[SDL_SCANCODE_ESCAPE]) { enable_loop = false; } if (keyPressed[SDL_SCANCODE_UP] ) { player2.Update(25); } if (keyPressed[SDL_SCANCODE_DOWN]) { player2.Update(-25); } if (keyPressed[SDL_SCANCODE_W]) { player1.Update(20); } if (keyPressed[SDL_SCANCODE_S]) { player1.Update(-20); } Grouping.update(surface, background); SDL_UpdateWindowSurface(window); limitFPS(Ticks); } That way you're only processing keyboard input once per frame instead of once per event.
69,265,574
69,268,067
How to convert a class declaration to a string using macros?
I need to convert my class declaration into a string and I also need the class defined. in the code below i have given an example which results in Identifier Person is undefined or Incomplete type not allowed. but if this is possible with custom macros, some code would be much appreciated. struct Person; std::string Person::meta = STRINGIFY( struct Person{ static std::string meta; std::string name = "Test"; int age = 5; std::string address = "No:35179 Address"; }; ); Person person;
You can't do that; you can't initialize Person::meta before the type is defined, and you can't define the type as part of the initializing expression. However, you can move the initialization into the macro: #define WITH_META(cls, body) struct cls body; std::string cls::meta = "struct " #cls #body; WITH_META(Person, { static std::string meta; std::string name = "Test"; int age = 5; std::string address = "No:35179 Address"; }); int main() { std::cout << Person::meta << std::endl; } Output: struct Person{static std::string meta; std::string name = "Test"; int age = 5; std::string address = "No:35179 Address";}
69,265,707
69,265,896
Template type argument `T` where `T*` expands to `nullptr_t`
What I'm looking for is basically this: template <typename T> struct a { using pointer_type = T*; }; What I want is such X so that a<X>::pointer_type evaluates to nullptr_t. Is this possible? Edit: This is what I actually need (the pointer_type is hidden in the signatures of the ENCODER and DECODER template arguments as MSG *) template <int MSGNUM, typename MSG, int(&ENCODER)(const MsgHeader* pHeader, const MSG* pMessage, unsigned char* destBuf, int destBufSize), int(&DECODER)(const MsgHeader* pHeader, const unsigned char* msgBody, int msgBodyLen, MSG* decodedMsg)> struct msgid { using msg_type = MSG; static constexpr int msgnum = MSGNUM; static constexpr auto encoder = ENCODER; static constexpr auto decoder = DECODER; }; using MSG1 = msgid<1,msg1struct,encodeMsg1,decodeMsg1>; using MSG2 = msgid<2,msg2struct,encodeMsg2,decodeMsg2>; using HDRONLY= msgid<-1,X,encodeHdr,decodeHdr>; HDRONLY would have to accept a nullptr where the decoded msg structure is used.
You could also use std::conditional from the <type_traits> header: #include <type_traits> // ... template <typename T> struct a { using pointer_type = typename std::conditional<std::is_same<T, std::nullptr_t>::value, std::nullptr_t, T* >::type; };
69,265,917
69,274,688
Same test cases showing different answer
I have doubt regarding this min-max problem: My code : void miniMaxSum(vector<int> arr) { sort(arr.begin(), arr.end()); int sum=0; for(int i=0; i<5; i++) sum += arr[i]; cout<<sum-arr[4]<<" "<<sum-arr[0]<<endl; } In other words: void miniMaxSum(vector<int> arr) { sort(arr.begin(), arr.end()); int min=0; for(int i=0; i<4; i++) min += arr[i]; cout<<min<<" "; int max=0; for(int i=1; i<5; i++) max += arr[i]; cout<<max<<endl; } These code running successfuly for sample data 1 and 2, but when I submit my code, these test cases also showing as wrong output. Can you please hint where this code wrong !
int is a 32bit integer, the problem mentions that it's possible for the answer to be greater than this. You will want to use a 64 bit integer (int64_t) for your vector and your max variables. You should also switch to passing by reference instead of by value void miniMaxSum(vector<int> arr) { will copy the entire array, who void miniMaxSum(const vector<int>& arr) { will pass in a read only reference to the array without copying it.
69,266,652
69,266,854
How i can print a number triangle in c++
#include<iostream> using namespace std; int main(){ int i=1; do{ if(i < 10){ cout<<"00"<<i<<" "; } else if (i < 100){ cout<<"0"<<i<<" "; } else { cout<<i<<" "; } if(i%10 ==0){ cout<<endl; } i++; }while (i <= 100); return 0; } this is output 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 063 064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079 080 081 082 083 084 085 086 087 088 089 090 091 092 093 094 095 096 097 098 099 100 this is output that I want: 001 011 012 021 022 023 031 032 033 034 041 042 043 044 045 051 052 053 054 055 056 061 062 063 064 065 066 067 071 072 073 074 075 076 077 078 081 082 083 084 085 086 087 088 089 091 092 093 094 095 096 097 098 099 100
You already know how to print the individual numbers, only the larger pattern is wrong. As the pattern is 2D, your code will be easier when that 2D aspect is also present in your code. What I mean: Instead of iterating i you can iterate row and column: for (int row=0; row<10; ++row) { for (int col=0; col<10; ++col) { if ( ...... ) { print_number(row,col); } } std::cout << "\n"; } After each row a newline is printed and you just need to figure out the right condition for the if and implement a print_number function (you already have most of what is needed for that function). For bonus points you can read about break to improve the logic of the above loop. Alternatively adjust the bounds of the inner loop in such a way that you can remove the if.
69,266,840
69,267,107
How to loop through certain Ascii characters in c++
I only want to loop through certain Ascii characters and not all are directly next to each other . For example I only want to loop from char '1 to 7' and then from char '? to F'. I dont want to loop through '8 to >' . I have this for loop but this will include the char I don't want. for (char i = '1'; i < 'H'; i++) How should I modify it to only loop through what I want?
Each character has a fixed ASCII value associated with it. You can refer to any character with that particular ASCII value. You can just skip the characters you do not want with an 'if' condition. You will find all the ASCII values here. Referring to your example, if you want to skip the characters from '?' to 'F', the code might look something like this: #include <iostream> using namespace std; int main() { for (char i = '1'; i < 'H'; i++) { if(i>=63 && i<=70) // 63 is the ASCII value for '?' // 70 is the ASCII value for 'F' { // skipping the ASCII values we do not need continue; } cout << i << ""; } return 0; }
69,266,921
69,272,002
Building mediapipe fails with both GCC and Clang
I am trying to build Hello World example of Mediapipe in C++. These are my exports in .bash_profile: export PATH=$PATH:$(go env GOPATH)/bin export GLOG_logtostderr=1 export CC=/usr/bin/clang export CXX=/usr/bin/clang++ #export CC=/usr/bin/gcc #export CXX=/usr/bin/g++ export BAZEL_CXXOPTS="-std=gnu++17" then I run this, fallowing the instructions: bazelisk run --copt -DMESA_EGL_NO_X11_HEADERS --copt -DEGL_NO_X11 --sandbox_writable_path ~/.ccache --sandbox_debug --verbose_failures mediapipe/examples/desktop/hello_world:hello_world the effect being "no member named 'max' in the global namespace" error on this line: if (x->version == std::numeric_limits<uint32_t>::max()) { that's on Clang I've only used because GCC11 changed how it now doesn't include <limits> so with CC/CXX variables set to gcc/g++, it gives "'::max' has not been declared; did you mean std::max?" errors... did Clang made similar changes? I'm on Fedora, I don't have access to old GCC10.
mediapipe depends on an old version of abseil c++ that does not include a commit necessary to work on newer libstdc++ versions. So, com_google_absl in the mediapipe WORKSPACE needs an update.
69,267,565
69,268,056
How can we get NiceMock<> behavior to apply to a single method?
When a mocked method is called without an expectation set, gmock emits a warning: GMOCK WARNING: Uninteresting mock function call - returning default value. Function call: getAddress(@0x563e6bbf5530 16-byte object <F0-3A 32-6B 3E-56 00-00 30-A7 BF-6B 3E-56 00-00>) Returns: "" NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details. Such warnings can be suppressed by wrapping the mock with NiceMock<> before injecting it. Is it possible to get the same effect, but only for some of the methods on the mock? For example, consider this mock (written using an older version of gtest): class PocoMock : public Poco { public: PocoMock() // : Poco() { } MOCK_CONST_METHOD1(listen, void(Poco::Net::ServerSocket& rSocket)); MOCK_CONST_METHOD1(start, void(Poco::Net::TCPServer& rServer)); MOCK_CONST_METHOD1(stop, void(Poco::Net::TCPServer& rServer)); MOCK_CONST_METHOD1( getAddress, std::string(const Poco::Net::StreamSocket& rSocket)); } Is it possible to tell gmock to suppress warnings about unexpected calls to getAddress(), but not about listen(), start() and stop()?
You can explicitly said you can have any number of call to getAddress: EXPECT_CALL(mock, getAddress(testing::_)).Times(testing::AnyNumber()); Demo
69,267,575
69,267,847
C++ use class with conversion operator as index into array
#include <cinttypes> #include <type_traits> template<typename Id, typename Value> class sparse_set { static_assert(std::is_integral_v<Id>, ""); (1) static_assert(std::is_unsigned_v<Id>, ""); Value& operator[](Id id); void push_back(const Value& value); // class implementation left out }; class entity { public: explicit entity(std::uint32_t id) : _id(id) {} ~entity() = default; std::uint32_t id() const { return _id; } operator std::uint32_t() const { (2) return _id; } private: std::uint32_t _id; }; // class entity int main() { const auto e = entity{2}; auto set = sparse_set<entity, int>{}; set.push_back(0); set.push_back(1); set.push_back(2); set.push_back(3); auto i = set[e]; (3) return 0; } I am trying to use a class with a conversion operator to std::uint32_t (2) as an index into a container class (3). Accessing an element with an instance of that class works and i get the right element. But testing the class with a static_assert and std::is_unsigned_v and std::is_integral_v results in an assertion failure. I need assertions to make sure Id can be used as an index. When I static_assert with std::uint32_t everything works so I would expect the conversion operator to work aswell.
std::is_unsigned and std::is_integral only works for primitive types, it doesn't work for classes, even if they are implicitly convertible to a type they support. You can solve this by two ways: Create your own trait: #include <type_traits> // ... using uint16 = std::uint16_t; using uint32 = std::uint32_t; class entity { /* ... */ }; template <typename T> struct is_valid_index : std::is_unsigned<T> {}; template <> struct is_valid_index<entity> : std::true_type {}; template <typename T> constexpr auto is_valid_index_v = is_valid_index<T>::value; template<typename Id, typename Value> class sparse_set { static_assert(is_valid_index_v<Id>, ""); // ... }; // ... Remove std::is_unsigned completely and use std::is_convertible instead: #include <type_traits> // ... using uint16 = std::uint16_t; using uint32 = std::uint32_t; class entity { /* ... */ }; template<typename Id, typename Value> class sparse_set { static_assert(std::is_convertible_v<Id, uint32>, ""); // ... }; // ...
69,268,428
69,268,511
How to pass a second vector into the function that is the third argument of sort() function from C++ STL without using global variables?
I want to pass the below function as as the third argument in sort() function from C++ STL. bool fn(int a, int b, vector<int> v1) { if (v1[a]< v1[b]) return true; else return false; } I want sort a vector according to the values in another vector. sort(v2.begin(), v2.end(),fn); How do I pass the first vector v1 to the function fn so that the function fn can use it to sort the second vector v2 without the use of global variables?
First, your comparator has the wrong signature. std::sort expects a callable that can be called with 2 elements. You can use a lambda expression that captures the vector: sort(v2.begin(), v2.end(),[&v1](const auto& a,const auto& b){ return v1[a]< v1[b]; }); I tried to write this function fn inside main in hopes that it would be in scope but that didn't work. You cannot define functions within functions. You can define a type with operator() inside a function, and thats basically what a lambda expression does. The following hand written functor will achieve the same: struct my_comparator { std::vector<int>& v1; bool operator(size_t a,size_t b) { return v1[a] < v1[b]; } }; std::sort(v2.begin(),v2.end(),my_comparator{v2});
69,268,516
69,503,643
Is the const overload of begin/end of the range adapters underconstrained?
In C++20, some ranges have both const and non-const begin()/end(), while others only have non-const begin()/end(). In order to enable the range adapters that wraps the former to be able to use begin()/end() when it is const qualified, some range adapters such as elements_view, reverse_view and common_view all provide constrained const-qualified begin()/end() functions, for example: template<view V> requires (!common_­range<V> && copyable<iterator_t<V>>) class common_view : public view_interface<common_view<V>> { public: constexpr auto begin(); constexpr auto end(); constexpr auto begin() const requires range<const V>; constexpr auto end() const requires range<const V>; }; template<input_­range V, size_t N> requires view<V> && has-tuple-element<range_value_t<V>, N> class elements_view : public view_interface<elements_view<V, N>> { public: constexpr auto begin(); constexpr auto end(); constexpr auto begin() const requires range<const V>; constexpr auto end() const requires range<const V>; }; The begin() const/end() const will only be instantiated when const V satisfies the range, which seems reasonable. But only one simple constraint seems to be insufficient. Take common_view for example, it requires that V is not a common_range. But when V is not a common_range and const V is a common_range (I know that such a range is extremely weird, but in theory, it can exist, godbolt): #include <ranges> struct weird_range : std::ranges::view_base { int* begin(); const int* end(); std::common_iterator<int*, const int*> begin() const; std::common_iterator<int*, const int*> end() const; }; int main() { weird_range r; auto cr = r | std::views::common; static_assert(std::ranges::forward_range<decltype(cr)>); // ok cr.front(); // ill-formed } In the above example, const V still satisfied the range concept, and when we apply r to views::common, its front() function will be ill-formed. The reason is that view_interface::front() const will still be instantiated, and the common_iterator will be constructed inside the begin() const of common_view, this will cause a hard error to abort the compilation since const V itself is common_range. Similarly, we can also create a weird range based on the same concept to make the front() of views::reverse and views::keys fail (godbolt): #include <ranges> struct my_range : std::ranges::view_base { std::pair<int, int>* begin(); std::pair<int, int>* end(); std::common_iterator<int*, const int*> begin() const; std::common_iterator<int*, const int*> end() const; }; int main() { my_range r; auto r1 = r | std::views::reverse; static_assert(std::ranges::random_access_range<decltype(r1)>); // ok r1.front(); // ill-formed auto r2 = r | std::views::keys; static_assert(std::ranges::random_access_range<decltype(r2)>); // ok r2.front(); // ill-formed } So, is the const overload of begin()/end() of the range adapters underconstrained, or is the definition of weird_range itself ill-formed? Can this be considered a standard defect? This question is mainly inspired by the LWG 3592, which states that for lazy_split_view, we need to consider the case where the const Pattern is not range, and then I subsequently submitted the LWG 3599. When I further reviewing the begin() const of other range adapters, I found that most of them only require const V to be range, this seemingly loose constraint made me raise this question. In order to enable the range adapters' begin() const, theoretically, the constraints for const V should be exactly the same as V, which means that the long list of constraints on V, such as elements_view, needs to be replaced with const V instead of only constraints const V to be a range. But in fact, it seems that the standard is not interested in the situation where the iterator and sentinel types of V and const V are very different.
Recent SG9 discussion on LWG3564 concluded that the intended design is that x and as_const(x) should be required to be substitutable with equal results in equality-preserving expressions for which both are valid. In other words, they should be "equal" in the [concepts.equality] "same platonic value" sense. Thus, for instance, it is not valid for x and as_const(x) to have entirely different elements. The exact wording and scope of the rule will have to await a paper, and we'll have to take care to avoid banning reasonable code. But certainly things like "x is a range of pairs but as_const(x) is a range of ints" are not within any reasonable definition of "reasonable".
69,268,747
69,268,854
C++ linker error for extern-declared global object
I have trouble using an extern-declared global object. As I understand it I should be able to declare an object as extern in a header file, define it in a source file, then use the object in any other source file where the header is included. However, with the following structure, I get a linker error saying that the logger symbol is undefined. logger.hpp: #ifndef MY_LOGGER_H #define MY_LOGGER_H namespace foo { class Logger { public: void log(int num); }; extern Logger logger; } // foo #endif logger.cpp: #include "logger.hpp" using namespace foo; void Logger::log(int num) { /* Do stuff */ } Logger logger; main.cpp: #include "logger.hpp" using namespace foo; int main() { logger.log(3); // arbitrary number } If I declare a Logger in main(), everything works fine, so the header and source files are being included and linked correctly. I get the same error using built-in types (e.g. int), so I don't think it's an issue with the Logger class itself either. Appologies if this is a dumb question, I have a few years' experience in C++ but I've avoided global variables like the plague until now.
This declaration Logger logger; defines a variable in the global namespace. You need to write using qualified name #include "logger.hpp" using namespace foo; void Logger::log(int num) { /* Do stuff */ } Logger foo::logger; From the C++ 20 Standard (9.8.1.2 Namespace member definitions) 2 Members of a named namespace can also be defined outside that namespace by explicit qualification (6.5.3.2) of the name being defined, provided that the entity being defined was already declared in the namespace and the definition appears after the point of declaration in a namespace that encloses the declaration’s namespace Here is a demonstrative program. #include <iostream> namespace foo { class Logger { public: void log(int num); }; extern Logger logger; } // foo using namespace foo; void Logger::log(int num) { /* Do stuff */ } Logger foo::logger; int main() { logger.log(3); return 0; }
69,268,771
72,947,616
How do I use Visual Studio Code to build, debug and run existing C++ solution (.sln) from Visual Studio 2019?
I have an existing C++ solution which I have been building and running using Visual Studio 2019. I would like to build and run the application on Ubuntu using g++ and Visual Studio Code. What is the best way of achieving this? Most of the samples provided are building single .cpp file but my application consists of many .cpp files built into one application executable. https://code.visualstudio.com/docs/cpp/config-linux How do I set up Visual Studio Code to compile C++ code? I have installed the https://github.com/fernandoescolar/vscode-solution-explorer extension but that only enables me to browse the C++ solution. How to build the solution and being able to debug and run the C++ application? Any advice and insight is appreciated.
Use CMake and generate CMakeLists.txt from .sln and included .vcxproj using https://github.com/pavelliavonau/cmakeconverter cmake-converter -s MyProject.sln
69,269,261
69,269,633
Using class member as key in a std::map of said class
I have a class with an enum class member variable which is intended to be used as a description of the instantiated object, there will never be two instantiated objects of the same type, example: class A { enum class Type { Type1, Type2, ...} type; } I want to store all instantiated objects within a collection for easy access based on the type, so I think that a map would be suitable: class B { std::map<A::Type, A> components; } However, something tells me this is not great design because I am effectively duplicating the same data, i.e. using a class (A) member variable (type) as a key that points to a value (object of class A) that also holds the same information. The other alternative would be not to use the enum as a class A member variable but define that enum within class B and only using it as a key. Any advice?
Lets consider the key features of the map unique keys ordererd with respect to keys keys are const, values not key are stored seperately from the mapped values Your requirement is in contrast with the last bullet so now you can consider what compromise you can make with the others. std::set<A,CustomComparator> With a custom comparator you can ensure unique keys that can be stored in the values and sorting can be the same as with the map. But elements are const. You could use mutable but this bypasses const-correctness and should be used with care. std::vector<A> This is the most flexible but you need to take care of almost everything you got from the map manually. It can be feasible if you populate the vector only once and then only access elements, because then you need to check for uniqueness and sort the elements only once. some non-std container Jarod42 suggested boosts intrusive set. There might be other non-standard containers that fit your needs. just stay with std::map<A::type,A> If the key is only a single enum value, then storing the keys twice is an easy solution that has some cost, but allows you to use a map when that is the container you want to use. Not store the keys in the mapped_values in the first place This is actually the cleanest solution when the mapped_values are only stored in the map and not used outside of the map. And when you still need the mapped_values together with the keys outside of the map you can use std::pair<type::A,A>.
69,269,563
70,950,612
how to acquire a structure of eax register in c++
if i use struct, it will take up memory unlike the actual register where al and ah together make ax register and the eax register merges with the ax register. if i use union, al and ah values will be in the same place where in real, they are 2 separate registers. how can i acquire a structure of the eax register? i have noticed in the dos.h header (which is in c) has "union regs" which has the structure i need. but on my machine, there is no such "union regs". till now, i've tried :- struct regs { uint32 eax, ebx, ecx, edx, esi, edi, esp, ebp; uint16 ax, bx, cx, dx; uint8 ah, al, bh, bl, ch, cl, dh, dl; };
@Sebastian mentioned that I should combine structs and unions to get that kind of a architecture. I was not sure if nested structs and unions would but I tried and it worked:- union {int32 eax; union {int16 ax; struct {int8 ah, al;};};} reg_eax; Note that using a struct or union without a name works as long as a different member of the same level does not have the same name.
69,269,979
69,270,373
i'm getting "timeout: the monitored command dumped core" error in c++ code of stack
There are 3 stacks stk0, stk1 and stk2. To distinguish push and pop the program is using push0, push1 and push2 for 3 stacks and similarly pop0, pop1, and pop2. Program ends with stop0, stop1 or stop2 and shows contents of stack0, stack1 or stack2 and then exits. My code works fine for all test cases accept the one i mentioned below. #include <iostream> #include <stack> using namespace std; int main() { stack<string> stk0; stack<string> stk1; stack<string> stk2; while(true) { string a; cout<<"Give one of options: pop, push, stop\n"; cin >> a; if(a=="push0") { string b; cin >> b; stk0.push(b); } else if(a=="push1") { string b; cin >> b; stk1.push(b); } else if(a=="push2") { string b; cin >> b; stk2.push(b); } else if(a=="pop0") { if(!stk0.empty()) { string b = stk0.top(); stk0.pop(); cout<<"Element popped from stack 0 is: "<<b<<endl; } else cout<<"Underflow in stack 0\n"; } else if(a=="pop1") { if(!stk1.empty()) { string b = stk1.top(); stk1.pop(); cout<<"Element popped from stack 1 is: "<<b<<endl; } else cout<<"Underflow in stack 1\n"; } else if(a=="pop2") { if(!stk2.empty()) { string b = stk2.top(); stk2.pop(); cout<<"Element popped from stack 2 is: "<<b<<endl; } else cout<<"Underflow in stack 2\n"; } else if(a=="stop0") { while(!stk0.empty()) { cout<<stk0.top()<<endl; stk0.pop(); } break; } else if(a=="stop1") { while(!stk0.empty()) { cout<<stk1.top()<<endl; stk1.pop(); } break; } else if(a=="stop2") { while(!stk2.empty()) { cout<<stk2.top()<<endl; stk2.pop(); } break; } } } when i input push0 Agra push1 Jaipur push0 Lucknow push2 Bhopal push1 Ajmer push1 Udaipur pop0 pop1 push2 Indore push0 Meerut stop1 i get timeout: the monitored command dumped core error.
Look at this part of your code: else if(a=="stop1") { while(!stk0.empty()) { cout<<stk1.top()<<endl; stk1.pop(); } break; } When a is stop1, the loop will continuously rotate and stk1 will be popped and its value will be printed, but the loop won't exit because the condition is !stk0.empty() and not !stk1.empty(). You probably wanted to do this: else if(a=="stop1") { while(!stk1.empty()) { // <- Notice change from 'stk0.empty()' to 'stk1.empty()' cout<<stk1.top()<<endl; stk1.pop(); } break; }
69,270,119
69,270,757
Convert std::vector<string> to just a std::string in C++20 using std::views
I am trying to convert a vector to a string and join with C++20(MSVC on visual studio 19 v142, c++latest). std::vector<std::string> strings = { "1s","2s" }; auto view1 = strings | std::views::transform([](std::string num) {return std::format("{} ", num); }); // okay auto view2 = strings | std::views::join; // okay auto view3 = strings | std::views::transform([](std::string num) {return std::format("{} ", num); }) | std::views::join; // Compiler error //error C2678: binary '|': no operator found which takes a left-hand operand of type 'std::ranges::transform_view<std::ranges::ref_view<std::vector<std::string,std::allocator<std::string>>>,_Ty>' " I know I can do it elegantly with actions in range-v3, but I am not supposed to use it. Is there a way to do it, by just using C++20 standard library?
In the original design of views::join, it didn't just join any range of ranges, it had to be a range of reference to ranges. This worked: auto view2 = strings | views::join; // okay Because strings is a range of string& (which is a reference to a range). But this did not: auto view3 = strings | views::transform([](std::string num) { return std::format("{} ", num) }) | views::join; // Compiler error because now we're joining a range of string (specifically, prvalue strings, which is what your function returns). That violated the constraints. range-v3's views::join has the same constraint. However, it is a fairly common use-case to be able to do this. So a recent defect against C++20 was to change the design of views::join to allow it to join any range of ranges. That's P2328. libstdc++ (gcc's standard library) already implements this, MSVC does not yet, nor does range-v3 (though I have a PR open). So the official C++20 answer is: what you're doing is correct, your library just hasn't implemented it yet. Now, the range-v3 answer is to introduce a caching layer: auto view3 = strings | rv::transform([](std::string num) { return std::format("{} ", num) }) | rv::cache1 | rv::join; What cache1 does is cache one element at a time, which turns our range of prvalue string into a range of lvalue string such that join can successfully join it. The P2328 design is to basically incorporate this internally into join itself so that you don't have to do it manually. But until that happens, you can do the above using range-v3. There is no cache1 in C++20 and won't be in C++23 either. Or you can use Casey's hack. But also don't.
69,270,633
69,271,349
Behavior of If constexpr in C++
Even having a lot a questions about this topic, I am having more and more problems. I think the problem is in understanding the meaning of certain words. All quotes below are from Cppreference What does 'discarded' mean in the text below? I understand 'discarded' as something never compiled/touched, something that, whatever it is (like random characters that would be errors), it won't interfere in the rest of the program. In a constexpr if statement, the value of condition must be a contextually converted constant expression of type bool (until C++23)an expression contextually converted to bool, where the conversion is a constant expression (since C++23). If the value is true, then statement-false is discarded (if present), otherwise, statement-true is discarded. What 'instantiaded' mean ? If a constexpr if statement appears inside a templated entity, and if condition is not value-dependent after instantiation, the discarded statement is not instantiated when the enclosing template is instantiated . What 'checked' mean? I understand that 'checked' means the code was totally compiled and verified for any possible error at that time. Outside a template, a discarded statement is fully checked. if constexpr is not a substitute for the #if preprocessing directive:
Consider this example: #include <iostream> #include <string> template <typename T> void foo() { T t; if constexpr (std::is_same_v<T,std::string>){ std::cout << t.find("asd"); } else { t = 0; std::cout << t; } } int main () { foo<int>(); // (2) } When T is a type that does not have a find method, then std::cout << t.find("asd") is an error. Nevertheless, the template is ok. What 'instantiaded' mean ? The template is instantiated in (2). foo is just a template, instantiating it results in a function foo<int> that you can call. What does 'discarded' mean in the text below? The true-branch is discarded when foo<int> is instantiated (because the condition is false). Hence, even though int has no find method, the code compiles without error. Now consider this similar, but very different example: #include <iostream> int main () { int x = 0; if constexpr (true) { std::cout << x; } else { x.find("asd"); } } What 'checked' mean? The text is a little contrived, it says that in the above example the false branch is discarded, but nevertheless it is checked, because it is outside of a template. It is just the english term: "checked" means the compiler checks if the code is correct. int has no method find, hence the above results in an error: <source>:8:15: error: request for member 'find' in 'x', which is of non-class type 'int' 8 | x.find("asd"); | ^~~~ Even though this statement is never executed, it must be valid code.
69,270,763
69,270,854
Cannot catch in the initialize list
For the following code: #include <iostream> struct Str { Str() { throw 100; } }; class Cla { public: Cla() try : m_mem() { } catch(...) { std::cout << "Catch block is called"<< std::endl; } private: Str m_mem; }; int main() { Cla obj; } I tried to catch the exception in the catch block. But after the catch block is run, the system still calls std::terminate to terminate the program. I didn't re-throw the exception in the catch block, can you tell me why the system crashes? Thanks! Here is a test on compiler explorer: https://godbolt.org/z/74sTcxrY4
You're contradicting yourself. I tried to catch the exception in the catch block. But after the catch block is run If the catch block is run, you succeeded catching the exception from the initializer list. You're just surprised by what happened next. First, let's think about what happens when a constructor throws: the object is not constructed. Right? the constructor never finished setting it up, so you can't use it for anything. int main() { Cla obj; // member subobject constructor throw, but we caught it! obj.print(); // but we still can't use this here, because the constructor never completed } So it doesn't really make sense to let you swallow the exception here. You can't handle it, because you can't go back and re-try constructing your member and base-class subobjects. If you don't have a properly-constructed object, the only way C++ has of dealing with that is to unwind the block scope in which that object would otherwise be assumed to be ... well, a real object. Hence, per the documentation: Every catch-clause in the function-try-block for a constructor must terminate by throwing an exception. If the control reaches the end of such handler, the current exception is automatically rethrown as if by throw;. The return statement is not allowed in any catch clause of a constructor's function-try-block. ... and equivalently in the standard (draft) The currently handled exception is rethrown if control reaches the end of a handler of the function-try-block of a constructor or destructor. Otherwise, flowing off the end of the compound-statement of a handler of a function-try-block is equivalent to flowing off the end of the compound-statement of that function (see [stmt.return])
69,270,929
69,278,195
Is there any practical reason why std::get_if (std::variant) takes a variant argument by pointer instead of by value/&/const&?
I've never used std::get_if, and since its name is different from std::get, I don't see a reason why its argument should be a pointer¹ (whereas std::get has a by-reference parameter). ¹If it was named std::get too, then overload resolution would be a reason enough. Yes, my question could be duped to the question Is it absolutely necessary for std::any_cast() and std::get_if(std::variant) to take pointer as an argument?, but the point is that there's no answer there that addresses std::get_if vs std::get, just one comment; the only answer concentrates on std::any_cast.
This is because get_if is noexcept, so an exception will never be thrown. In order to achieve this, it must return a pointer so that nullptr can be returned when the access fails. Because it returned the pointer, it must take the pointer of the variant. If it takes the reference of variant, then it must be able to accept the type of variant&, const variant&, variant&& and const variant&&, but it does not make sense for the pointer to remain ref-qualified. Considering that get_if accepts variant&&, what you do is return the address of an xvalue, which is terrible. Even if get_if only allows variant& and const variant&, the latter can still accept a variant&& and return a dangling.
69,271,268
69,718,929
Windows Open Dialog Box hangs forever with Address Sanitizer enabled
When Address Sanitizer is enabled, the Open Dialog Box cannot be shown. It hangs forever. Thank you. It hangs when running hr = pFileOpen->Show(NULL); #include <windows.h> #include <shobjidl.h> int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow) { HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); if (SUCCEEDED(hr)) { IFileOpenDialog* pFileOpen; // Create the FileOpenDialog object. hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_ALL, IID_IFileOpenDialog, reinterpret_cast<void**>(&pFileOpen)); if (SUCCEEDED(hr)) { // Show the Open dialog box. hr = pFileOpen->Show(NULL); pFileOpen->Release(); } CoUninitialize(); } return 0; }
The fix is available in current VS 2022 and VS 2019 Partial workaround for older VS: To make this occur less often, add SetProcessAffinityMask(GetCurrentProcess(), 1); at the beginning of your program. This seem to fix completely Open Dialog case, but doesn't fix more complex occurrences. (Be sure not to keep this workaround for normal program runs, as it effectively disables running on multiple CPU cores)
69,271,601
69,272,704
what is the reason that its only finds "if" condition is true where no such string exist that satisfies this condition
can anyone help me with my code? I don't understand where its making such problem. my code is to check if a given string is valid variable or not. My checkIdentifier function should return false for some cases and true for some cases but its only return false. my input is abcd and its will print valid but when my input is abcd# its will print invalid #include<bits/stdc++.h> #include<strings.h> using namespace std; string ishfakur; void getInput(){ cin>>ishfakur; } bool checkKeyword(){ string keyword[32]={ "auto","double","int","struct","break","else","long", "switch","case","enum","register","typedef","char", "extern","return","union","const","float","short", "unsigned","continue","for","signed","void","default", "goto","sizeof","voltile","do","if","static","while" } ; for(int i=0;i<32;i++){ if(ishfakur==keyword[i]){ return true; } } } bool checkIdentifier(){ if(ishfakur.length()>=30 || ishfakur.at(0)<='9' || strstr(ishfakur.c_str(),"#") || checkKeyword()==true) return false; else return true; } void giveOutout(bool st){ if(st==true){ printf("valid"); } else printf("invalid"); } int main(){ bool status; getInput(); status = checkIdentifier(); giveOutout(status); }
its solved Here the condition ishfakur.at(0)>='0' satisfies even when its a valid string because the ASCI values for a to z are greater than 0 so its always true. So I have changed it to ishfakur.at(0)<='9' now I am checking if its less than equals to 9 now its restricted between 0 to 9. So no chance for a valid string to be invalid. Also checkKeyword() function has returns nothing if the condition is not satisfies but it has to return either true or false as the return type is Boolean. So after the loop a default return false; added. this was the only reason the program couldn't provide desired output. #include <string> #include <iostream> #include <cstdio> #include<strings.h> using namespace std; string ishfakur; string keyword[32]={ "auto","double","int","struct","break","else","long", "switch","case","enum","register","typedef","char", "extern","return","union","const","float","short", "unsigned","continue","for","signed","void","default", "goto","sizeof","voltile","do","if","static","while" } ; void getInput(){ cin>>ishfakur; } bool checkKeyword(){ for(int i=0;i<32;i++){ if(ishfakur==keyword[i]){ return true; } } return false; } bool checkIdentifier(){ bool status=true; if(ishfakur.length()>=30 || ishfakur.at(0)<='9' || strstr(ishfakur.c_str(),"#") || checkKeyword()==true) return false; return status; } void giveOutout(){ if(checkIdentifier()==true){ printf("valid"); } else printf("invalid"); } int main(){ getInput(); giveOutout(); }
69,271,802
69,272,338
String subscript out of range in Visual Studio
I've been following Codecademy's course on C++ and I've reached the end but I'm confused with the last task. We have to create a program which filters chosen words as 'swear words' and replaces them with whichever character chosen. I have written the code in Visual Studio which can be seen below main.cpp #include <iostream> #include <string> #include "functions.h" int main() { std::string word = "broccoli"; std::string sentence = "I sometimes eat broccoli."; bleep(word, sentence); for (int i = 0; i < sentence.size(); i++) { std::cout << sentence[i]; } std::cout << "\n"; } functions.cpp #include <iostream> #include <string> #include "functions.h" void asterisk(std::string word, std::string &text, int i) { for (int k = 0; k < word.size(); k++) { text[i + k] = '*'; } } void bleep(std::string word, std::string &text) { for (int i = 0; i < text.size(); i++) { int match = 0; for (int j = 0; j < word.size(); j++) { if (text[i + j] == word[j]) { match++; } } if (match == word.size()) { asterisk(word, text, i); } } } functions.h #pragma once void bleep(std::string word, std::string &text); void asterisk(std::string word, std::string &text, int i); Now, when I run this code in Visual Studio, I get an assert relating to string subscript it out of range. But with the same code, it works in Codecademys in browser code editor. I cannot for the life of me work out why it won't run in VS.
This for inner loop for (int j = 0; j < word.size(); j++) { if (text[i + j] == word[j]) { match++; } } does not take into account that the tail of the string text can be much less than the value of word.size(). So this for loop provokes access memory outside the string text. To avoid this situation at least rewrite the outer loop the following way if ( not ( text.size() < word.size() ) ) { for ( size_t i = 0, n = text.size() - word.size() + 1; i < n; i++) { //... } A more efficient and safer approach is to use the method find of the class std::string instead of loops. Here is a demonstrative program. #include <iostream> #include <string> std::string & bleep( std::string &text, const std::string &word, char c ) { if ( auto n = word.size() ) { for ( std::string::size_type pos = 0; ( pos = text.find( word, pos ) ) != std::string::npos; pos += n ) { text.replace( pos, n, n, c ); } } return text; } int main() { std::string word = "broccoli"; std::string sentence = "I sometimes eat broccoli."; std::cout << sentence << '\n'; std::cout << bleep( sentence, word, '*' ) << '\n'; return 0; } The program output is I sometimes eat broccoli. I sometimes eat ********.
69,271,840
69,272,238
Would a shared_ptr be materialized if I'm only calling a method on its object?
I have a trivial question on c++ shared_ptrs. Please consider the following pseudo code, class Foo{ int run(); } class Bar{ // NOTE: returns a shared_ptr, not a const ref shared_ptr<Foo> GetFoo() const; } Bar bar{...}; int k = bar.GetFoo()->run(); in this scenario, when we call bar.GetFoo(), would a shared_ptr<Foo> be materialized (i.e. creating an atomic_counter, etc)? Or can the compiler simplify the last statement further?
The rules of the language require a shared_ptr<Foo> to be materialized even if it is immediately discarded. Calling ->run() only affects when the temporary is materialized, not whether. In practice, the rules about when the temporary is materialized are actually just rules about who has to allocate the memory for the temporary object to reside in. The construction of the temporary object occurs before GetFoo even returns, just like pre-C++17. This is because only GetFoo or one of its callees actually knows how to perform the construction (e.g. which arguments to pass to the shared_ptr constructor). All that being said, the materialization can be elided only if the compiler can prove that it doesn't change the observable behaviour of the program. Since shared_ptr is fairly complicated (it has a control block with atomic counters as you seem to be aware of) it is unlikely that the compiler can prove this. Indeed, even when the definition of the function that creates the shared_ptr resides in the same translation unit, it appears that the initialization and destruction of the shared_ptr object are simply inlined, not elided.
69,272,046
69,311,493
Disable or enable warnings for cppcheck using a configuration file
With clang-tidy static analyzer I can keep a file (.clang-tidy) in the root of the project with the warnings I want to activate or deactivate. clang-tidy will look for this file (as far I know) and use the options defined there. This saves me from hard coding long command lines in CMake or Makefiles. Is it possible to do the same with cppcheck static analyzer? Currently I have this very long command line hardcoded: cppcheck --max-ctu-depth=3 --enable=all --inline-suppr --suppress=*:*thrust/complex* --suppress=missingInclude --suppress=syntaxError --suppress=unmatchedSuppression --suppress=preprocessorErrorDirective --language=c++ --std=c++14 --error-exitcode=666 This is an example of .clang-tidy configuration file that I keep at the root of a project: --- Checks: ' *, -readability-magic-numbers, -modernize-use-nodiscard, -altera-struct-pack-align, -cert-err58-cpp, -cppcoreguidelines-avoid-non-const-global-variables, -cppcoreguidelines-macro-usage, -cppcoreguidelines-pro-bounds-array-to-pointer-decay, -cppcoreguidelines-pro-type-vararg, -cppcoreguidelines-avoid-magic-numbers, -fuchsia-default-arguments-calls, -fuchsia-trailing-return, -fuchsia-statically-constructed-objects, -fuchsia-overloaded-operator, -hicpp-vararg, -hicpp-no-array-decay, -llvm-header-guard, -llvmlibc-restrict-system-libc-headers, -llvmlibc-implementation-in-namespace, -llvmlibc-callee-namespace ' WarningsAsErrors: '*' HeaderFilterRegex: '.' AnalyzeTemporaryDtors: false FormatStyle: file ...
You can store the configuration in a *.cppcheck file and then use the --project command line option to run the check. See the manual - Cppcheck GUI project section. cppcheck files are normally generated by CppCheckGUI via File -> New project file. The exact syntax is undocumented but it's basically just an XML file and looks to be fairly straightforward if you want to create the file directly without using the GUI. Sample test.cppcheck file: <?xml version="1.0" encoding="UTF-8"?> <project version="1"> <builddir>test2-cppcheck-build-dir</builddir> <platform>Unspecified</platform> <analyze-all-vs-configs>false</analyze-all-vs-configs> <check-headers>true</check-headers> <check-unused-templates>false</check-unused-templates> <max-ctu-depth>10</max-ctu-depth> <exclude> <path name="WINDOWS/"/> </exclude> <suppressions> <suppression>IOWithoutPositioning</suppression> </suppressions> </project>
69,273,154
69,273,698
Problem while taking input using cin after detaching that thread in C++
Code: #include <iostream> #include <windows.h> #include <thread> using namespace std; int input(int time, int *ptr) { int sec = 0, flag = 0; thread t1([&]() { cin >> *ptr; sec = 0; flag = 1; t1.detach(); }); thread t2([&]() { while (flag == 0) { if (sec == time) { if (t1.joinable()) { t1.detach(); } break; } Sleep(1000); sec++; } }); t2.join(); return flag; } int start(int time, int *ptr) { return input(time, ptr); } int main() { int arr[10], flag2 = 1, count = 0; for (int i = 0; i < 10; i++) { cout << "Enter " << i + 1 << " element: "; flag2 = start(2, arr + i); if (flag2 == 0) { cout << endl; break; } count++; } cout << endl << "Array elements: "; for (int i = 0; i < count; i++) { cout << *(arr + i) << " "; } int temp; cout << "\nEnter temporary value: "; cin >> temp; cout << "Here is what you gave as input: " << temp; return 0; } Output: Enter 1 element: 5 Enter 2 element: 2 Enter 3 element: 6 Enter 4 element: 8 Enter 5 element: Array elements: 5 2 6 8 Enter temporary value: 7 terminate called after throwing an instance of 'std::system_error' what(): No such process Expected output: Enter 1 element: 5 Enter 2 element: 2 Enter 3 element: 6 Enter 4 element: 8 Enter 5 element: Array elements: 5 2 6 8 Enter temporary value: 7 Here is what you gave as input: 7 Code overview: Above code takes array input from user until user wants to stop, like I want to take infinite input from user, for linked list/stack/queue, I know that array has fixed size, but my problem is not with taking infinite input, that works fine, I used two thread one thread (timer t2) for counting seconds (in this case 2 seconds) and another (input t1) to take input from user. When user finished giving input he just need to wait for 2 seconds and thread t2 will detach thread t1, and now here comes the problem. Problem: Everything is right till line 59, but then when I try to take input for 'temp' an exception occurs, terminate called after throwing an instance of 'std::system_error' what(): No such process. As I said before about my code, I am taking pointer from user and storing value at that address. But, when user stopped giving input and thread t2 detached t1, then code resumes, no problem till here but input of cin inside thread t1 remain incomplete, it requires an input, hence when I give input for 'temp' it takes it for my previous input inside thread t1 which was detached by thread t2 without taking input, I think, since that thread is no longer attached to main thread, this exception comes. Is there any solution available for this? I tried a lot but failed, please review my code. Any help will be appreciated.
In your case you should use atomic shared variables across threads. The std::cin is blocking operation. In your code two seconds later doing detach for thread1. But std::cin still waiting for input... The console window can std::cin or std::cout but not both at the same time so you need to change algorithm to avoid this problem.
69,273,240
69,274,294
Iterations getting skipped in a for loop
I'm currently working on a reliability design algorithm, which I found on this video https://www.youtube.com/watch?v=uJOmqBwENB8 here. I wrote the code in c++, but I've came across a problem where in one of the loops some iterations get skipped. Here is the whole code: #include <iostream> #include <cmath> #include <vector> #include <utility> using namespace std; int main(){ int n; cin>>n; int cost[n],num_available[n],max_cost; double rel[n]; for(int i=0;i<n;i++) cin>>cost[i]; for(int i=0;i<n;i++) cin>>rel[i]; for(int i=0;i<n;i++) cin>>num_available[i]; cin>>max_cost; vector<pair<double,int>> resSet; resSet.push_back(make_pair(1,0)); for(int i=0;i<n;i++){ vector<pair<double,int>> tempSet; for(int j=0;j<num_available[i];j++){ for(int pos=0;pos<resSet.size();pos++){ int sum_left_costs=0; for(int k=i+1;k<n;k++) sum_left_costs+=cost[k]; if(sum_left_costs+resSet[pos].second+cost[i]*(j+1)>max_cost) break; tempSet.push_back (make_pair(resSet[pos].first*(1-pow((1-rel[i]),j+1)) ,resSet[pos].second+cost[i]*(j+1))); } } for(int i=0;i<tempSet.size();i++){ cout<<"Reliability: "<<tempSet[i].first<< ", Price: "<<tempSet[i].second<<endl; } resSet=tempSet; cout<<endl; } double maxRel=0,pos; for(int i=0;i<resSet.size();i++){ if(maxRel<resSet[i].first){ pos=i; maxRel=resSet[i].first; } } cout<<"Best Reliability: "<<resSet[pos].first<< " for price: "<<resSet[pos].second; return 0; } Anyways, while trying to find the problem, I added some changes to code in the loops, just to see how many iterations does the loop go through: for(int i=0;i<n;i++){ cout<<"i="<<i<<", "; vector<pair<double,int>> tempSet; for(int j=0;j<num_available[i];j++){ cout<<"j="<<j<<", "; for(int pos=0;pos<resSet.size();pos++){ cout<<"pos="<<pos<<", "; int sum_left_costs=0; for(int k=i+1;k<n;k++) sum_left_costs+=cost[k]; if(sum_left_costs+resSet[pos].second+cost[i]*(j+1)>max_cost) break; tempSet.push_back (make_pair(resSet[pos].first*(1-pow((1-rel[i]),j+1)) ,resSet[pos].second+cost[i]*(j+1))); } } resSet=tempSet; cout<<endl; } Now, once I executed the program, these were the results: Input: 3 30 15 20 0.9 0.8 0.5 2 3 3 105 Output: i=0, j=0, pos=0, j=1, pos=0, i=1, j=0, pos=0, pos=1, j=1, pos=0, pos=1, j=2, pos=0, pos=1, i=2, j=0, pos=0, pos=1, pos=2, pos=3, j=1, pos=0, pos=1, j=2, pos=0, pos=1, Best Reliability: 0.63 for price: 105 But the expected output should of been: i=0, j=0, pos=0, j=1, pos=0, i=1, j=0, pos=0, pos=1, j=1, pos=0, pos=1, j=2, pos=0, pos=1, i=2, j=0, pos=0, pos=1, pos=2, pos=3, j=1, pos=0, pos=1,pos=2,pos=3, j=2, pos=0, pos=1, pos=2, pos=3 Best Reliability: 0.648 for price: 100 Any ideas what could cause these problems? P.S. Yes i know I need to learn how to use a debugger.
If you switch your break to a continue it gets your expected results. Reliability: 0.9, Price: 30 Reliability: 0.99, Price: 60 Reliability: 0.72, Price: 45 Reliability: 0.792, Price: 75 Reliability: 0.864, Price: 60 Reliability: 0.8928, Price: 75 Reliability: 0.36, Price: 65 Reliability: 0.396, Price: 95 Reliability: 0.432, Price: 80 Reliability: 0.4464, Price: 95 Reliability: 0.54, Price: 85 Reliability: 0.648, Price: 100 Reliability: 0.63, Price: 105 Best Reliability: 0.648 for price: 100 break will exit the innermost loop, continue will go the next iteration
69,273,679
69,288,813
Can this matrix calculation be implemented or approximated without an intermediate 3D matrix?
Given an NxN matrix W, I'm looking to calculate an NxN matrix C given by the equation in this link: https://i.stack.imgur.com/dY7rY.png, or in LaTeX $$C_{ij} = \max_k \bigg\{ \sum_l \bigg( W_{ik}W_{kl}W_{lj} - W_{ik}W_{kj} \bigg) \bigg\}.$$ I have tried to implement this in PyTorch but I've either encountered memory problems by constructing an intermediate NxNxN 3D matrix which, for large N, causes my GPU to run out of memory, or used a for-loop over k which is then very slow. I can't work out how I can get round these. How might I implement this calculation, or an approximation of it, without a large intermediate matrix like this? Suggestions, pseudocode in any language or an implementation in any of Python/Numpy/PyTorch would be much appreciated.
The first solution using Numba (You can do the same using Cython or plain C) would be to formulate the problem using simple loops. import numpy as np import numba as nb @nb.njit(fastmath=True,parallel=True) def calc_1(W): C=np.empty_like(W) N=W.shape[0] for i in nb.prange(N): TMP=np.empty(N,dtype=W.dtype) for j in range(N): for k in range(N): acc=0 for l in range(N): acc+=W[i,k]*W[k,l]*W[l,j]-W[i,k]*W[k,j] TMP[k]=acc C[i,j]=np.max(TMP) return C Francesco provided a simplification which scales far better for larger array sizes. This leads to the following, where I also optimized away a small temporary array. @nb.njit(fastmath=True,parallel=True) def calc_2(W): C=np.empty_like(W) N=W.shape[0] M = np.dot(W,W) - N * W for i in nb.prange(N): for j in range(N): val=W[i,0]*M[0,j] for k in range(1,N): TMP=W[i,k]*M[k,j] if TMP>val: val=TMP C[i,j]=val return C This can be optimized further by partial loop unrolling and optimizing the array access. Some compilers may do this automatically. @nb.njit(fastmath=True,parallel=True) def calc_3(W): C=np.empty_like(W) N=W.shape[0] W=np.ascontiguousarray(W) M = np.dot(W.T,W.T) - W.shape[0] * W.T for i in nb.prange(N//4): for j in range(N): val_1=W[i*4+0,0]*M[j,0] val_2=W[i*4+1,0]*M[j,0] val_3=W[i*4+2,0]*M[j,0] val_4=W[i*4+3,0]*M[j,0] for k in range(1,N): TMP_1=W[i*4+0,k]*M[j,k] TMP_2=W[i*4+1,k]*M[j,k] TMP_3=W[i*4+2,k]*M[j,k] TMP_4=W[i*4+3,k]*M[j,k] if TMP_1>val_1: val_1=TMP_1 if TMP_2>val_2: val_2=TMP_2 if TMP_3>val_3: val_3=TMP_3 if TMP_4>val_4: val_4=TMP_4 C[i*4+0,j]=val_1 C[i*4+1,j]=val_2 C[i*4+2,j]=val_3 C[i*4+3,j]=val_4 #Remainder for i in range(N//4*4,N): for j in range(N): val=W[i,0]*M[j,0] for k in range(1,N): TMP=W[i,k]*M[j,k] if TMP>val: val=TMP C[i,j]=val return C Timings W=np.random.rand(100,100) %timeit calc_1(W) #16.8 ms ± 131 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) %timeit calc_2(W) #449 µs ± 25.7 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) %timeit calc_3(W) #259 µs ± 47.4 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) W=np.random.rand(2000,2000) #Temporary array would be 64GB in this case %timeit calc_2(W) #5.37 s ± 174 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) %timeit calc_3(W) #596 ms ± 30.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
69,273,730
69,273,831
Why does sleep not wait, no matter how high the value entered in the parentheses is?
I'm trying to rewrite a program that I have written earlier in C++ that connects to my laptop over ssh or sftp based on what the user types, that program works fine but I am trying to write the std::cout out letter by letter with a 200ms delay in between characters. Here's my current attempt(doesn't work): #include <iostream> #include <stdlib.h> #include <string> #include <unistd.h> int main() { std::cout << "S"; sleep(0.2); std::cout << "S"; sleep(0.2); std::cout << "H"; sleep(0.2); std::cout << " o"; sleep(0.2); std::cout << "r"; sleep(0.2); std::cout << " S"; sleep(0.2); std::cout << "F"; sleep(0.2); std::cout << "T"; sleep(0.2); std::cout << "P"; std::cout << "?\n" << ">"; std::string contype; std::cin >> contype; if(contype == "ssh") { system("ssh redacted"); } if(contype == "sftp") { system("sftp redacted"); } }
If you are using c++11, you should use thread and chrono to sleep for 200ms. #include <iostream> #include <stdlib.h> #include <string> #include <unistd.h> #include <chrono> #include <thread> int main() { std::cout << "S" << std::flush; std::this_thread::sleep_for(std::chrono::milliseconds(200)); std::cout << "S" << std::flush; std::this_thread::sleep_for(std::chrono::milliseconds(200)); std::cout << "H" << std::flush; std::this_thread::sleep_for(std::chrono::milliseconds(200)); std::cout << " o" << std::flush; std::this_thread::sleep_for(std::chrono::milliseconds(200)); std::cout << "r" << std::flush; std::this_thread::sleep_for(std::chrono::milliseconds(200)); std::cout << " S" << std::flush; std::this_thread::sleep_for(std::chrono::milliseconds(200)); std::cout << "F" << std::flush; std::this_thread::sleep_for(std::chrono::milliseconds(200)); std::cout << "T" << std::flush; std::this_thread::sleep_for(std::chrono::milliseconds(200)); std::cout << "P" << std::flush; std::cout << "?\n" << ">"; std::string contype; std::cin >> contype; if(contype == "ssh") { system("ssh redacted"); } if(contype == "sftp") { system("sftp redacted"); } } should work just fine. Edit: you should output std::flush at the end of each output to explicitly flush the buffer. Edit 2: as mentioned in the comments, defining a constant instead of using the magic number upon every iteration is better. Another option is to define a function that goes over a string and prints each letter, then waits. This would like this - #include <iostream> #include <stdlib.h> #include <string> #include <unistd.h> #include <chrono> #include <thread> void printAndSleep(const std::string& msg, int timePeriod); int main() { const std::string msg = "SSH or SFTP"; const int waitingTime = 200; printAndSleep(msg, waitingTime); std::cout << "?\n" << ">"; std::string contype; std::cin >> contype; if(contype == "ssh") { system("ssh redacted"); } if(contype == "sftp") { system("sftp redacted"); } } void printAndSleep(const std::string& msg, int timePeriod){ for (char c : msg) { std::cout << c << std::flush; std::this_thread::sleep_for(std::chrono::milliseconds(timePeriod)); } }
69,273,765
69,274,120
cannot catch segmentation fault second time
I'm trying to restart the program when segmention fault occures. I have following minimal reproducible code:- #include <csignal> #include <unistd.h> #include <iostream> int app(); void ouch(int sig) { std::cout << "got signal " << sig << std::endl; exit(app()); } struct L { int l; }; static int i = 0; int app() { L *l= nullptr; while(1) { std::cout << ++i << std::endl; sleep(1); std::cout << l->l << std::endl; //crash std::cout << "Ok" << std::endl; } } int main() { struct sigaction act; act.sa_handler = ouch; sigemptyset(&act.sa_mask); act.sa_flags = 0; sigaction(SIGKILL, &act, 0); sigaction(SIGSEGV, &act, 0); return app(); } It successfully catches sigsegv first time but after it prints 2, it shows me segmentation fault (core dumped) 1 got signal 11 2 zsh: segmentation fault (core dumped) ./a.out tested with clang 12.0.1 and gcc 11.1.0 on ArchLinux Is this operating system specific behavior or is something wrong in my code
The problem is that when you restart the program by calling exit(app()) from inside ouch(), you are still technically inside the signal handler. The signal handler is blocked until you return from it. Since you never return, you therefore cannot catch a second SIGSEGV. If you got a SIGSEGV, then something really bad has happened, and there is no guarantee that you can just "restart" the process by calling app() again. The best solution to handle this is to have another program start your program, and restart it if it crashed. See this ServerFault question for some suggestions of how to handle this.
69,274,713
69,275,363
VS profiler, source information not available
I'm trying to use visual studio performance profiler for the first time and I'm interested in a specific function of mine which is successfully detected by the profiler. However, when I click on it I get "Source information is not available" . How do I fix this? All external functions from libraries are visible. Any function that is in "lab.cpp" won't show. I mean, not even "main" is available. This is the only file I edit, I write all my code in there:
In case someone else has the same problem, I solved it by setting the "Debug Information Format" which was previously empty in my cpp file's(the file containing the functions) General Properties:
69,274,793
69,284,424
C++ type casting / type convention
Can anyone explain what lines 5 & 7 mean? int a; double b = 2.3; a = b; cout << a << endl; a = int(b); // <-- here cout << a << endl; a = (int)b; // <-- here cout << a << endl;
This is called C-style casting and is not recommended to be used in c++ because it can bring to precision loss. What happens here is that the double type is represented in memory as a structure holding the whole part and the floating part. And when you say a = int(someVariableNameWhichIsActuallyDouble) it takes only the whole part of that variable and assigns it to a. So for example if you have b = 2.9; and you want to take only the whole part of the number you can do a c-style cast. But since you wrote C++ type casting for such cases i recommend you to use a = static_cast(b); But be cautious because when doing narrowing casting(casting from a larger type to a narrower type) you need to be causios not to loose precision.
69,275,801
69,276,056
Can't pass lambda that calls member function as C++11 thread ctor argument
I would like to pass a lambda that calls a member function as an argument to the thread constructor but have been unable to. Here's a simple example: #include <thread> class Foo { void run(void func()) { func(); } void bar() { return; } void bof() { std::thread thread(&Foo::run, this, [&]{bar();}); // This fails to compile } }; The above results in the following error: $ g++ --std=c++11 -c funcThreadArg.cpp In file included from /usr/include/c++/4.8.2/thread:39:0, from funcThreadArg.cpp:1: /usr/include/c++/4.8.2/functional: In instantiation of ‘struct std::_Bind_simple<std::_Mem_fn<void (Foo::*)(void (*)())>(Foo*, Foo::bof()::__lambda0)>’: /usr/include/c++/4.8.2/thread:137:47: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (Foo::*)(void (*)()); _Args = {Foo* const, Foo::bof()::__lambda0}]’ funcThreadArg.cpp:14:62: required from here /usr/include/c++/4.8.2/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (Foo::*)(void (*)())>(Foo*, Foo::bof()::__lambda0)>’ typedef typename result_of<_Callable(_Args...)>::type result_type; ^ /usr/include/c++/4.8.2/functional:1727:9: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (Foo::*)(void (*)())>(Foo*, Foo::bof()::__lambda0)>’ _M_invoke(_Index_tuple<_Indices...>) ^ Is what I want to do possible? If so, how?
Use a std::function in Foo::run() class Foo { void run(std::function<void()> func) { func(); } void bar() { return; } void bof() { std::thread thread(&Foo::run, this, [this](){ bar(); }); thread.join(); } };
69,275,851
69,275,899
C++ enum keyword in function parameters
What is the point of using the enum keyword in the function parameter? It seems to do the same thing without it. enum myEnum{ A, B, C }; void x(myEnum e){} void y(enum myEnum e){} Is there a difference between the two?
In this function declaration void x(myEnum e){} the enumeration myEnum shall be already declared and not hidden. In this function declaration void y(enum myEnum e){} there is used the so-called elaborated type name. If in the scope there is declared for example a variable with the name myEnum like int myEnum; then using this function declaration void y(enum myEnum e){} allows to refer to the enumeration with the name myEnum that without the keyword enum would be hidden by the declaration of the variable. Here is a demonstrative program. #include <iostream> enum myEnum{ A, B, C }; void x(myEnum e){} int myEnum; // compiler error //void y(myEnum e){} void y(enum myEnum e){} int main() { // your code goes here return 0; } As it is seen the commented function declaration will not compile if to uncomment it.
69,275,870
69,276,085
Using replace with std::ranges::views
I am trying to learn ranges in C++20 using Microsoft Visual Studio 2019. I created a function to make lowercase in a string and replace all spaces by '_'. template <typename R> auto cpp20_string_to_lowercase_without_spaces( R&& rng ) { auto view = rng | std::ranges::views::transform( ::tolower ) | std::ranges::views::common; std::ranges::replace( view, ' ', '_' ); return view; } And I got the following errors: Error C2672 'operator __surrogate_func': no matching overloaded function found Error C7602 'std::ranges::_Replace_fn::operator ()': the associated constraints are not satisfied I tried to use view.begin(), view.end() I tried to use the std::ranges::copy before call std::ranges::replace. Is it something I am doing wrong? PS: In the project settings, I had to select Preview - Features from the Latest C++ Working Draft (/std:c++latest) because with ISO C++20 Standard (/std:c++20) with the latest version of Visual Studio 2019 preview I can't use views without compilation errors.
transform creates a non-modifiable view. Specifically, it creates a range containing objects that are manufactured as needed. They have no permanent, fixed storage, so they cannot be "replaced" with something else. You can copy the range into a container and then execute your replace operation on the container.
69,275,873
69,276,325
Boost X3: Can a variant member be avoided in disjunctions?
I'd like to parse string | (string, int) and store it in a structure that defaults the int component to some value. The attribute of such a construction in X3 is a variant<string, tuple<string, int>>. I was thinking I could have a struct that takes either a string or a (string, int) to automagically be populated: struct bar { bar (std::string x = "", int y = 0) : baz1 {x}, baz2 {y} {} std::string baz1; int baz2; }; BOOST_FUSION_ADAPT_STRUCT (disj::ast::bar, baz1, baz2) and then simply have: const x3::rule<class bar, ast::bar> bar = "bar"; using x3::int_; using x3::ascii::alnum; auto const bar_def = (+(alnum) | ('(' >> +(alnum) >> ',' >> int_ >> ')')) >> ';'; BOOST_SPIRIT_DEFINE(bar); However this does not work: /usr/include/boost/spirit/home/x3/core/detail/parse_into_container.hpp:139:59: error: static assertion failed: Expecting a single element fusion sequence 139 | static_assert(traits::has_size<Attribute, 1>::value, Setting baz2 to an optional does not help. One way to solve this is to have a variant field or inherit from that type: struct string_int { std::string s; int i; }; struct foo { boost::variant<std::string, string_int> var; }; BOOST_FUSION_ADAPT_STRUCT (disj::ast::string_int, s, i) BOOST_FUSION_ADAPT_STRUCT (disj::ast::foo, var) (For some reason, I have to use boost::variant instead of x3::variant for operator<< to work; also, using std::pair or tuple for string_int does not work, but boost::fusion::deque does.) One can then equip foo somehow to get the string and integer. Question: What is the proper, clean way to do this in X3? Is there a more natural way than this second option and equipping foo with accessors? Live On Coliru
Sadly the wording in the x3 section is exceedingly sparse and allows it (contrast the Qi section). A quick test confirms it: Live On Coliru #include <boost/spirit/home/x3.hpp> namespace x3 = boost::spirit::x3; template <typename Expr> std::string inspect(Expr const& expr) { using A = typename x3::traits::attribute_of<Expr, x3::unused_type>::type; return boost::core::demangle(typeid(A).name()); } int main() { std::cout << inspect(x3::double_ | x3::int_) << "\n"; // variant expected std::cout << inspect(x3::int_ | "bla" >> x3::int_) << "\n"; // variant "understandable" std::cout << inspect(x3::int_ | x3::int_) << "\n"; // variant suprising: } Prints boost::variant<double, int> boost::variant<int, int> boost::variant<int, int> All Hope Is Not Lost In your specific case you could trick the system: auto const bar_def = // (+x3::alnum >> x3::attr(-1) // | '(' >> +x3::alnum >> ',' >> x3::int_ >> ')' // ) >> ';'; Note how we "inject" an int value for the first branch. That satisfies the attribute propagation gods: Live On Coliru #include <boost/spirit/home/x3.hpp> #include <boost/fusion/adapted/struct.hpp> #include <boost/fusion/include/io.hpp> #include <iomanip> namespace x3 = boost::spirit::x3; namespace disj::ast { struct bar { std::string x; int y; }; using boost::fusion::operator<<; } // namespace disj::ast BOOST_FUSION_ADAPT_STRUCT(disj::ast::bar, x, y) namespace disj::parser { const x3::rule<class bar, ast::bar> bar = "bar"; auto const bar_def = // (+x3::alnum >> x3::attr(-1) // | '(' >> +x3::alnum >> ',' >> x3::int_ >> ')' // ) >> ';'; BOOST_SPIRIT_DEFINE(bar) } namespace disj { void run_tests() { for (std::string const input : { "", ";", "bla;", "bla, 42;", "(bla, 42);", }) { ast::bar val; auto f = begin(input), l = end(input); std::cout << "\n" << quoted(input) << " -> "; if (phrase_parse(f, l, parser::bar, x3::space, val)) { std::cout << "Parsed: " << val << "\n"; } else { std::cout << "Failed\n"; } if (f!=l) { std::cout << " -- Remaining " << quoted(std::string_view(f, l)) << "\n"; } } } } int main() { disj::run_tests(); } Prints "" -> Failed ";" -> Failed -- Remaining ";" "bla;" -> Parsed: (bla -1) "bla, 42;" -> Failed -- Remaining "bla, 42;" "(bla, 42);" -> Parsed: (bla 42) ¹ just today
69,276,413
69,304,324
Can I overwrite a const object via placement-new?
Basic.life/8 tells us that we can use the storage occupied by an object to create a new one after its lifetime has ended and use its original name to refer to it unless: the type of the original object is not const-qualified, and, if a class type, does not contain any non-static data member whose type is const-qualified or a reference type, and [...] emphasis mine But, just below that we can see a note saying that: If these conditions are not met, a pointer to the new object can be obtained from a pointer that represents the address of its storage by calling std​::​launder This explains the purposes of std::launder. We can have a class type that has const members and use placement-new to create a new object there with different internal values. What surprises me is the first part of the first quote. It clearly indicates that if the storage is const (not necessarily contains const members, but the whole object is declared as const), we cannot use it to refer to a new object as is, but it may imply that std::launder may fix it. But how would we create such object? The simplest example fails: const auto x = 5; new (&x) auto(10); It's because we cannot use const void* as a buffer for placement-new. We could const_cast it, but casting away a "true" constness is Undefined Behaviour. I believe this is also the case here. I would understand if there simply was a prohibition of using const objects as placement-new buffer, but if that would be the case, what would be the purpose of the emphasised part of the first quote? Can we use reuse a truly const object's storage for a different object?
Apparently all it took was to look just 2 items below the part of the standard I linked to. Basic.life/10 tells us that: Creating a new object within the storage that a const complete object with static, thread, or automatic storage duration occupies, or within the storage that such a const object used to occupy before its lifetime ended, results in undefined behavior. And it comes with an example: struct B { B(); ~B(); }; const B b; void h() { b.~B(); new (const_cast<B*>(&b)) const B; // undefined behavior } which ultimately leads me to a conclusion that it's illegal to use placement-new on a memory occupied by a truly const object. Thus, I believe that the note mentioned in the question (in reference to point 8) is faulty - it should exclude the case in question.
69,276,485
69,276,731
How can I initialize a 2D array with a value different than 0?
I've tried many methods and this one is one of them: void init_table(int _table[][MAX_COLUMNS]) { for (int i = 0; i < MAX_COLUMNS; i++) { for (int j = 0; j < MAX_ROWS; j++) { _table[i][j] = -1; } } } I am just trying to figure out how to initialize my array with -1 rather than 0 it defaults to.
If you need to fill by the same value, use std::fill: std::fill(_table, _table + MAX_ROWS*MAX_COLUMNS, -1); Of course, if you use padding or other advanced techniques, you should take this into account and adjust your code, but this is more advanced topics and should be considered separately.
69,276,614
69,276,805
What is this object get destructed twice?
The socket object's destructor get called twice according to the print statement on destructor. Can anyone explain me why this happens? Log Connection Emplaced Socket Moved From Handle 1 Socket Object destructed and isLive 0 Connection Object destructed Socket Object destructed and isLive 1 Source #include <iostream> #include <future> #include <string> #include <unordered_map> class Socket { public: bool isLive{}; ~Socket() { std::cout << "Socket Object destructed and isLive " << isLive << "\n"; } }; class Connection { public: Socket socket; ~Connection() { std::cout << "Connection Object destructed" << "\n"; } }; std::unordered_map<std::string, Connection> connections; void handle() { auto& connection = connections["A"]; std::cout << "From Handle " << connection.socket.isLive << "\n"; } void worker(Socket&& socket) { const auto& [connection, inserted] = connections.try_emplace("A"); std::cout << "Connection Emplaced" << "\n"; connection->second.socket = std::move(socket); connection->second.socket.isLive = true; std::cout << "Socket Moved" << "\n"; std::async(std::launch::async, handle); } int main() { Socket socket; worker(std::move(socket)); }
In order to store an item in the unordered_map you need to create its copy for the map and try_emplace does it: the element is constructed as value_type. So, you get another copy of the Socket object when you execute: const auto& [connection, inserted] = connections.try_emplace("A"); If you question is more about why std::move doesn't help here, it is more about the state of the object moved from: Unless otherwise specified, all standard library objects that have been moved from are placed in a "valid but unspecified state", meaning the object's class invariants hold (so functions without preconditions, such as the assignment operator, can be safely used on the object after it was moved from). The same goes to your class, which means that the object in main function is still exists and the destructor must be called.
69,276,882
69,277,015
Getting "Exited with return code -11(SIGSEGV)" when attempting to run my code
#include <iostream> #include <vector> #include <string> using namespace std; vector<string> separate(string str){ string build = ""; vector<string> temp; for(int i = 0;i < str.size(); i++){ if(str[i] != ' '){ build += str[i]; } else if(str[i] == ' '){ temp.push_back(build); build = ""; } } return temp; } int main() { int count; string sentence; vector<int> numTimes; getline(cin, sentence); vector<string> words = separate(sentence); for(int i = 0; i < words.size(); i++){ for(int j = 0; j < words.size(); i++){ if(words[i] == words[j]){ count++; } } numTimes.push_back(count); } for(int k = 0; k < words.size(); k++){ cout << words[k] << " - " << numTimes[k] << endl; } return 0; } The code is supposed to receive a string, separate it into the individual words, place those words into a vector and finally output the number of times the word occurs in the sentence. However when running my code, I get a message saying that the program was exited with code -11. I have looked a bit online but do not fully understand what this means or where it is occurring in my code.
@Allan Wind is right, but to offer an alternate solution using the C++17 standard. Iterating Rather than use indexes, let's use a more modern for loop. for (const char &ch : s) Rather than: for (size_t i = 0; i < str.size(); i++) After all, the index is not important in this situation. Dealing with multiple spaces Right now, both the OP's code and Allan's will push an empty string onto the output vector whenever they encounter more than one contiguous space. We can correct that by resetting the string to empty when a space is encountered, but when a space is encountered and the string is empty, don't take any action. We also need to check if the string is non-empty when the loop is finished. If so, we need to push that onto the output vector. We may not get a trailing space to trigger pushing that last word. vector<string> separate(string s) { vector<string> output; string current = ""; for (const char &ch : s) { if (current != "" && ch == ' ') { output.push_back(current); current = ""; } else if (ch == ' ') { // Do nothing! } else { current += ch; } } if (current != "") { output.push_back(current); } return output; } Putting it together so far #include <string> #include <vector> #include <iostream> using namespace std; vector<string> separate(string s); int main() { auto v = separate("hello world foo"); for (auto i : v) { cout << i << endl; } } vector<string> separate(string s) { vector<string> output; string current = ""; for (const char &ch : s) { if (current != "" && ch == ' ') { output.push_back(current); current = ""; } else if (ch == ' ') { // Do nothing! } else { current += ch; } } if (current != "") { output.push_back(current); } return output; } Counting words We can use a map to count the occurrences of words. We use a map<string, int> where each word is the key, and the val is the occurrences. As we iterate over the words, if the word already exists as a key in the map, we increment it by `. If not, we set it to 1. int main() { auto v = separate("hello world hello world foo"); map<string, int> m; for (auto i : v) { if (m[i]) { m[i] += 1; } else { m[i] = 1; } } for (auto const& [key, val] : m) { cout << "The word \"" << key << "\" occurs " << val << " times." << endl; } }
69,276,945
69,277,204
Point raw pointer to a shared_ptr
I started programming in C++ after a 1-year break, and I am having difficulties here and there (not that I really knew it before the break). My current problem is that I don't know how to use pointers properly. I have the following std::vector: std::vector<std::shared_ptr<IHittable>> world; Where IHittable is the interface of Hittable objects. Now, in this std::vector, multiple derivations of IHittable are pushed, like Sphere, Triangle, etc. Each of these derived classes has a function intersects() like this: Intersection Sphere::intersects(const Ray & ray) { auto x = ... ... return {x, this}; } Intersection looks like this: class Intersection { public: Intersection(double t, IHittable * object); [[nodiscard]] double t() const; [[nodiscard]] IHittable * object() const; private: double t_; IHittable * object_ = nullptr; }; I really don't know how to write this code correctly. I need to return a this pointer from the member function intersects() of an object which is itself allocated dynamically and is stored in a std::shared_ptr. Is there a way to handle this? Another example: std::vector<std::shared_ptr<IHittable>> world; world.push_back(std::make_shared<Sphere>()); auto s = Intersection(4.0, world[0]); Should work. PS: I could just create multiple std::vectors without std::shared_ptr: std::vector<Sphere> spheres; std::vector<Triangles> spheres; ... But IMHO, it would be nice to iterate over every object at once. PS2: I am now using shared_from_this() and most of my code works, thanks.
I think this sounds like a good fit for std::enable_shared_from_this as Remy pointed out in the comments. I whipped up a simplified example which hopefully makes it clear how it can be used to achieve what you're after. class Intersection; class IHittable : public std::enable_shared_from_this<IHittable> { public: virtual Intersection intersects( ) = 0; virtual void print( ) const = 0; virtual ~IHittable( ) = default; }; class Intersection { public: Intersection( std::shared_ptr<IHittable> object ) : object_{ std::move( object ) } { } void print_shape( ) const { object_->print( ); } private: std::shared_ptr<IHittable> object_; }; class Square : public IHittable { public: Intersection intersects( ) override { return Intersection{ shared_from_this( ) }; } void print( ) const override { std::cout << "Square\n"; } }; int main( ) { std::vector<std::shared_ptr<IHittable>> objects{ std::make_shared<Square>( ) }; const auto intersect{ objects.front( )->intersects( ) }; intersect.print_shape( ); }
69,276,959
69,277,090
Inconsistent IsObject() property in searching through nested properties in rapidjson document
I'm having an issue where the rapidjson library appears to be inconsistent as to when it reports IsObject() as true. Sometimes when I call value.IsObject() after retrieving a Value from a Document, it correctly reports it as an Object. But sometimes it reports what I think should be an Object as not an Object. A toy program is below. It seems I am unintentionally mutating the document somehow, as the 2nd lookup for vegetables::celery remarkably fails. #define _CRT_SECURE_NO_DEPRECATE #include <rapidjson/document.h> #include <rapidjson/writer.h> #include <rapidjson/stringbuffer.h> #include <string.h> #include <stdio.h> using namespace rapidjson; int getInt(Document& jsonDoc, const char* propertyName) { if (!jsonDoc.IsObject()) { puts("Err: jsonDoc not an object"); return 0; } char* str = strdup(propertyName); char* p = strtok(str, ":"); printf("Looking for property `%s`\n", p); if (!jsonDoc.HasMember(p)) { printf(" - Error: %s not found, property %s\n", p, propertyName); free(str); return 0; } else { printf(" - found property '%s'\n", p); } rapidjson::Value& v = jsonDoc[p]; while (p = strtok(0, ":")) { printf("Looking for property `%s`\n", p); if (v.IsObject()) { puts(" - v is an object so I can look"); } else { printf(" - ERROR: v is NOT an object, I can't search for %s, property %s not found\n", p, propertyName); free(str); return 0; } if (!v.HasMember(p)) { printf(" - Error while digging: %s not found, property %s\n", p, propertyName); free(str); return 0; } else printf(" - found property '%s'\n", p); // otherwise, v = v[p]; // advance deeper into the tree } int val = v.GetInt(); printf(" - json got value %s=%d\n", propertyName, val); free(str); return val; } void test1() { const char* json = R"STR({ "fruits":{ "apples":1, "oranges":553, "bananas":900 }, "vegetables":{ "celery":10000, "cabbage":10000 } })STR"; Document d; d.Parse(json); int apples = getInt(d, "fruits::apples"); int oranges = getInt(d, "fruits::oranges"); int bananas = getInt(d, "fruits::bananas"); int celery = getInt(d, "vegetables::celery"); celery = getInt(d, "vegetables::celery"); int cabbage = getInt(d, "vegetables::cabbage"); } int main() { test1(); return 0; }
Two issues here. First and main: rapidjson::Value& v = jsonDoc[p]; ... v = v[p]; Since v is not a variable, but a reference, you don't set it to a new object, but change the original object it references to, damaging it. Use rapidjson library Pointers if you need to change the object beneath or you can use a trick like here: rapidjson::Value* v = &(jsonDoc[p]); ... v = &(*v)[p]; Second In some returns in if-else you have the memory leak with str, you free it only at the end of the function.
69,277,263
69,277,776
question with while loop condition compare string
I'm trying to get the following code to work. I want it to be so that if the input of the person's name is not an "x", I want it to skip the loop and end. If not, I want it to loop. I thought the condition would be something like the following: void printProfile() { //make a "cookie" or OBJECT HealthProfile user; //get name, age, weight, height info string personName = " "; int yrs; double weight, feetHeight, inchesHeight; //while the input isn't an x, keep going. if x is inputted, skip the while loop while(personName != "x") { //prompt name cout << "Enter name or X to quit: "; getline(cin, personName); //prompt age cout << "Your age: "; cin >> yrs; //prompt weight cout << "Your weight: "; cin >> weight; //prompt height feet cout << "Your height - feet: "; cin >> feetHeight; //prompt height inches cout << "Your height - inches: "; cin >> inchesHeight; user.setName(personName); user.setAge(yrs); user.setWeight(weight); user.setHeight(feetHeight, inchesHeight); cout << "Health Profile for " << user.getName() << endl; cout << fixed << setprecision(1) << "BMI: " << user.getBMI() << endl; cout << "BMI Category: " << user.getCategory() << endl; cout << "Max heart rate: " << user.getMaxHR() << endl; } } but it actually runs the whole loop through one last time on input of "x" and then ends the program. How do I make it so that putting in x exits the program?
Change your loop condition to while(true) After you got the name, add a check: if((personName == "x") break;
69,277,352
69,277,546
How to use Windows LLKeyboard Hook for Combination Keypresses in C++
I have a working Windows hook to detect the simple keypress combinations of both LCTRL + x, and LCTRL + v. The only problem I have is when I press LCTRL, then release, then press x or v, my program thinks they are still being pressed together. Here is my Hook Callback function: HHOOK hookHandle; KBDLLHOOKSTRUCT hookdata; LRESULT __stdcall HookCallback(int code, WPARAM wparam, LPARAM lparam) { if (code >= 0) { if (wparam == WM_KEYDOWN) { hookdata = *((KBDLLHOOKSTRUCT*)lparam); switch(hookdata.vkCode) { case(88): if(GetAsyncKeyState(VK_LCONTROL)) { std::cout<<"CTRL X PRESSED"; } break; case (86): if(GetAsyncKeyState(VK_LCONTROL)) { std::cout<<"CTRL V PRESSED"; } break; } } } return CallNextHookEx(hookHandle, code, wparam, lparam); } Example Input Test 1) Press LCTRL, Press X Test 2) Press LCTRL, Release LCTRL, Press X Expected Output Test 1) CTRL X PRESSED Test 2) No Output Actual Output Test 1) CTRL X PRESSED (WORKING) Test 2) CTRL X PRESSED (NOT WORKING)
You're incorrectly checking GetAsyncKeyState's return value: If the function succeeds, the return value specifies whether the key was pressed since the last call to GetAsyncKeyState, and whether the key is currently up or down. If the most significant bit is set, the key is down, and if the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState. However, you should not rely on this last behavior; for more information, see the Remarks. Change the check to GetAsyncKeyState(...) & 0x8000 to fix that by checking only the highest bit. A small thing: Microsoft made the VK values the same as the ASCII code. Since complete portability is of small concern here, you can use 'X' and 'V' instead of 88 and 86 to better express intent.
69,277,476
69,278,093
Can a std::unique_ptr be reassigned such that its old value is destroyed *before* the new one is constructed?
I'm interested in updating an old personal project to modern C++. I appreciate how RAII simplifies cleanup: instead of making a new object and remembering to delete it before every return point in a function, just make_unique and it will be destroyed appropriately. But I have one nitpick when comparing the generated assembly. Say there's a class method that replaces one of its unique_ptr members with a new value: // std::unique_ptr<int> MyClass::m_foo; void MyClass::refresh_foo(int x) { m_foo = std::make_unique<int>(x * 3 + 5); } This will create a new int, assign it to m_foo, and then delete the old value of m_foo. But that's not quite the same as the old behavior, which could delete the old value, then create a new one and assign it to m_foo: // int *MyClass::m_foo; void MyClass::refresh_foo(int x) { delete m_foo; m_foo = new int(x * 3 + 5); } From the Compiler Explorer, gcc, clang, and MSVC all generate less code for the old way than the new one. I understand why this is the case, since that's the order in which all expressions are evaluated; p = q; has to construct q first. And of course m_foo had an invalid value in between the delete and new lines. But is there a way I'm missing to have unique_ptr destroy its old value and then create a new one in one expression? A "replace_unique"? Seems like it would be helpful when dealing with large objects so two of them don't needlessly coexist. Edit: To be clear, I'm just using int as a trivial example here. My actual use cases are with classes of my own or from a library. And m_foo.reset(new int(x * 3 + 5)); naturally has the same problem compared to the old way of doing things, since it too has to construct the new int before assigning it and deleting the previous one.
You can use unique_ptr::reset() to deterministically destroy the currently held object when you want. Update the unique_ptr with a nullptr pointer before then updating it with a new object pointer, eg: // std::unique_ptr<int> MyClass::m_foo; void MyClass::refresh_foo(int x) { m_foo.reset(); // <- int is destroyed here m_foo = std::make_unique<int>(x * 3 + 5); }
69,277,564
69,318,918
Add distance field : [x,y,z,distance] from VLP-16 using ROS or velodyne driver
Velodyne lidars publish PointCloud2 messages with the fields containing : x, type : float32 y, type : float32 z, type : float32 intensity, type : float32 ring, type : uint16 time, type : float32 However, I need to add distance field(output points with distance) because I needed this field as a research purpose. Is it possible to write a node or adapt the velodyne driver to output points with that field? If so, could you possibly tell me how to achieve that? Any help is much appreciated. Thanks:)
The best solution is not to change the velodyne driver, but since you're using ros, to leverage all the ecosystem tools built in. For example, the velodyne publishes a sensor_msgs/PointCloud2 topic. Then internally, using C++, ROS treats any PointCloud2 msg into any PCL pointcloud type. If you're doing serious processing of pointclouds, don't re-invent the wheel (but worse), try solving the problem with tools from PCL. Use it's pre-built filters (ex ground plane filter) and prebuilt segmentation tools (ex could Euclidean Cluster Extraction solve your problem?). Additionally, some of these PCL tools are pre-wrapped in ros, to use from the launch file if you want! Otherwise you could use PCL to add a distance parameter, by choosing the pointcloud type in ros as of type pcl::PointWithRange or pcl::PointWithViewpoint. I don't think it'll autocompute that variable, but you can iterate through the points and compute it yourself, and the memory for it will already be allocated and localized.
69,277,649
69,277,675
Does passing an std::optional<T> by reference actually save copying?
I know that std::optional<T&> isn't supported in the standard. This question is about whether passing std::optional<T>& has any performance advantage Sample code (https://godbolt.org/z/h56Pj6d6z) reproduced here #include <ctime> #include <iomanip> #include <iostream> #include <optional> void DoStuff(std::optional<std::string> str) { if (str) std::cout << "cop: " << *str << std::endl; } void DoStuffRef(const std::optional<std::string>& str) { if (str) std::cout << "ref: " << *str << std::endl; } int main() { std::optional<std::string> str = {}; DoStuff(str); DoStuffRef(str); str = "0123456789012345678901234567890123456789"; DoStuff(str); DoStuffRef(str); } (My actual use case is an optional for a complex user-defined type, but I hope that a long string would do the same compiler-wise) In this case, does DoStuffRef actually save any copying effort compared to DoStuff? I tried to look at godbolt output but I don't know enough assembly to be sure. I do see that in the case of DoStuff, there seems to be a temp std::optional<T> created which is not present in DoStuffRef so my suspicion is that yes, passing an optional by reference save some copying Appreciate the help!
If you pass actual std::optional<std::string> then yes, there would be no copy. But if you pass just std::string then temporary optional has to be constructed first, resulting in a copy of the string.
69,277,652
69,304,334
Whenever I try to update my code in C++(VSCode) with the g++ thing, it doesn't update what I put even after deleting the old .exe file
my code looks like ^^^ (comments because i make a file for notes on a new programming language im learning to look back at to help me) I will put g++ filename.cpp and then ./a.exe after making a change and it doesn't change the output in the terminal. So for example if I put a :) at the end of the last string, it wouldn't update what it puts in the terminal even after doing g++ filename.cpp. I've tried deleting the older a.exe file before doing g++ but it doesn't fix the problem.
Please make sure you are actually using the GCC Compiler and that you are not getting errors at the moment of compile your code. You can use this to check the compiler: g++ --version; if you don't have the compiler installed, it will give you an error. Also, at the moment of compile your code, you should use the g++ installed on your computer with the .cpp file that you want to compile and create the .exe file. Example: Here we have Basic00.cpp having a simple "hello world": Then, we run g++ .\Basic00.cpp It will create the a.exe file: Now you just need to run .\a.exe: And, if you want to add ":)" at the end of the string, you just need to add it, compile the code again (step 2) and run the exe file (step 4): I recommend that you read this about how to use VS Code with G++ to compile and run your code without having issues. Very important: Remember that you need to compile your code every time that you make a change. Edit with the new Image: I checked your image and the tab is showing a white circle, it means that you are not saving the changes, press Ctrl+S (to save) or configure Auto Save on File -> Auto Save, after saving compile your code again and run the .exe file.
69,278,066
69,279,263
Unable to use gmsh from Visual Studio C++
I downloaded the sdk and ran the Windows related commands described here. Then I created a new VC++ project and copied the contents of a tutorial file included with that sdk (t1.cpp). There were compile time errors, which I fixed by including the path to gmsh.h in the include settings found in projcet->Properties->Configuration Properties->C/C++->General->Additional Include Directories. I also included path to the gmsh.lib file at projcet->Properties->Configuration Properties->Linker->General->Additional Libraries Directories. Still I am getting the below error while trying to build the project: LNK2019: unresolved external symbol gmshFree referenced in function "int __cdecl gmsh::model::geo::addCurveLoop(class std::vector<int,class std::allocator<int> > const &,int,bool)" (?addCurveLoop@geo@model@gmsh@@YAHAEBV?$vector@HV?$allocator@H@std@@@std@@H_N@Z) Please say what I am missing here. I am running Microsoft Visual Studio Community 2019 (Version 16.10.4) on Windows 10.
Did you add #include "gmsh.h " and add gmsh.lib in Configuration Properties > Linker > Input? For more information, you could refer to the document: Create a client app that uses the DLL.
69,278,186
69,293,190
Opengl shader bitwise operation not working in Windows
I use an integer to use as a "filter" and pass it to a geometric shader and use a bitwise operation to get the bit values. It works in macOS, but not in Windows. To show my point, I used and modified the tutorial code in the geometric shader part in the learnopengl.com found at https://learnopengl.com/Advanced-OpenGL/Geometry-Shader Based on the tutorial code, I added the following code in the main.cpp. (I added enabledFaces[] and VFO, and passed them to the shaders.) I only set one bit to each enabledFaces[] integer for simplicity. int enabledFaces[] = { 1 << 0, 1 << 1, 1 << 2, 1 << 3 }; unsigned int VBO, VAO, VFO; glGenBuffers(1, &VBO); glGenBuffers(1, &VFO); glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(points), &points, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), 0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(2 * sizeof(float))); glBindVertexArray(VFO); glBindBuffer(GL_ARRAY_BUFFER, VFO); glBufferData(GL_ARRAY_BUFFER, sizeof(enabledFaces), &enabledFaces, GL_STATIC_DRAW); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 1, GL_INT, GL_FALSE, sizeof(int), 0); glBindVertexArray(0); In the vertex shader as a pass-through: #version 330 core layout (location = 0) in vec2 aPos; layout (location = 1) in vec3 aColor; layout (location = 2) in int vEnabledFaces; out int gEnabledFaces; out VS_OUT { vec3 color; } vs_out; void main() { vs_out.color = aColor; gl_Position = vec4(aPos.x, aPos.y, 0.0, 1.0); gEnabledFaces = vEnabledFaces; } And the geometric shader (added the if statement with the gEnabledFaces): ##version 330 core layout (points) in; layout (triangle_strip, max_vertices = 5) out; in int gEnabledFaces[]; in VS_OUT { vec3 color; } gs_in[]; out vec3 fColor; void build_house(vec4 position) { fColor = gs_in[0].color; // gs_in[0] since there's only one input vertex gl_Position = position + vec4(-0.2, -0.2, 0.0, 0.0); // 1:bottom-left EmitVertex(); gl_Position = position + vec4( 0.2, -0.2, 0.0, 0.0); // 2:bottom-right EmitVertex(); gl_Position = position + vec4(-0.2, 0.2, 0.0, 0.0); // 3:top-left EmitVertex(); gl_Position = position + vec4( 0.2, 0.2, 0.0, 0.0); // 4:top-right EmitVertex(); gl_Position = position + vec4( 0.0, 0.4, 0.0, 0.0); // 5:top fColor = vec3(1.0, 1.0, 1.0); EmitVertex(); EndPrimitive(); } void main() { if ( (gEnabledFaces[0] & 0x01) != 0 || (gEnabledFaces[0] & 0x04) != 0) build_house(gl_in[0].gl_Position); } No change in the fragment shader: #version 330 core out vec4 FragColor; in vec3 fColor; void main() { FragColor = vec4(fColor, 1.0); } Due to the if statement in the main() in the geometric shader, two houses (the first and the third polygons) out of the 4 polygons should be displayed. It works correctly on Mac, but nothing is displayed in Windows. If I remove the if statement in Windows, all polygons display correctly. Would someone please explain why this does not work in Windows and how to fix it? Thank you.
As suggested by G.M., the use of glVertexAttribIPointer solves the problem. But I use Qt and unfortunately, it seems that glVertexAttribIPointer is not available. So I changed the glVertexAttribPointer to float type instead of an integer type. So, Changing from glVertexAttribPointer(2, 1, GL_INT, GL_FALSE, sizeof(int), 0); to glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, sizeof(float), 0); Then it works in Windows, in spite of the fact that the passing variables (in the C++ and also in shaders) are all integer type. Strange but it works.
69,278,755
69,292,749
Linear index for a diagonal run of an upper triangular matrix
Given a NxN matrix, I would like to linearly index into its upper right triangle, following a diagonal by diagonal pattern, starting after the main diagonal. For example, given a 4x4 matrix X 0 3 5 X X 1 4 X X X 2 X X X X I'm looking for a non recursive (closed form) function mapping linear indices from 0 to 5 to (x,y) achieving f(0) = (0, 1) f(1) = (1, 2) f(2) = (2, 3) f(3) = (0, 2) f(4) = (1, 3) f(5) = (0, 3) Related for row by row runs: Linear index upper triangular matrix algorithm for index numbers of triangular matrix coefficients
Thanks to @loopy-walt's observation, we have an answer! Using the result from Linear index upper triangular matrix, a transformation of the result (i, j) |-> (j-i-1, j) Gives the expected outcome. Here is a C++ implementation. #include<tuple> #include<cmath> // Linear indexing of the upper triangle, row by row std::tuple<size_t, size_t> k2ij(size_t n, size_t k){ size_t i = n - 2 - (size_t)std::floor(std::sqrt(4*n*(n-1) - (8*k) -7)/2.0 - 0.5); size_t j = k + i + 1 - n*(n-1)/2 + (n-i)*((n-i)-1)/2; return {i,j}; } // Linear indexing of the upper triangle, diagonal by diagonal std::tuple<size_t, size_t> d2ij(size_t n, size_t d){ const auto [i, j] = k2ij(n, d); return {j-i-1, j}; // Conversion from row by row to diag by diag } #include<iostream> #include<set> int main(int argc, char** argv) { size_t n = 4; size_t top = n*(n-1)/2; for(size_t d=0; d<top; ++d){ const auto [i,j] = d2ij(n, d); std::cout << "d2ij(" << n << ", " << d << ") = (" << i << ", " << j << ")" << std::endl; } return 0; } Producing d2ij(4, 0) = (0, 1) d2ij(4, 1) = (1, 2) d2ij(4, 2) = (2, 3) d2ij(4, 3) = (0, 2) d2ij(4, 4) = (1, 3) d2ij(4, 5) = (0, 3) Note: if someone wishes the form f(d) instead, a lambda can be used to capture the dimension 'n' auto f = [n](size_t d){return d2ij(n, d);}; const auto [i,j] = f(5); Thanks to everybody that took the time to read and help!
69,278,926
69,280,221
Is there some STL "container" for one element on the heap?
My question: Classes that contain only STL containers can use the Rule of Zero, and so avoid having to manually write the destructor/copies, etc. I'm wondering if there's an STL tool (with the above property) designed for the simplest case: one element (on the heap)? To explain when we'd want this: Okay this problem is more niche/hypothetical: We've got an object Foo with lots of members (n members). Foo gets move-copied a lot, so much that it's worthwhile storing its data as a single heap object (so instead of n shallow copies it can do just 1). It's also sometimes deep copied. We can solve this by using vector with one element: class Foo { struct Data { char gender; int age; std::string name; // lots of data }; std::vector<Data> data; public: Foo () : data(1) {} void Input (char c, int x, const std::string & str) { auto & d = data[0]; d.gender = c; d.age = x; d.name = str; } void Print () const { auto & d = data[0]; std::cout << d.gender << std::endl << d.age << std::endl << d.name << std::endl; } }; demo To avoid the constructor and all those [0]s we could wrap the vector into its own class, but this feels like a hack - vector is over-kill for this and could hold extra memory (size and capacity if the compiler doesn't optimise-out). Note that unique_ptr and shared_ptr have different copy profiles to this, so aren't helpful here (example). Also, this problem is similar to but not quite the same as pimpl, because here we have a type that's defined (with pimpl we can't even use the above vector technique).
You are possibly looking for what is called deep/clone/copy/value pointer (basically a unique pointer with deep copy capabilities). There was even a proposal, don't know its actual status: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3339.pdf. AFAIK, it has not been accepted up to now. Maybe, some external library provides it (Boost?). Relevant question: Is there a scoped ptr that has deep copy functionality built in? In its accepted answer, there is a link to some library, which should provide the required functionality. It doesn't seem to be any more maintained, but maybe it is still usable. You can google for some more solutions. For instance, you can copy-paste (and possibly review) this implementation: https://vorbrodt.blog/2021/04/05/stddeep_ptr/. I believe you can find some solutions on Code Reivew site as well, such as: DeepPtr: a deep-copying unique_ptr wrapper in C++. I think it's a good idea to employ std::unique_ptr and just wrap it with the deep-copy functionality.
69,280,674
69,285,751
co_await custom awaiter in boost asio coroutine
I am currently trying to use the new C++20 coroutines with boost::asio. However I am struggling to find out how to implement custom awaitable functions (like eg boost::asio::read_async). The problem I am trying to solve is the following: I have a connection object where I can make multiple requests and register a callback for the response. The responses are not guaranteed to arrive in the order they have been requested. I tried wrapping the callback with a custom awaitable however I am unable to co_await this in the coroutine since there is no await_transform for my awaitable type in boost::asio::awaitable. The code I tried to wrap the callback into an awaitable is adapted from here: https://books.google.de/books?id=tJIREAAAQBAJ&pg=PA457 auto async_request(const request& r) { struct awaitable { client* cli; request req; response resp{}; bool await_ready() { return false; } void await_suspend(std::coroutine_handle<> h) { cli->send(req, [this, h](const response& r) { resp = r; h.resume(); }); } auto await_resume() { return resp; } }; return awaitable{this, r}; } which I tried calling in a boost coroutine like this: boost::asio::awaitable<void> network::sts::client::connect() { //... auto res = co_await async_request(make_sts_connect()); //... } giving me the following error: error C2664: 'boost::asio::detail::awaitable_frame_base<Executor>::await_transform::result boost::asio::detail::awaitable_frame_base<Executor>::await_transform(boost::asio::this_coro::executor_t) noexcept': cannot convert argument 1 from 'network::sts::client::async_request::awaitable' to 'boost::asio::this_coro::executor_t' Is there any way to achieve this functionality ?
I actually managed to find a solution to this. The way to do this is by using boost::asio::async_initiate to construct a continuation handler and just defaulting the handler to boost::use_awaitable. As an added bonus this way it is trivial to match it to the other async function by simply using a template argument for the handler. template<typename ResponseHandler = boost::asio::use_awaitable_t<>> auto post(const request& req, ResponseHandler&& handler = {}) { auto initiate = [this]<typename Handler>(Handler&& self, request req) mutable { send(req, [self = std::make_shared<Handler>(std::forward<Handler>(self))](const response& r) { (*self)(r); }); }; return boost::asio::async_initiate< ResponseHandler, void(const response&)>( initiate, handler, req ); } The only problem here is that std::function does not move construct apparently so I had to wrap the handler in a std::shared_ptr.
69,281,119
69,281,391
Remove icons on buttons in QMessageBox
There is an output message with three buttons: QMessageBox messageBox(QMessageBox::Question, tr(""), tr(""), QMessageBox::No | QMessageBox::Yes | QMessageBox::Cancel, this); messageBox.setButtonText(QMessageBox::No, tr("1")); messageBox.setButtonText(QMessageBox::Yes, tr("2")); messageBox.setButtonText(QMessageBox::Cancel, tr("Cancel")); auto response = messageBox.exec(); Could you tell me please how to remove the standard icons that are highlighted in the red square?
Could you try: QMessageBox messageBox(this); messageBox.addButton(tr("1"), QMessageBox::NoRole); messageBox.addButton(tr("2"), QMessageBox::YesRole); messageBox.addButton(tr("Cancel"), QMessageBox::RejectRole); auto response = messageBox.exec();
69,281,372
69,293,941
Using SWIG to Wrap C++ Function With Default Values
I have the following C++ function in say.hpp: #include <iostream> void say(const char* text, const uint32_t x = 16, const uint32_t y = 24, const int32_t z = -1) { std::cout << text << std::endl; } Here is my say.i: %module say %{ #include "say.hpp" %} %include "say.hpp" Then, I built the shared library: $ swig -python -c++ -I/usr/include say.i $ g++ -fPIC -c say_wrap.cxx -I/opt/rh/rh-python38/root/usr/include/python3.8 $ g++ -shared say_wrap.o -o _say.so Then, I tried to call it: >>> import say >>> say.say("hello") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/hc/test/cpp/say.py", line 66, in say return _say.say(text, x, y, z) TypeError: Wrong number or type of arguments for overloaded function 'say'. Possible C/C++ prototypes are: say(char const *,uint32_t const,uint32_t const,int32_t const) say(char const *,uint32_t const,uint32_t const) say(char const *,uint32_t const) say(char const *) >>> It seems something is wrong with having default values for the function parameters as once I remove them, it works. Any idea?
Use the following say.i file. SWIG has prewritten code for the standard integer types and needs it included to understand them. Without them, the wrapper receives the default values as opaque Python objects and doesn't know how to convert them to the correct C++ integer types. %module say %{ #include "say.hpp" %} %include <stdint.i> %include "say.hpp" Result: >>> import say >>> say.say('hello') hello >>> say.say('hello',1,2,3) hello Note you could also supply the typedefs directly, but better to use stdint.i: %module say %{ #include "say.hpp" %} typedef unsigned int uint32_t; typedef int int32_t; %include "say.hpp"
69,281,595
69,281,652
PPP Stroustrup exercise - copy a C-style string into memory it allocates on the free store
I'm solving the following exercise (17.4) from Stroustrup's PPP book: Write a function char* strdup(const char* ) that copies a C-style string into memory it allocates on the free store. Don't use any standard library function. Here's my implementation, which compiles just fine. I have a question about an error message that I found when I run the function. #include <iostream> #include <string> char* strdup(const char* s) { if (s==0) return 0; // get number of char in s int n = 0; while (s[n] != 0) ++n; // allocate memory with room for terminating 0 char* pc = new char[n+1]; // copy string for (int i = 0; s[i]; ++i) pc[i] = s[i]; pc[n] = 0; // zero at the end: it's a C-style string delete[] s; return pc; } int main() try { std::string str; char* cstr; while (std::cin>>str && str!="quit") { cstr = strdup(&str[0]); std::cout << cstr << "\n"; delete[] cstr; } } catch (std::exception& e) { std::cerr << "exception: " << e.what() << std::endl; } catch (...) { std::cerr << "exception\n"; } It compiles, but when I run it and I write the first character, I have a pointer being freed was not allocatederror. If I remove delete[] s, then I have no memory leak and it runs just fine. But why is (apparently) correct to do not delete[]the s? Is it because it has not been allocated with new?
A std::string does manage the memory it uses to store the string. In main you do std::string str; and cstr = strdup(&str[0]); but your strdup calls delete[] s; on the parameter. This is what you already know. Now consider that the destructor of std::string does already clean up the memory when it goes out of scope. The buffer used by the std::string cannot be deleted twice. You shall not call delete on &str[0]. You only need to delete objects that you created via new. Also there is small string optimization. In this case &str[0] does not point to a heap allocated buffer which you could delete. PS: You are using 0 when you should rather use nullptr for pointers and '\0' for the null terminator.
69,281,840
69,282,120
Delete and remove a pointer from a list
I have this code (its a smol version of the code that replicates the error) and it gives a some kind of error with memory. idk just pls help me fix it. It deletes the object so there remains just the nullptr. Idk why but it doesn't want to remove the pointer from the list. #include <iostream> #include <list> // casual include here i create a class thats the base for all of my other classes class Object // a virtual class { public: bool needs_delete = false; virtual void tick() {} virtual void render() {} }; a player class that inherits from the Object class i created earlier class Player : public Object { public: float x, y; // <-- just look at da code dont read dis Player(float x, float y) : // i initialize the "x" & "y" with the x & y the user has set in the constructor x(x), y(y) {} void tick() override // just look at the code { x++; if (x > 10000) { needs_delete = true; } } void render() override // just look at the code { // nothing... } }; just the main function. at this point im just writing text because stackoverflow wont let me post this piece of constant depression. pls help :) int main() { std::list<Object*>* myObjs = new std::list<Object*>; // a list that will contain the objects for (int i = 0; i < 1000; i++) // i create 1k player just for testing { myObjs->push_back(new Player(i, 0)); } while (true) { if (myObjs->size() == 0) // if there are no objects i just break out of the loop break; for (Object* obj : *myObjs) // update the objects { obj->tick(); obj->render(); // some other stuff } // DA PART I HAVE NO IDEA HOW TO DO // pls help cuz i suck for (Object* obj : *myObjs) // help pls :) { // baisicly here i want to delete the object and remove it from the list if (obj->needs_delete) { std::cout << "deleted object\n"; delete obj; myObjs->remove(obj); } } } }
What about: myObjs->remove_if([](auto& pObj) { if ( pObj->needs_delete ) { delete pObj; return true; } else return false; });
69,281,998
69,282,277
Vector of Base unique_ptr causes object slicing on emplace_back(new T())
I'm trying to pass a type as a argument to a method that will properly construct and push a object to a vector of unique_ptr, however the created object is always the Base object. This happens when using emplace_back(), the same works fine if I just instantiate the object. Constructing the object outside the vector works fine, however I'm not sure how to move the pointer to the vector after. body_parts.hpp #include <vector> #include <string> #include <fmt/core.h> using namespace std; namespace uhcr { class body_part { public: string name = "Generic"; template <class T> void add_body_part() { this->body_parts.emplace_back<T*>(new T()); fmt::print("{}\n", this->body_parts.back()->name); } private: vector<unique_ptr<body_part>> body_parts; }; class torso : public body_part { public: string name = "Torso"; }; } character.hpp #include <string> #include "components/body_parts.hpp" using namespace std; namespace uhcr { class character : public body_part { public: string name = "Character"; }; } main.cpp #define FMT_HEADER_ONLY #include <memory> #include <fmt/core.h> #include "src/character.hpp" using namespace fmt; using namespace uhcr; void create_human() { character human; human.add_body_part<torso>(); } int main(void) { create_human(); return 1; } The error is at add_body_part(), when running this code it prints "Generic".
You have multiple data members named name in your subclasses. You probably want to assign values to the member in body_part, not declare new members that shadow it. class body_part { public: body_part() = default; string name = "Generic"; template <class T> void add_body_part() { this->body_parts.emplace_back<T*>(new T()); fmt::print("{}\n", this->body_parts.back()->name); } protected: body_part(std::string name) : name(name) {} private: vector<unique_ptr<body_part>> body_parts; }; class torso : public body_part { public: torso() : body_part("Torso") {} }; class character : public body_part { public: character() : body_part("Character") {} };
69,282,015
69,282,087
Declaring a class template member that belongs to all specializations
What I'm looking for is a way to say: This is the same for all specializations: template <typename T> struct Foo { using id_type = unsigned int; // this does not depend on T! }; Foo::id_type theId; // Doesn't matter what the specialization is, id_type is always the same. I want to access id_type without having to specify the specialization...
You can't have exactly what you are asking for. Foo is not a class. Foo<T> is a class, for any T. You could have a non-template base that holds id_type struct FooBase { using id_type = unsigned int; }; template <typename T> struct Foo : FooBase{}; FooBase::id_type theId; You could provide a default parameter for T template <typename T = struct FooPlaceholder> struct Foo { using id_type = unsigned int; // this does not depend on T! }; Foo<>::id_type theId; However nothing stops me from writing an explicit specialisation of Foo that lacks (or redefines) id_type. template <> struct Foo<MyType> { }; template <> struct Foo<MyOtherType> { int id_type = 42; };
69,282,407
71,219,124
Linking to TBB libraries with CMake
I have tbb downloaded and placed in my repository directory: > tree deps/tbb/ -d deps/tbb/ ├── bin ├── cmake │   └── templates ├── include │   ├── serial │   │   └── tbb │   └── tbb │   ├── compat │   ├── internal │   └── machine └── lib    ├── ia32    │   └── gcc4.8    └── intel64    └── gcc4.8 In my CMakeLists.txt I have tried this: include_directories("deps/tbb/include") find_library(TBB_LIB NAMES tbbbind_debug tbbbind tbb_debug tbbmalloc_debug tbbmalloc_proxy_debug tbbmalloc_proxy tbbmalloc tbb_preview_debug tbb_preview tbb HINTS "${CMAKE_PREFIX_PATH}/deps/tbb/lib/intel64/gcc4.8" ) add_executable(${PROJECT_NAME} src/main.cpp ) target_link_libraries(${PROJECT_NAME} PUBLIC ${TBB_LIB}) But building with cmake, linker throws this error: /usr/lib64/gcc/x86_64-suse-linux/7/../../../../x86_64-suse-linux/bin/ld: cannot find -lTBB_LIB-NOTFOUND collect2: error: ld returned 1 exit status I couldn't figure out what is missing. Thanks. Update This commit resolves the previous error: - HINTS "${CMAKE_PREFIX_PATH}/deps/tbb/lib/intel64/gcc4.8" + HINTS "deps/tbb/lib/intel64/gcc4.8" But, new errors are thrown: undefined reference to `tbb::interface7::internal::task_arena_base::internal_current_slot()' Update Other than find_library, what CMake tools are available to link to TBB shared libraries? I have tried some CMake tools, but I cannot figure out how to link to TBB *.so files correctly!
Inspired by @AlexReinking answer, here is the final implementation: project(my-cpp-service VERSION 0.1.0) # Equivalent to command-line option of `-DCMAKE_PREFIX_PATH=...` list(APPEND CMAKE_MODULE_PATH "deps/tbb/cmake/") find_package(TBB REQUIRED) add_executable(${PROJECT_NAME} src/main.cpp ) target_link_libraries(${PROJECT_NAME} PUBLIC TBB::tbb )
69,282,654
69,282,705
What is the correct way of freeing std::thread* heap allocated memory?
I'm declaring a pointer to a thread in my class. class A{ std::thread* m_pThread; bool StartThread(); UINT DisableThread(); } Here is how I call a function using a thread. bool A::StartThread() { bool mThreadSuccess = false; { try { m_pThread= new std::thread(&A::DisableThread, this); mThreadSuccess = true; } catch (...) { m_pDisable = false; } if(m_pThread) { m_pThread= nullptr; } } return mThreadSuccess; } Here is the function called by my thread spawned. UINT A::DisableThread() { //print something here. return 0; } If I call this StartThread() function 10 times. Will it have a memory leak? for (i = 0; i<10; i++){ bool sResult = StartThread(); if (sResult) { m_pAcceptStarted = true; } }
What is the correct way of freeing m_pThread= new std::thread(&A::DisableThread, this); The correct way to free a non-array object created using allocating new is to use delete. Avoid bare owning pointers and avoid unnecessary dynamic allocation. The example doesn't demonstrate any need for dynamic storage, and ideally you should use a std::thread member instead of a pointer. If I call this StartThread() function 10 times. Will it have a memory leak? Even a single call will result in a memory leak. The leak happens when you throw away the pointer value here: m_pThread= nullptr; could you add your better solution Here's one: auto future = std::async(std::launch::async, &A::DisableThread, this); // do something while the other task executes in another thread do_something(); // wait for the thread to finish and get the value returned by A::DisableThread return future.get()
69,282,858
69,282,948
Friend function cannot access private members
When reading C++ Primer I encountered the following snippet (I've omitted code that I think is irrelevant): class Message { friend class Folder; public: // ... private: std::string contents; std::set<Folder*> folders; // ... }; // ... void swap(Message& lhs, Message& rhs) { using std::swap; for (auto f : lhs.folders) { f->remMsg(&lhs); } // class Folder is undefined by book // ... } // ... C++ Primer gives a task to implement class Folder. So I add more code:: class Folder; // my code class Message { friend void swap(Message&, Message&); // my code friend class Folder; public: // ... private: std::string contents; std::set<Folder*> folders; // ... }; void swap(Message&, Message&); // my code // I added the whole class class Folder { friend void swap(Folder&, Folder&); friend class Message; public: // ... private: // ... void addMsg(Message* m) { msgs.insert(m); } void remMsg(Message* m) { msgs.erase(m); } }; void swap(Folder&, Folder&); // my code In file.cpp void swap(Message& lhs, Message& rhs) { using std::swap; for (auto f : lhs.folders) { f->remMsg(&lhs); } // In vs2019 // Error (active) E0265 function "Folder::remMsg" is inaccessible // ... } As you can see, I can't use the method Folder::remMsg(). Then I try to figure out how friend function works. struct B; // This is [line 1] struct A { friend void swap(A&, A&); private: int n; std::vector<B*> Bs; }; void swap(A& lhs, A& rhs) { for (auto f : lhs.Bs) { f->n; } // f->n is still inaccessible // If I delete line 1, the code can be compiled successfully // same with class Folder // ... } struct B { friend struct A; private: int n; A C; }; I don't understand why does this happen. (I declare class Message and class Folder friend class with each other because I want symmetric swap to use copy-swap)
void swap(Message& lhs, Message& rhs) is a friend of Message, but you try to access private members of Folder. Your last code has the same issue: friend void swap(A&, A&); is a friend of A but you try to access private members of B. friend is not transitive. Just because A is friend of B and swap is a friend of A does not mean swap is a friend of B. If you want void swap(A&,A&) grant access to private member of B then make it a friend of B: #include <vector> struct B; struct A { friend void swap(A&, A&); private: int n; std::vector<B*> Bs; }; struct B { friend void swap(A&,A&); private: int n; A C; }; void swap(A& lhs, A& rhs) { for (auto f : lhs.Bs) { f->n; } // ^^ access private member of A //^^ access private member of B }
69,282,861
69,282,985
vector's emplace_back - vector as a constructor argument
I have the following structs: struct A{}; struct B { B(std::shared_ptr<A> a, int x): a_(a), x_(x){} std::shared_ptr<A> a_; int x_; }; struct C { C(std::vector<B> v, bool c){} }; I would like to insert an object of type C to the vector but the following code doesn't work: std::vector<C> vecC; vecC.emplace_back({std::make_shared<A>(), 2}, false); Alternatively this way doesn't make sense with emplace_back: vecC.emplace_back(B{std::make_shared<A>(), 2}, false); How should I insert an object of type C to the vector ?
You forgot another pair of braces for the std::vector. Also, you need to tell emplace_back() what kind of arguments you pass it, so you need to invoke std::vector's constructor: vecC.emplace_back(std::vector{ B{ std::make_shared<A>(), 2 } }, false); Alternatively, don't use emplace_back() and use push_back() instead: vecC.push_back({{{std::make_shared<A>(), 2}}, false});
69,283,061
69,283,563
Considering that std::cout is an initialized object, why does visual studio 'not recognise its identifier' whilst setting a Watch in the debugger?
Considering that std::cout is an initialized object, why does visual studio 'not recognise its identifier' whilst setting a Watch in the debugger? How do I view this object in memory? Setting both std::cout and cout as watch variables returns: [identifier "std::cout" is undefined] [identifier "cout" is undefined] respectively. #include <iostream> int main() { std::cout << "Usage of std::cout\n"; // breakpoint return 0; } According to https://en.cppreference.com/w/cpp/io/cout on the topic of cout: These objects are guaranteed to be initialized during or before the first time an object of type std::ios_base::Init is constructed and are available for use in the constructors and destructors of static objects with ordered initialization (as long as <iostream> is included before the object is defined).
you could create a local reference to std::cout and add a watch for that. E.g.: auto& mycout = std::cout;
69,283,525
69,284,207
what does the colon in asm volatile() mean
i'm not sure if i accidently modified the code a bit, but here it is (i'm a beginner to inline assembly, but quite used to assembly in a different file):- void out8(uint16 port, uint8 data) {asm volatile("outb %0, %1" : "dN"(port) : "a"(data));} void out16(uint16 port, uint16 data) {asm volatile("outw %0, %1" : "dN"(port) : "a"(data));} void out32(uint16 port, uint32 data) {asm volatile("outl %%eax, %%dx" : "dN"(port) : "a"(data));} previously it gave no error but now it is. but can anyone correct this code? and also, tell me on what basis is the colon separating the values, the "dN" and the "a" in the colon separated areas, the "%0" and "%1" in the inline assembly, why are those variables "port" and "data" in brackets next to the "a" and "dN" and what is the difference between "%[reg]" and "%%[reg]" so that i can solve problems like these later when i get them. (tl;du (u stands for understand) the manual page for inline extended assembly is japanese (you know what i mean, right?)) [SOLVED] used :- void out(uint16 port, uint8 data) {asm volatile("outb %1, %0" :: "dN"(port), "a"(data));} void out(uint16 port, uint16 data) {asm volatile("outw %1, %0" : : "dN"(port), "a"(data));} // Warning, this one's still unsafe, even though it compiles void out(uint16 port, uint32 data) {asm volatile("outl %%eax, %%dx" : : "dN"(port), "a"(data));} (Warning to future readers: outl still has a bug, see the answer(s).)
Read the manual for the syntax, obviously. https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html. asm asm-qualifiers ( AssemblerTemplate : OutputOperands [ : InputOperands [ : Clobbers ] ]) See also https://stackoverflow.com/questions/tagged/inline-assembly for links to guides other than the official docs. You have "dN"(port) in the outputs section, but it's actually an input (no = or +). And yes, the I/O port number should be an input: it's something the asm statement needs to get from the surrounding code of your program, not something the asm statement is providing back to your program. So the compiler needs to know how to provide it to the asm statement, not collect it. If you're confused by the fact that out has two "inputs", think of it like a store instruction. Two pieces of data come from the CPU (the data and the address), resulting in a store to memory. Unlike a load or in where the load instruction writes a register, and the compiler needs to know where that result is placed. You also have the %0, %1 operands in the wrong order for the order of the constraints, assuming this is for AT&T syntax (not gcc -masm=intel). Named constraints like [port] "dN" (port) to match %[port] in the template would avoid that. https://www.felixcloutier.com/x86/out is out dx/imm8, AL/AX/EAX in Intel syntax, or out %al/%ax/%eax, %dx/$imm8 in AT&T. Also, you separately broke out32() in another way. A "dN" constraint allows the compiler to pick DX or an immediate for that variable (if its value is known at compile time and is small enough). But your asm template string doesn't reference that %0 first operand, instead hard-coding the %%dx register name, which is only correct if the compiler picks DX. An optimized build that inlines out32(0x80, 0x1234) would not have put the port number in DX with preceding instructions, instead picking the N (unsigned 8-bit) constraint because it's cheaper. But no $0x80 gets filled in anywhere in the final compiler-generated asm because there's no %0 in the template for the compiler to expand. Think of asm template strings like printf format strings that the compiler expands, before passing on the whole asm to the assembler. (Including compiler-generated instructions before and after, from compiling other C statements, and for some constraints like "r" or "d" to put a C variable or expression's value into a register if it wasn't already there.) %% is just a literal %, so if you want to hard-code an AT&T register name like %eax, you use %%eax in the Extended Asm template. You can see that asm on https://godbolt.org/. (Use "binary" mode to see if the resulting compiler-generated asm will actually assemble. That's not guaranteed when using inline asm.) For working outb / etc. macros, many codebases define them, and I think some libc implementations have inline wrappers, like maybe MUSL, maybe also glibc. If you just want working code, don't try to write your own when you don't know inline asm. Related: How do you explain gcc's inline assembly constraints for the IN, OUT instructions of i386? breaks down an inb wrapper function. C inline asm for x86 in / out port I/O has operand-size mismatch the size of register picked for "d" depends on the C type width, and has to be 16-bit because in/out specifically use DX. (I/O address space is 64k, unlike memory address space.) GCC Inline Assembly 'Nd' constraint https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html The manual. Read it. Inline asm is easy to get subtly but dangerously wrong; do not rely on trial and error / "seems to work". https://gcc.gnu.org/wiki/DontUseInlineAsm. (Or in this case, find some known-good in/out wrapper functions in a libc header or something and use them instead of writing your own, if you don't know inline asm.) https://stackoverflow.com/tags/intel-syntax/info
69,283,715
69,284,111
C++ compiler optimisations (MSYS2 MinGW-64 bit GCC compiler used with VSCode)
I'm trying to apply the different optimisation levels (-O0, -O1, -O2, -O3 and so on) to the compilation and execution of a .cpp file. However, I can't figure out the exact syntax I need to use and where to write the instructions (i.e. in which terminal, the VSCode terminal or the MinGW terminal)? Any help would be much appreciated. tasks.json: { "tasks": [ { "type": "cppbuild", "label": "C/C++: g++.exe build active file", "command": "C:\\msys64\\mingw64\\bin\\g++.exe", "args": [ "-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "Task generated by Debugger." }, { "type": "cppbuild", "label": "C/C++: cpp.exe build active file", "command": "C:\\msys64\\mingw64\\bin\\cpp.exe", "args": [ "-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": "build", "detail": "compiler: C:\\msys64\\mingw64\\bin\\cpp.exe" } ], "version": "2.0.0" }
In this field: "args": [ "-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe" ], add the optimization option: "args": [ "-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe", "-O2" ], Consider that you have two tasks (I am not sure why you have the second one) and you need to set it in the correct task. If I were you I would remove the unused one and instead create a task for debug and release build: Release build in Visual Studio Code Be careful that this is about c# and cannot be copy pasted!
69,284,009
69,284,010
Dereference a double pointer (a pointer to a pointer to a value) in GDB
I'm writing a script to reverse engineer an executable. I have a situation where RAX is a pointer to a value which itself is a pointer to an object. The very first value of that object, in turn, is a pointer to a string. A visualization should clear it up: RAX | | points to | V Value on the stack | | points to | V The start of an object (std::vector<std::string) | | the very first value of that object points to | V A string in memory I want to access the string in memory. How do I do that with one command?
Here's how I did it: # Dereference RAX to get the value on the stack (gdb) x/gx $rax 0x7fffffffe0d0: 0x0000555555598700 # Dereference the value on the stack to get the start of the object (gdb) x/gx *((uint64_t*)$rax) 0x555555598700: 0x0000555555578ea0 # Dereference the start of the object because it points to a string (gdb) x/s *((uint64_t*)*((uint64_t*)$rax)) 0x555555578ea0: "/root/.ssh/id_rsa" I had to cast the values to uint64_t because otherwise GDB would think it's a 32-bit value (I'm working with a 64-bit executable). Additionally, there was another pointer to a string 4 bytes after the start of the vector object. Here's how I accessed that string: x/s *((uint64_t*)*((uint64_t*)$rax) + 4)
69,284,573
69,284,702
Can we get underscores in printf instead of blank spaces while writing "%15.2f" or something like that?
#include <iostream> using namespace std; int main() { double B = 2006.008; printf("%15.2f", B); return 0; } Output: +2006.01 with blank spaces in the beginning I want to replace those white spaces with underscores(_). Is there any syntax in print or any direct method to do that? My desired output: _______+2006.01
As in the comments suggested you can write a function for this, but not with printf(). #include <algorithm> #include <iostream> std::string formatNumber(double number) { char buffer[15 + 1 + 2]; sprintf(buffer, "%15.2f", number); std::string s(buffer); std::replace(s.begin(), s.end(), ' ', '_'); return s; } int main() { double B = 2006.008; auto toPrint = formatNumber(B); std::cout << toPrint << std::endl; return 0; }
69,284,652
69,285,189
C++20 chrono, parsing into zoned time and formatting without trailing decimals
I am writing a bit of code that intakes a string from a user, and formats it into a zoned time. The parsing code is a bit more complicated than this example, but this will reproduce problem. This is compiled with MSVC++ compiled with /std:c++latest. #include <iostream> #include <string> #include <chrono> #include <sstream> int main() { std::string timeString("2020-02-03 00:12:34"); std::string formatString("%Y-%m-%d %T"); bool successful = true; std::stringstream iss(timeString); std::chrono::local_time<std::chrono::system_clock::duration> localTimeStamp; if (not (iss >> std::chrono::parse(formatString, localTimeStamp))) { successful = false; } auto result = std::chrono::zoned_time(std::chrono::current_zone(), localTimeStamp); std::cout << std::format("{:%Y-%m-%d %T}", result) << std::endl; } Results in the following output: 2020-02-03 00:12:34.0000000 I would like for the output to not have the trailing decimals. Since it's a string, I can always truncate the string at the decimal anyway. Is there a better way to do this?
Just change the type of localTimeStamp to have seconds precision: std::chrono::local_time<std::chrono::seconds> localTimeStamp; There's also this convenience type-alias to do the same thing if you prefer: std::chrono::local_seconds localTimeStamp; The precision of the parsing and formatting is dictated by the precision of the time_point being used.
69,284,670
69,284,996
Why is a pointer used in this program instead of regular variables?
Can anybody please explain how this code functions? Pointers are kinda confusing so I need a little bit of help to understand what's happening. I know that it's calculating the sum and absolute difference but I don't get why we need pointers here. Please help. #include <iostream> using namespace std; void update(int *a, int *b) { int sum = *a + *b; int abs = *a - *b; if (abs < 0) abs *= -1; cout << sum << '\n' << abs; } int main() { int a, b; int *pa = &a, *pb = &b; cin >> a >> b; update(pa, pb); return 0; }
You're right. This is confusing. The code is needlessly difficult, in more ways than one. Let's look at what's happening. The function update(int *a, int *b) takes two pointers to integers as parameters. That is, when you call it, you pass the addresses of two variables that are ints. The function adds and subtracts the actual integers, using the * operator to dereference the pointers, meaning, to read the actual variables that a and b are pointing at. There's no need to pass the parameters as pointers, and the first change I'd make to this code is to pass the variables by value. All that update() needs to know is the values, not where the variables are in memory. (If it needed to change the values of those variables, that'd be different.) The only result of calling the function is the printing of the sum and absolute difference between the values, which is why the second thing about the code that I'd change is the name of this function. Looking at main() we see that the parameters passed are indeed the addresses of two variables, which are obtained using the address-of & operator. Note that the variables defined in main() are given the same name as the parameters in update(), which is potentially confusing since they are quite different. In one case they are integers; in another, pointers to integers. But even if they were the same type, they would refer to different variables in different places in memory, and a programmer might confuse the two. So the last change I'd make is rename the variables. void print_sum_difference(int i1, int i2) { int sum = i1 + i2; int abs = i1 - i2; if (abs < 0) abs *= -1; cout << sum << '\n' << abs; } int main() { int a, b; cin >> a >> b; print_sum_difference(a, b); return 0; } Having said all that... why were pointers used? I'm guessing that the code in question is a step on the road to using "pass by reference" mechanisms to allow a function to modify values in the calling code. When we pass by value, as in my code above, the function is given a copy of the variables. Two new integers are made, the values are copied, and the function gets to use those. If it changes them, the variables in main() aren't changed. But in the original code, the values could be changed by code in update() like *a=0; which would change the value of a in main().
69,284,854
69,285,023
C++ Program is not finding the searched word - except the first line
Task: Create program to read given text file and print into another text file all lines containing given substring. Reading from files should be carried out line per line. My code: #include <iostream> #include <fstream> #include <sstream> using namespace std; int main(){ string inputFileName = "inputFile.txt"; string outputFileName = "outputFile.txt"; fstream inputfile; ofstream outputFile; inputfile.open(inputFileName.c_str()); outputFile.open(outputFileName.c_str()); string keyWord; cout << "Please, enter a key word: " << endl; cin >> keyWord; string line; while (getline(inputfile, line)) { // Processing from the beginning of each line. if(line.find(keyWord) != string::npos){ outputFile << "THE LINE THAT IS CONTAINING YOUR KEY WORD: " << "\n" << line << "\n"; } else cout << "Error. Input text doesn't have the mentioned word." << endl; break; } cout << "An output file has been created!"; } Problem: I can find the word that I'm searching for in the first line. But not in the following lines (after Enter, \n)!
int found = 0; while (getline(inputfile, line)) { // Processing from the beginning of each line. if(line.find(keyWord) != string::npos){ outputFile << "THE LINE THAT IS CONTAINING YOUR KEY WORD: " << "\n" << line << "\n"; found = 1; } } if(found == 0) { cout << "Error. Input text doesn't have the mentioned word." << endl; }
69,284,927
69,285,054
C++ std::conditional_t wont compile with std::is_enum_v and std::underlying_type_t
I am trying to wite type traits for types that can index into e.g. an std::vector, which should include enum types because i can cast them to their underlying type. I have written following traits so far. #include <iostream> #include <type_traits> #include <cinttypes> #include <vector> #include <utility> template<typename T> struct is_unsigned_integral : std::integral_constant< bool, std::is_integral<T>::value && std::is_unsigned<T>::value > {}; template<typename T> inline constexpr auto is_unsigned_integral_v = is_unsigned_integral<T>::value; template<typename, typename = void> struct is_index : std::false_type {}; template<typename T> struct is_index< T, std::enable_if_t< is_unsigned_integral_v< std::conditional_t< std::is_enum_v<T>, std::underlying_type_t<T>, T > > > > : std::true_type {}; template<typename T> inline constexpr auto is_index_v = is_index<T>::value; enum class idx : unsigned int {}; int main() { static_assert(is_index_v<unsigned int>, ""); static_assert(is_index_v<idx>, ""); return 0; } But im getting following error message type_traits:2009:15: error: only enumeration types have underlying types typedef __underlying_type(_Tp) type; I would expect the following std::conditional_t< std::is_enum_v<T>, std::underlying_type_t<T>, T > to evaluate eighter to T or to underlying type is T is an enum. How would i make this work?
Substitution fails because there is no std::underlying_type_t<unsigned int>. You can specialize seperately: #include <iostream> #include <type_traits> #include <cinttypes> #include <vector> #include <utility> template<typename T> struct is_unsigned_integral : std::integral_constant< bool, std::is_integral<T>::value && std::is_unsigned<T>::value > {}; template<typename T> inline constexpr auto is_unsigned_integral_v = is_unsigned_integral<T>::value; template<typename, typename = void> struct is_index : std::false_type {}; template<typename T> struct is_index< T, std::enable_if_t< is_unsigned_integral_v<T> > > : std::true_type {}; template <typename T> struct is_index<T,std::enable_if_t<std::is_enum_v<T> >> : is_index<std::underlying_type_t<T> > {}; template<typename T> inline constexpr auto is_index_v = is_index<T>::value; enum class idx : unsigned int {}; int main() { static_assert(is_index_v<unsigned int>, ""); static_assert(is_index_v<idx>, ""); return 0; } PS: From cppreference/std::underlying_type If T is a complete enumeration (enum) type, provides a member typedef type that names the underlying type of T. Otherwise, the behavior is undefined. (until C++20) Otherwise, if T is not an enumeration type, there is no member type. Otherwise (T is an incomplete enumeration type), the program is ill-formed. (since C++20) I have to admit that I am not sure how that undefined beahvior (before C++20) plays with SFINAE in your example. Though, note that it is not an issue in the above, because it only uses std::underlying_type_t<T> when T is actually an enum type.
69,285,327
69,285,408
Assigning a function to a variable in C++
What happens if you assign a function to a variable as shown below unsigned char uchHeaderVer; uchHeaderVer = GetCodec(Page.Version); BYTE CWAV::GetCodec(BYTE byVersion) { RecorderInfoMap::iterator it; if ((it = m_mapRecInfo.find(byVersion)) != m_mapRecInfo.end()) { return (BYTE) ((*it).second.nCodec); } else { return 4; } } Version is of type BYTE and is stored in a typedef struct
What happens if you assign a function to a variable as shown below You aren't assigning a function to a variable. You are calling a function, and assigning the result to that variable. You haven't shown what BYTE is, but it is very likely to be a type alias for either unsigned char (or possibly char). You can't assign a function to a variable, because functions aren't objects. You can only assign pointers to functions to variables, e.g. BYTE (*pGetCodec)(BYTE) = &CWAV::GetCodec; auto pGetCodec2 = &CWAV::GetCodec; using GetCodecF = BYTE (*)(BYTE); GetCodecF pGetCodec3 = &CWAV::GetCodec;
69,285,443
69,474,719
Add CRL number extension to CRL using OpenSSL
For some client testing I need to generate certificates and revocation lists "on the fly". I am able to setup a revocation list with the CRL number extension using OpenSSL console commands and configuration files. However I can't make this work in code. Here are my relevant functions: X509* g_certificate[MAX_CERTIFICATE_COUNT]; EVP_PKEY* g_certificateKeyPair[MAX_CERTIFICATE_COUNT]; X509_CRL* g_crl; UINT16 GenerateCrl(UINT16 issuerCertificateIndex, UINT16 crlNumber, INT32 lastUpdate, INT32 nextUpdate) { ASN1_TIME* lastUpdateTime = ASN1_TIME_new(); ASN1_TIME* nextUpdateTime = ASN1_TIME_new(); char crlNumberString[32]; int result = 1; if (g_crl != NULL) X509_CRL_free(g_crl); g_crl = X509_CRL_new(); result &= X509_CRL_set_version(g_crl, 1); result &= X509_CRL_set_issuer_name(g_crl, X509_get_subject_name(g_certificate[issuerCertificateIndex])); // there are multiple X509 certificate objects stored in memory, which I use to setup certificate chains ASN1_TIME_set(lastUpdateTime, time(NULL) + lastUpdate); ASN1_TIME_set(nextUpdateTime, time(NULL) + nextUpdate); result &= X509_CRL_set1_lastUpdate(g_crl, lastUpdateTime); result &= X509_CRL_set1_nextUpdate(g_crl, nextUpdateTime); ASN1_TIME_free(lastUpdateTime); ASN1_TIME_free(nextUpdateTime); _itoa_s((int)crlNumber, crlNumberString, 10); // my CRLs need to have the authority key identifier and CRL number extensions result &= SetCrlExtension(issuerCertificateIndex, NID_authority_key_identifier, "keyid:always"); // this does add the auth key id extension result &= SetCrlExtension(issuerCertificateIndex, NID_crl_number, crlNumberString); // this does not add CRL number the extension result &= X509_CRL_sign(g_crl, g_certificateKeyPair[issuerCertificateIndex], EVP_sha256()); return result; } INT16 SetCrlExtension(UINT16 issuerCertificateIndex, INT16 extensionNid, const char* extensionData) { X509V3_CTX ctx; X509_EXTENSION* extension; lhash_st_CONF_VALUE conf; // actually I have no idea what this is for, probably it is not required here int result = 1; X509V3_set_ctx(&ctx, g_certificate[issuerCertificateIndex], NULL, NULL, g_crl, 0); extension = X509V3_EXT_conf_nid(&conf, &ctx, extensionNid, (char*)extensionData); result &= X509_CRL_add_ext(g_crl, extension, -1); return result; } void SaveCrlAsPem(const char* fileName) { FILE* f; fopen_s(&f, fileName, "wb"); PEM_write_X509_CRL(f, g_crl); if (f != NULL) fclose(f); } So e.g. GenerateCrl(1, 1234, -3600, 36000); SaveCrlAsPem("crl.pem"); should result in a CRL having said extension. But it does only contain the authority key identifier extension. Everything else is fine. Im also adding the certificate extensions in basically the same way and dont't have any issues there. So how can I get the CRL number attached to my CRL?
You mention that you are able to setup the CRL number extension from OpenSSL command line. You should probably take a look at the source code of the particular command then. I haven't used CRLs, but I believe you are using the ca command. Looking for NID_crl_number in its source at apps/ca.c (from OpenSSL 1.1.1g) shows the following code: /* Add any extensions asked for */ if (crl_ext != NULL || crlnumberfile != NULL) { X509V3_CTX crlctx; X509V3_set_ctx(&crlctx, x509, NULL, NULL, crl, 0); X509V3_set_nconf(&crlctx, conf); if (crl_ext != NULL) if (!X509V3_EXT_CRL_add_nconf(conf, &crlctx, crl_ext, crl)) goto end; if (crlnumberfile != NULL) { tmpser = BN_to_ASN1_INTEGER(crlnumber, NULL); if (!tmpser) goto end; X509_CRL_add1_ext_i2d(crl, NID_crl_number, tmpser, 0, 0); ASN1_INTEGER_free(tmpser); crl_v2 = 1; if (!BN_add_word(crlnumber, 1)) goto end; } } So, it seems you can use X509V3_EXT_CRL_add_nconf or X509_CRL_add1_ext_i2d for the purpose. Please refer the apps/ca.c of the OpenSSL version that you are using. Another solution: Maybe not the best approach, but you can probably launch the same OpenSSL commands as processes from code and process their output if it's acceptable.
69,285,515
69,285,612
Does lifetime of a const auto reference inside a ranged-based for loop extends to the end of the scope?
I have ran across a bit of code, that clears a deque while inside a range-based for loop. The const auto reference is still used subsequently. Here is a small reproduction. struct Foo { int x; } deque<Foo> q1; deque<Foo> q2; q1.push_front({0}); q1.push_front({1}); for (const auto& ref : q1) { if (ref.x == 1) { q1.clear(); q2.push_front(ref); break; } } std::cout << q2.front().x << std::endl; This q2 appears to have gotten the value of ref. But I am thinking that the q1.clear() should have deleted the underlying data of ref. Does the lifetime for the reference last through the scope, or is this an undefined behaviour? If it is an undefined behaviour, why is this working??? edit: missed the break from the original code, added back to narrow down the discussion.
Does the lifetime for the reference last through the scope, or is this an undefined behaviour? To start with, the following range-based for loop: for (auto const& ref : q1) { // ... } expands, as per [stmt.ranged]/1, to { auto &&range = (q1); for (auto begin_ = range.begin(), end_ = range.end(); begin_ != end_; ++begin_) { auto const& ref = *begin_; // ... } } Now, as per the docs for std::deque<T>::clear: Erases all elements from the container. After this call, size() returns zero. Invalidates any references, pointers, or iterators referring to contained elements. Any past-the-end iterators are also invalidated. if the if (ref.x == 1) branch is ever entered, then past the point of q1.clear(); the iterator whose pointed-to object ref is referring to (here: the deque element) is invalidated, and any further use of the iterator is undefined behavior: e.g. incrementing it an dereferencing it in the next loop iteration. Now, in this particular example, as the for-range-declaration is auto const& as compared to only auto &, if the *begin_ dereferencing (prior to invalidating iterators) resolves to a value and not a reference, this (temporary) value would bind to the ref reference and have its lifetime extended. However, std::deque is a sequence container and shall adhere to the requirements of [sequence.reqmts], where particularly Table 78 specifies: /3 In Tables 77 and 78, X denotes a sequence container class, a denotes a value of type X [...] Table 78: Expression: a.front() Return type: reference; (const_­reference for constant a) Operational semantics: *a.begin() Whilst not entirely water-proof, it seems highly likely that dereferencing a std::deque iterator (e.g. begin() or end()) yields a reference type, something both Clang and GCC agrees on: #include <deque> #include <type_traits> struct S{}; int main() { std::deque<S> d; static_assert(std::is_same_v<decltype(*d.begin()), S&>, ""); // Accepted by both clang and gcc. } in which case the use of ref in q2.push_front(ref); is UB after the q1.clear(). We may also note that the end() iterator, stored as end_, is also invalidated by the invocation of clear(), which is another source of UB once the invariant of the expanded loop is tested in the next iteration. If it is an undefined behaviour, why is this working??? Trying to reason with undefined behavior is a futile exercise.
69,285,919
69,286,097
Need help struct-void error: type name isn't allowed
I created a struct and void function. I want to write out age and name inside of struct xyz with the void abc. But i didn't understand i'm getting an error on case 1-2 part type name isn't allowed #include <iostream> using namespace std; struct xyz { int age = 20; string name = "name"; }; void abc() { int num; cin >> num; switch (num) { case 1: cout << xyz.age << endl; return; case 2: cout << xyz.name << endl; return; } } int main() { for(;;) abc(); }
You'd have to do something like this - #include <iostream> using namespace std; struct xyz { int age = 20; string name = "name"; }; void abc() { xyz myStruct; int num; cin >> num; switch (num) { case 1: cout << myStruct.age << endl; return; case 2: cout << myStruct.name << endl; return; } } int main() { for(;;) abc(); } Another option would be something like this - #include <iostream> using namespace std; struct xyz { int age; string name; }; void abc() { xyz myStruct{20, "name"}; int num; cin >> num; switch (num) { case 1: cout << myStruct.age << endl; return; case 2: cout << myStruct.name << endl; return; } } int main() { for(;;) abc(); }
69,286,141
69,286,703
Accessing overloaded method from a parent class
I have stumbled upon this code, and I can't understand, why do I need to specify the class I want to call the method with one argument from? What's more interesting, if I remove the second overloaded method with two parameters, everything will work fine. class A { public: virtual void foo(int a) const final {}; virtual void foo(int a, int b) const = 0; }; class B : public A { public: void foo(int a, int b) const override {} }; int main() { B b; b.A::foo(1); // Why do I need to specify A::foo?? // b.foo(1) -- won't compile }
Because what b sees is the overloaded instance of foo(int a, int b), which preforms name hiding, therefore foo(int a, int b) makes foo(int a) invisible from b. If you want to make foo(int a), you should specify that it should look in class A, that's why you need A::
69,286,582
69,289,045
what is the meaning in C++ when casting both (int) and (int16_t)
I am studying a C++ code in Arduino example for reading external data. The code use casting (int16_t) and also (int). int16_t is fixed integer type, but I don't understand it's purpose in the code. _vRaw[0] = (int)(int16_t)(Wire.read() | Wire.read() << 8); Is there any difference if I write like below? _vRaw[0] = (int)(Wire.read() | Wire.read() << 8);
I've written code like this before so I can explain the purpose of the cast to int16_t. The Arduino command Wire.read() generally returns a number between 0 and 255 representing a byte read from the I2C device. Sometimes, two of the bytes you read from a device will represent a single signed 16-bit number using Two's complement. So, for example, if the first byte is 1 and the second byte is 2, we want to interpret that as a value of 1 + 2*256 = 513. If both bytes are 255, we want to interpret that as -1. Let's assume that your code is being compiled for a system where int is 32-bit (almost any 32-bit microcontroller), and both bytes are 255, and think about this expression: (Wire.read() | Wire.read() << 8) The value of this expression would simply be 255 | (255 << 8) which is 65535. That is bad; we wanted the value to be -1. The easy way to fix that bug is to add a cast to int16_t: (int16_t)(Wire.read() | Wire.read() << 8) When we cast 65535 to an int16_t type, we get -1 because an int16_t cannot hold 65535 (it can only hold values from -32768 to 32767). (The C++ standard does not guarantee that we get -1, but it is implementation defined behavior so you can check the manual of your compiler if you want to make sure.) If we later cast it back to an int (either with an explicit cast or by setting some int equal to it), the compiler will do the correct signed extension operation and give us an int with a value of -1. By the way, I'm not confident that your compiler will run the two calls to Wire.read() in the right order unless you have a semicolon between then. Also, the final cast to int is probably not needed. So I would rewrite the code to be something like this: uint8_t lsb = Wire.read(); _vRaw[0] = (int16_t)(lsb | Wire.read() << 8);
69,286,717
69,286,798
How to understand this expression in C++ struct?
struct Task{ int value,time,deadline; bool operator < (const Task& t1)const{ return d<t1.deadline; } }task[1000]; I've read this block of code of struct initialization. the first line, initialize variables, is easy to grasp. What about the second line? the bool operator thing. Seems like some kind of sorting rules. I have never seen any code like this in cpp before, could someone help me to understand it?
What you observe is called operator overloading. In this case the operator< is overloaded for class Task. This is done in order to be able to write something like this. Task t1{1,2,3}; Task t2{2,3,4}; if(t1 < t2) //note, the operator< is called { //do your thing }
69,287,014
69,289,950
Store memory address of local variable in global container
In my understanding it is not possible to store the address of a local memory in a global container, because the local variable will eventually be destroyed. class AA { std::string name; public: explicit AA(std::string n) : name(n) {} std::string getName() const { return name; } }; class Y { std::vector<std::reference_wrapper<AA>> x; public: void addAA(AA& aa) { x.emplace_back(aa); } AA& getLastA() { return x.back(); } }; void foobar(Y& y) { AA aa("aa"); y.addAA(aa); } int main() { Y y; foobar(y); std::cout << y.getLastA().getName() << std::endl; // error - probably because the local aa has been destroyed. return 0; } However, I do not understand why this code works: void foobar(Y& y, AA& aa) { y.addAA(aa); } int main() { Y y; { AA aa("aa"); foobar(y,aa); } std::cout << y.getLastA().getName() << std::endl; return 0; } aa is again created in another scope and should be destroyed. However, it is possible to get its name later in main. The code works fine. Why don't we get an error in the second case?
In my understanding it is not possible to store the address of a local memory in a global container, because the local variable will eventually be destroyed. You're starting from a flawed understanding. It's certainly a bad idea to keep the address of a local variable beyond its lifetime, but it's still possible. As you say, it's a bad idea because that pointer will quickly become invalid. Even so, you can take the address of any variable, and the language won't prevent you from storing it wherever you like. Like C before it, C++ lets you do a great many things that are bad ideas, so be careful.
69,287,136
69,287,471
How to make a c++ program and will use the command line input and ls in that directory?
My system is Ubuntu 20.04. Suppose I am in project directory and this directory contains these folders/files: test, hello.txt. I wrote the following program:- #include <iostream> #include <string> #include <cstdlib> using namespace std; int main(int argc, char* argv[]){ const char* command = "ls" + argv[1]; system(command); return 0; } And then I will test as first argument of the program while running it. I expected it will print all files and folders in test folder. But it gave me an error. Can someone tell me, what is the error and how to fix it?
What you do in your code is not correct, You add two pointers, and the result you will clearly not be what you expect. Use std::string. So your code will look like this: #include <iostream> #include <string> #include <cstdlib> #include <string> using namespace std; int main(int argc, char* argv[]) { if(argc < 2) { cerr << "missing cli argument\n"; return -1; } auto command = std::string("ls ") + std::string(argv[1]); system(command.data()); return 0; } Usually using the system function is a bad practice, so in your case I would rather use the functionality that performs your task: display all files in folder. Together with your code, it will look like this: #include <string> #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main(int argc, char* argv[]) { if(argc < 2) { std::cerr << "missing cli argument\n"; return -1; } std::string path = argv[1]; for (const auto & entry : fs::directory_iterator(path)) std::cout << entry.path() << std::endl; return 0; }