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
73,364,524
73,375,622
trying to update TWSAPI.. getting error on linking? is this the new intel lib?
I utilize a conan recipe to build the TWS-API in C++ .. and recently (4-10 months ago) IBKR pushed in a prebuilt library into the mix.. some intel lib.. I tried to fix all the code , refresh function definitions.. but on linking I am getting stuck ... -- Library z found /home/emcp/.conan/data/zlib/1.2.12/_/_/package/dfbe50feef7f3c6223a476cd5aeadb687084a646/lib/libz.a -- Library bz2 found /home/emcp/.conan/data/bzip2/1.0.8/_/_/package/c32092bf4d4bb47cf962af898e02823f499b017e/lib/libbz2.a -- Library backtrace found /home/emcp/.conan/data/libbacktrace/cci.20210118/_/_/package/dfbe50feef7f3c6223a476cd5aeadb687084a646/lib/libbacktrace.a -- Library ssl found /home/emcp/.conan/data/openssl/1.1.1o/_/_/package/dfbe50feef7f3c6223a476cd5aeadb687084a646/lib/libssl.a -- Library crypto found /home/emcp/.conan/data/openssl/1.1.1o/_/_/package/dfbe50feef7f3c6223a476cd5aeadb687084a646/lib/libcrypto.a -- Conan: Adjusting default RPATHs Conan policies -- Conan: Adjusting language standard -- Current conanbuildinfo.cmake directory: /home/emcp/git/build_cmake -- Conan: Compiler GCC>=5, checking major version 11 -- Conan: Checking correct version: 11 -- Configuring done -- Generating done -- Build files have been written to: /home/emcp/Dev/git/build_cmake [ 12%] Building CXX object CMakeFiles/ibrokers_server.dir/src/ibrokers_server.cpp.o [ 25%] Building CXX object CMakeFiles/ibrokers_server.dir/src/gen-cpp/ibrokers.cpp.o [ 37%] Building CXX object CMakeFiles/ibrokers_server.dir/src/gen-cpp/ibrokers_types.cpp.o [ 50%] Building CXX object CMakeFiles/ibrokers_server.dir/src/tws-client/AccountSummaryTags.cpp.o [ 62%] Building CXX object CMakeFiles/ibrokers_server.dir/src/tws-client/AvailableAlgoParams.cpp.o [ 75%] Building CXX object CMakeFiles/ibrokers_server.dir/src/tws-client/TestCppClient.cpp.o [ 87%] Building CXX object CMakeFiles/ibrokers_server.dir/src/tws-client/Utils.cpp.o [100%] Linking CXX executable bin/ibrokers_server /usr/bin/ld: CMakeFiles/ibrokers_server.dir/src/tws-client/TestCppClient.cpp.o: in function `decimalStringToDisplay[abi:cxx11](unsigned long long)': TestCppClient.cpp:(.text._Z22decimalStringToDisplayB5cxx11y[_Z22decimalStringToDisplayB5cxx11y]+0x46): undefined reference to `__bid64_to_string' /usr/bin/ld: /home/emcp/.conan/data/twsapi/10.17.01/stonks/prod/package/062863c92a5a0a247840166e9f84ebe8d10786b9/lib/libtwsapi.a(EClient.cpp.o): in function `void EClient::EncodeField<unsigned long long>(std::ostream&, unsigned long long)': EClient.cpp:(.text+0x52e): undefined reference to `__bid64_to_string' /usr/bin/ld: /home/emcp/.conan/data/twsapi/10.17.01/stonks/prod/package/062863c92a5a0a247840166e9f84ebe8d10786b9/lib/libtwsapi.a(EDecoder.cpp.o): in function `EDecoder::DecodeField(unsigned long long&, char const*&, char const*)': EDecoder.cpp:(.text+0x803c): undefined reference to `__bid64_from_string' collect2: error: ld returned 1 exit status gmake[2]: *** [CMakeFiles/ibrokers_server.dir/build.make:247: bin/ibrokers_server] Error 1 gmake[1]: *** [CMakeFiles/Makefile2:83: CMakeFiles/ibrokers_server.dir/all] Error 2 gmake: *** [Makefile:91: all] Error 2 chmod: cannot access 'ibrokers_server': No such file or directory Is there a way I can .. ensure or refresh my conan cache other than erase the build area and do conan install .. --upgrade ?
according to this post https://github.com/InteractiveBrokers/tws-api/issues/1150#issuecomment-1215515313 we have a problem with the new intel code not linking properly.. this user was on Debian and was able to apt install the library.. and link it manually sudo apt install libintelrdfpmath-dev and in your linker.. add this module bidgcc000
73,365,461
73,365,551
Non-type parameter pack cartesian product, "template argument deduction/substitution failed"
I was messing with non-type parameter packs and tried to do a cartesian product with them. I arrived at a piece of code that somehow compiles with GCC in C++20 but not C++17, and does not compile with Clang at all. I also tried MSVC, which, like GCC, compiles in C++20 but not C++17, but also generates a lot of assembly code for some reason. I would like to understand why the code doesn't compile in C++17. The error message isn't useful, it just says template argument deduction/substitution failed: and the line in question... Here is the simplest snippet I could come up with: #include <iostream> #include <utility> template<auto ...values> struct ValueParameterPack {}; template<std::size_t I, typename T, T ...values> constexpr T get(ValueParameterPack<values...>) { constexpr T value_array[] = {values...}; return value_array[I]; } template<std::size_t I, typename T> constexpr auto get_v = get<I>(T{}); template<auto ...values1, auto ...values2, std::size_t ...Is> auto cartesian_product(ValueParameterPack<values1...>, ValueParameterPack<values2...>, std::index_sequence<Is...>) -> ValueParameterPack< std::make_pair( get_v<Is / sizeof...(values2), ValueParameterPack<values1...>>, get_v<Is % sizeof...(values2), ValueParameterPack<values2...>> )... >; template<auto ...values1, auto ...values2> auto cartesian_product(ValueParameterPack<values1...>, ValueParameterPack<values2...>) -> decltype(cartesian_product( ValueParameterPack<values1...>{}, ValueParameterPack<values2...>{}, std::make_index_sequence<sizeof...(values1) * sizeof...(values2)>() )); template<typename ValueParameterPack1, typename ValueParameterPack2> using CartesianProduct = decltype(cartesian_product(ValueParameterPack1{}, ValueParameterPack2{})); int main() { using T = CartesianProduct<ValueParameterPack<1, 2>, ValueParameterPack<3, 4>>; } https://godbolt.org/z/sWGv7G7e5 Here is a longer version that actually makes use of the cartesian product in case you're curious, but it's not very important: https://godbolt.org/z/dnYbKMe18 I'm sure there are other ways to achieve what I want, and I welcome any idea, but I'm mostly just curious as to why GCC can compile it with -std=c++20 but not with std=c++17, since I don't think I'm using any C++20 feature. And I want some insights into that error message that provides no additional details.
When you write, ValueParameterPack< std::make_pair( get_v<Is / sizeof...(values2), ValueParameterPack<values1...>>, get_v<Is % sizeof...(values2), ValueParameterPack<values2...>> )... >; you can't pass a std::pair as a template non-type argument. You can, however, pass it as two arguments (if the particular types allow it). So I'd recommend to pass, instead of a ValueParameterPack<pair<int,int>(..)...>, passing a ValueParameterPack<int, int, ...>. Then process it by every pair of element. If you don't like the idea of processing two elements as a step, I've included a workaround solution below using compile-time pairs. To be clear, when I write, 'can't pass', I don't mean it according to the C++ standard. It's an error message that occurs with g++. Likely a compiler / library issue. While debugging your code, there were at minimum 2 similar issues, so it's not something that never occurs - likely worth reporting. Here's a way to solve it without std::pair<>: #include <iostream> #include <utility> template<auto i, auto j> struct mypair {}; template<auto ...values> struct ValueParameterPack {}; template<std::size_t I, typename T, T ...values> constexpr T get(ValueParameterPack<values...>) { constexpr T value_array[] = {values...}; return value_array[I]; } template<std::size_t I, typename T> constexpr auto get_v = get<I>(T{}); template<size_t I, size_t C, typename T1, typename T2> using mypair_gen = mypair< get_v<I / C, T1>, get_v<I % C, T2> >; template<auto ...values1, auto ...values2, std::size_t ...Is> auto cartesian_product(ValueParameterPack<values1...>, ValueParameterPack<values2...>, std::index_sequence<Is...>) -> ValueParameterPack< mypair_gen<Is, sizeof...(values2), ValueParameterPack<values1...>, ValueParameterPack<values2...>>{}... >; template<auto ...values1, auto ...values2> auto cartesian_product(ValueParameterPack<values1...>, ValueParameterPack<values2...>) -> decltype(cartesian_product( ValueParameterPack<values1...>{}, ValueParameterPack<values2...>{}, std::make_index_sequence<sizeof...(values1) * sizeof...(values2)>() )); template<typename ValueParameterPack1, typename ValueParameterPack2> using CartesianProduct = decltype(cartesian_product(ValueParameterPack1{}, ValueParameterPack2{})); int main() { using T = CartesianProduct<ValueParameterPack<1, 2>, ValueParameterPack<3, 4>>; }
73,365,561
73,422,496
cygwin g++ can't find pmr namespace and related issues
Ok so I decided to compile some code from godbolt locally on my Windows 10 64bit using Cygwin and the cygwin terminal. It compiles fine on godbolt, but cygwin/mingw64 g++ spits out loads of errors along the lines of: jsontest.cpp:310:23: error: β€˜string’ is not a member of β€˜std::pmr’; did you mean β€˜std::string’? 310 | auto expand(std::pmr::string s, ospolicy policy) { | ^~~~~~ In file included from /usr/lib/gcc/x86_64-pc-cygwin/11/include/c++/string:39, from jsontest.cpp:2: /usr/lib/gcc/x86_64-pc-cygwin/11/include/c++/bits/stringfwd.h:79:33: note: β€˜std::string’ declared here 79 | typedef basic_string<char> string; ^~~~~~ There are a lot more issues but I think they are all related to this one. When I looked into the headerfile for #include<string> (which I did), std::pmr::string is defenitely defined there. The file stringfwd.h just forward declares basic_string templates so it should still find the definitions. This is the section inside the string headerfile: #if __cplusplus >= 201703L && _GLIBCXX_USE_CXX11_ABI namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace pmr { template<typename _Tp> class polymorphic_allocator; template<typename _CharT, typename _Traits = char_traits<_CharT>> using basic_string = std::basic_string<_CharT, _Traits, polymorphic_allocator<_CharT>>; using string = basic_string<char>; #ifdef _GLIBCXX_USE_CHAR8_T using u8string = basic_string<char8_t>; #endif using u16string = basic_string<char16_t>; using u32string = basic_string<char32_t>; #ifdef _GLIBCXX_USE_WCHAR_T using wstring = basic_string<wchar_t>; #endif } // namespace pmr //... } // namespace std You can see that the std::pmr::string typedef is guarded and only availabe when the C++ version is greater than 17 (as polymorphic memory resources are only available from C++17) and something about the CXX ABI. I'm using gcc 11.3 which should be able to support even C++20 language features. I'm not getting it... what am I doing differently than godbolt? EDIT: Try this to reproduce: Download cygwin from here and install it the usual way (add g++ to environment vars) Create testfolder with the following file: test_pmr.cpp (CompilerExplorer) #include <iostream> #include <memory_resource> int main() { std::pmr::string str = "Hello World!"; std::cout << str << std::endl; } Compile using the following command: g++ -std=c++20 test_pmr.cpp -s -o test_pmr When I follow this I get this error: test_pmr.cpp: In function β€˜int main()’: test_pmr.cpp:6:15: error: β€˜string’ is not a member of β€˜std::pmr’; did you mean β€˜std::string’? 6 | std::pmr::string str = "Hello World!"; | ^~~~~~ In file included from /usr/lib/gcc/x86_64-pc-cygwin/11/include/c++/iosfwd:39, from /usr/lib/gcc/x86_64-pc-cygwin/11/include/c++/ios:38, from /usr/lib/gcc/x86_64-pc-cygwin/11/include/c++/ostream:38, from /usr/lib/gcc/x86_64-pc-cygwin/11/include/c++/iostream:39, from test_pmr.cpp:1: /usr/lib/gcc/x86_64-pc-cygwin/11/include/c++/bits/stringfwd.h:79:33: note: β€˜std::string’ declared here 79 | typedef basic_string<char> string; | ^~~~~~ test_pmr.cpp:8:18: error: β€˜str’ was not declared in this scope; did you mean β€˜std’? 8 | std::cout << str << std::endl; | ^~~ | std EDIT2: It works using only MSYS with static linking: g++ -std=c++20 -static-libgcc -static-libstdc++ test_pmr.cpp -s -o test_pmr So the problem seems to lie in an incorrect stdlib configuration that ships with cygwin.
To use anything in the std::pmr namespace, it looks like you need to add -D_GLIBCXX_USE_CXX11_ABI to your general compiler flags. I got a clean and successful compile and execute with g++ -std=c++20 -Wall -Wextra -Werror -D_GLIBCXX_USE_CXX11_ABI test_pmr.cpp -s -o test_pmr.exe
73,365,661
73,365,723
Systematic approach of how to think about operator overloading
I'm learning how to do operator overloading and trying to come up with a systematic approach of how to know number of arguments an overloaded operator should take in and if the function should be constant. I know the system is not perfect and doesn't catch all the edge cases, but I'm thinking that will work itself out with some logical thinking in the end. What I'm looking for is if this systematic approach is catching the majority of cases, or am I missing something important? Systematic approach Important: Think logically through the entire process regarding if the input paramters can be const, * or &. Is the operator overloader a member function and NOT a stream?* It should take 1 argument which is the value/object to the right of the operator, UNLESS it is a unary operator then it should take 0 arguments. Does it alter the class object? If it does, add const to the end of it. Is the operator overloader a member function and ALSO a stream?* It should take 2 arguments, first a reference to the stream object and secondly (most likely) a reference to the class object. Does it alter the class object? If it does, add const to the end of it. Is the operator overloader NOT a member function?* In that case it should take 2 arguments which is the value/object to the left and right of the operator, UNLESS it is a unary operator then it should take 1 argument. No const at the end needed. Below is the header file that I based the system on. Vector.h #pragma once #include <iostream> class Vector { public: Vector(double x = 0.0, double y = 0.0); Vector& operator+=(Vector const& other); Vector& operator-=(Vector const& other); Vector& operator*=(double other); Vector& operator/=(double other); Vector operator-() const; bool operator==(Vector const& other) const; bool operator!=(Vector const& other) const; double operator*(Vector const& rhs) const; double length() const; friend std::ostream& operator<<(std::ostream& os, Vector const& other); friend std::istream& operator>>(std::istream& is, Vector& other); private: double x; double y; }; Vector operator+(Vector const& lhs, Vector const& rhs); Vector operator-(Vector const& lhs, Vector const& rhs); Vector operator*(Vector const& lhs, double rhs); Vector operator*(double lhs, Vector const& rhs); Vector operator/(Vector const& lhs, double rhs);
You got one thing wrong: friend std::ostream& operator<<(std::ostream& os, Vector const& other); You say this is written with two explicit arguments "because one of them is a stream." But actually it takes two explicit arguments because the friend keyword on the front implies this is a free function, not a member function. So it's covered by your third rule, and your second rule should be deleted entirely.
73,365,803
73,381,619
Error when including struct in a header file C++ "cannot overload functions distinguished by return type alone"
I have the following structures that work fine when included in a single main.cpp file. But, when I try to move things to a header.h I get an error. An example, main.cpp with full definitions (before moved to header.h file): using namespace std; static const int nx = 10; static const int ny = 10; struct cplx_buffer { fftw_complex* a; int rows; int cols; fftw_complex& operator()(int i, int j) const { return a[i * cols + j]; } }; cplx_buffer my_fftw_allocate_cplx(int x, int y) { return cplx_buffer{ fftw_alloc_complex(x * y), x, y }; } void print_matrix(cplx_buffer const& m) { std::cout << std::fixed << std::setprecision(2); for (int i = 0; i < m.rows; i++) { for (int j = 0; j < m.cols; j++) { std::cout << std::setw(16) << std::complex<double> { m(i, j)[0], m(i, j)[1] }; } std::cout << '\n'; } std::cout << '\n'; } int main(){ cplx_buffer outY = my_fftw_allocate_cplx((ny+1), nx); //stuff } Then my attempt of dividing things to header.h, header.cpp, and main.cpp files as the following: header.h using namespace std; static const int nx = 10; static const int ny = 10; struct cplx_buffer { fftw_complex* a; int rows; int cols; fftw_complex& operator()(int i, int j) const { return a[i * cols + j]; } }; void print_matrix(cplx_buffer const& m); cplx_buffer my_fftw_allocate_cplx(int x, int y); header.cpp looks like: #include "header.h" using namespace std; struct cplx_buffer { fftw_complex* a; int rows; int cols; fftw_complex& operator()(int i, int j) const { return a[i * cols + j]; } }; cplx_buffer my_fftw_allocate_cplx(int x, int y) { return cplx_buffer{ fftw_alloc_complex(x * y), x, y }; } //ERROR void print_matrix(cplx_buffer const& m) { std::cout << std::fixed << std::setprecision(2); for (int i = 0; i < m.rows; i++) { for (int j = 0; j < m.cols; j++) { std::cout << std::setw(16) << std::complex<double> { m(i, j)[0], m(i, j)[1] }; } std::cout << '\n'; } std::cout << '\n'; } The Main.cpp is: #include "header.h" using namespace std; int main(){ cplx_buffer outY = my_fftw_allocate_cplx((ny+1), nx); //stuff } The error comes from the header.cpp file in line: cplx_buffer my_fftw_allocate_cplx(int x, int y) { return cplx_buffer{ fftw_alloc_complex(x * y), x, y }; } //ERROR The full error message: cannot overload functions distinguished by return type alone
As someone in the comments suggested, the solution was to only define my struct in the header.h file and not to redefine it again in the header.cpp file.
73,365,808
73,366,719
Shared pointer to a const object thread safety
A thread holds a shared_ptr to a const map object. This shared_ptr is occasionally updated by another thread. This shared_ptr could also be read by different threads. Code snippet: class SharedPointerHolder { private: shared_ptr<const map<int, string>> sptr_; public: SharedPointerHolder() : sptr_(make_shared<const map<int, string>>()) {}; // new_sptr is guaranteed to be a valid pointer. void UpdateSharedPointer(shared_ptr<const map<int, string>>&& new_sptr) { if (!new_sptr) { return; } sptr_ = move(new_sptr); } void ReadSharedPointer() { // Since only UpdateSharedPointer() updates sptr_, it is guaranteed that sptr_ will always be valid. Still just in case, I have added this "if". if (!sptr_) { return; } local_sptr = sptr_; // Read the map object pointed by the local_sptr and perform some operations. } } UpdateSharedPointer() and ReadSharedPointer() can be called by different threads, but UpdateSharedPointer() will always be called after a certain time period, which ensures that the shared_ptr is not updated by two different threads at the same time. My question is: Does the sptr_ need to be protected by a lock? From what I read, a lock is required to protect the data pointed by the shared_ptr, but not for reading and updating the shared_ptr. Since in my case, the data is always const, I don't think a lock is required. It is possible that the private sptr_ is updated while we are in ReadSharedPointer(), but I am not concerned about that situation since I am fine working on a stale data. Let's say if UpdateSharedPointer() is not necessarily invoked after certain time period and multiple threads might be contending to update the sptr_ at the same time. Would I require a lock then? I understand that this might depend on whether my program can tolerate reading stale data, but is there any other race condition that I should be aware of? Use case: I am fine reading a stale map that was pointed by sptr_, in case sptr_ is updated by another thread. The most important thing that I am worried about is data corruption. Thanks!
Yes, access to sptr_ needs to be synchronized. Only modification of the shared_ptr's control block is atomic. Modification of the shared_ptr itself is not. If a single shared_ptr object is shared across threads then it will generally need some form of synchronization. Consider this logical diagram of multiple shared_ptrs sharing ownership of a single object: shared_ptr p1 shared_ptr p2 shared_ptr p3 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ control_block_ptr β”‚ β”‚ control_block_ptr β”‚ β”‚ control_block_ptr β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜ β””β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ control block β–Ό β–Ό β–Ό owned object β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ β”‚ β”‚ object_ptr β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Ίβ”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ strong_ref_count β”‚ β”‚ β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ β”‚ β”‚ weak_ref_count β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ If p3 is assigned to, then its control_block_ptr gets overwritten to point to the control block of the shared_ptr on the right-hand side of the assignment. This is a member of the shared_ptr itself, so this modification is not thread-safe. If any other thread is accessing p3 at the same time you will have a data race, and the behavior of your program becomes undefined. On the other hand, if you make a copy of p2 in thread A at the same time you assign to p3 in thread B, then that will be safe. Both will need to modify the strong_ref_count in their shared control block (the copy of p2 needs to increment it, and p3 needs to decrement it), but that ref count modification will be done atomically. You are guaranteed to get the correct result and no data race will occur.
73,366,157
73,438,040
Integrating X3Daudio with XAudio2
I am currently struggling with implementing 3D positional sound with XAudio2 library. I somehow managed to got it working when listener's and source's position are exactly 0.0f on all axis. When I move listener or source even a little bit, sound is no longer heard but is still playing. What am I missing here? Thanks :) uint32_t sourceInputChannels = 2; uint32_t masterInputChannels = 8; float* outputMatrix = new float[masterInputChannels * sourceInputChannels]; // Listener X3DAUDIO_LISTENER listener{}; listener.Position = { 0.0f, 0.0f, 0.0f }; listener.Velocity = { 0.0f, 0.0f, 0.0f }; listener.OrientFront = { 1.0f, 0.0f, 0.0f }; listener.OrientTop = { 0.0f, 0.0f, 1.0f }; // Emitter X3DAUDIO_EMITTER sourceEmitter{}; sourceEmitter.ChannelCount = 1; sourceEmitter.CurveDistanceScaler = FLT_MIN; sourceEmitter.Position = { 0.0f, 0.0f, 0.0f }; sourceEmitter.Velocity = { 0.0f, 0.0f, 0.0f }; sourceEmitter.OrientFront = { 1.0f, 0.0f, 0.0f }; sourceEmitter.OrientTop = { 0.0f, 0.0f, 1.0f }; sourceEmitter.ChannelRadius = 2.0f; sourceEmitter.InnerRadius = 2.0f; sourceEmitter.InnerRadiusAngle = X3DAUDIO_PI / 4.0f; X3DAUDIO_DSP_SETTINGS dspSettings{}; dspSettings.SrcChannelCount = sourceEmitter.ChannelCount; // 1 // 8 * 2, OUTPUT_CHANNELS is also present in CreateMasteringVoice dspSettings.DstChannelCount = OUTPUT_CHANNELS * sourceVoiceDetails.InputChannels; dspSettings.pMatrixCoefficients = outputMatrix; // Calculating X3DAudioCalculate(g_CealContext->X3DInstance, &listener, &sourceEmitter, X3DAUDIO_CALCULATE_MATRIX | X3DAUDIO_CALCULATE_DOPPLER | X3DAUDIO_CALCULATE_LPF_DIRECT | X3DAUDIO_CALCULATE_REVERB, &dspSettings); sourceVoice->SetOutputMatrix(g_CealContext->XMasterVoice, sourceInputChannels, masterInputChannels, outputMatrix); delete[] outputMatrix;
Okay, thanks to @chuck-walbourn I managed to get it working. The problem was that X3DAUDIO_EMITTER's member CurveDistanceScaler was set to FLT_MIN instead of some not-so-small value. Weird thing is I was following official Microsoft documention How to integrate X3DAudio with XAudio2 and the example code uses FLT_MIN, so I do not really understand what is going on.
73,366,837
73,367,346
Removing selected child elements in a XML file C++
I'm using tinyxml2. I have xml file with many elements on one node. My xml file: <city> <school> <class> <boy name="Jose"> <age>14</age> </boy> <boy name="Jim"> <age>15</age> </boy> <boy name="Mike"> <age>13</age> </boy> <boy name="Ben"> <age>14</age> </boy> <boy name="Eddy"> <age>14</age> </boy> <boy name="Jim"> <age>16</age> </boy> </class> </school> </city> For example, I have to remove the last three boys. I wrote this, but it don't work. void cropData(char *titlecity) { tinyxml2::XMLNode *city = nullptr; tinyxml2::XMLNode *school = nullptr; tinyxml2::XMLNode *class = nullptr; tinyxml2::XMLError result; tinyxml2::XMLDocument doccity; doccity.LoadFile(titlecity); tinyxml2::XMLNode* root = doccity.FirstChild(); if(root == nullptr) std::cout << "Cannot open file" << std::endl; city = doccity.FirstChildElement("city"); assert(city); school = city->FirstChildElement("school"); assert(school); class = school->FirstChildElement("class"); assert(class); int i = 0; for (tinyxml2::XMLElement *boy = class->FirstChildElement("boy"); boy; boy = boy->NextSiblingElement("boy")) { if(i>3) { boy->Parent()->DeleteChild(boy); } i++; } doccity.SaveFile("DeleteAttribute_demo_file.txt"); } This code does not change file. I'm really sorry, if my english is bad.
You have two errors in that code. One is a syntax error and the other is a logical error. The syntax error is that you can't name a variable "class" because "class" is a reserved word in C++. The logical error is that your for loop is iterating over elements by incrementing using the element's NextSiblingElement getter function; however, once you delete an element its next element will no longer be valid. See below: void cropData(tinyxml2::XMLDocument& doccity) { auto* city = doccity.FirstChildElement("city"); auto* school = city->FirstChildElement("school"); auto* class_ = school->FirstChildElement("class"); int i = 0; auto* boy = class_->FirstChildElement("boy"); while (boy != nullptr) { auto next = boy->NextSiblingElement("boy"); if (i > 3) { boy->Parent()->DeleteChild(boy); } boy = next; ++i; } doccity.SaveFile("DeleteAttribute_demo_file.txt"); } int main() { static const char* xml = "<?xml version=\"1.0\"?>" "<city>" " <school>" " <class>" " <boy name=\"Jose\">" " <age>14</age>" " </boy>" " <boy name=\"Jim\">" " <age>15</age>" " </boy>" " <boy name=\"Mike\">" " <age>13</age>" " </boy>" " <boy name=\"Ben\">" " <age>14</age>" " </boy>" " <boy name=\"Eddy\">" " <age>14</age>" " </boy>" " <boy name=\"Jim\">" " <age>16</age>" " </boy>" " </class>" " </school>" "</city>"; tinyxml2::XMLDocument doc; doc.Parse(xml); cropData(doc); }
73,366,933
73,366,971
What does "+" mean in cpp lambda declaration "auto fun1 = +[](){};"
I've seen in stackoverflow, people write lambda like this: int main() { auto f1 = +[](){}; auto f2 = [](){}; return 0; } (1) What does the + acturelly do in f1 expression? I tried to add capture, then f1 doesn't compile, but the error is not readable to me: auto f1 = +[=](){}; // fail to compile auto f2 = [=](){}; The error is: invalid argument type '(lambda at .\xxx.cpp:4:16)' to unary expression auto f1 = +[=](){}; (2) What does this error indicate? Thanks.
A lambda has a compiler-generated type. If you just assign the lambda as-is to an auto variable, then the auto variable's type will be deduced as the lambda's generated type. A non-capturing lambda is implicitly convertible to a plain function pointer. By placing + in front of the lambda, the lambda is explicitly converted to a function pointer, and then the auto variable's type will be deduced as the function pointer type, not the lambda type. A capturing lambda cannot be converted to a function pointer at all, which is why you get the compiler error.
73,367,039
73,367,074
Allocating memory thorugh malloc for std::string array not working
I'm having trouble allocating memory on the heap for an array of strings. Allocating with new works but malloc segfaults each time. The reason I want to use malloc in the first place is that I don't want to call the constructor unnecessarily. This works fine std::string* strings = new std::string[6]; This doesn't std::string* strings = (std::string *)malloc(sizeof(std::string[6])); One thing I've noticed is that the first variant (using new) allocates 248 bytes of memory while the second allocates only 240. This 8 byte difference is constant no matter the size of the array from what I've gathered and I cannot find what the source of the difference is. Here's the whole code that segfaults. #include <iostream> void* operator new(size_t size) { std::cout << size << std::endl; return malloc(size); } void* operator new [](size_t size) { std::cout << size << std::endl; return malloc(size); } int main() { std::string* strings = new std::string[6]; strings = (std::string *)malloc(sizeof(std::string[6])); strings[0] = std::string("test"); return 0; } Another thing I've noticed is that the above code seems to work if I use memset after malloc to set all of the bytes I allocated with malloc to 0. I don't understand where the 8 byte difference comes from if this works and also why this variant works at all. Why would it work just because I set all of the bytes to 0?
malloc() only allocates raw memory, but it does not construct any objects inside of that memory. new and new[] both allocate memory and construct objects. If you really want to use malloc() to create an array of C++ objects (which you really SHOULD NOT do!), then you will have to call the object constructors yourself using placement-new, and also call the object destructors yourself before freeing the memory, eg: std::string* strings = static_cast<std::string*>( malloc(sizeof(std::string) * 6) ); for(int i = 0; i < 6; ++i) { new (&strings[i]) std::string; } ... for(int i = 0; i < 6; ++i) { strings[i].~std::string(); } free(strings); In C++11 and C++14, you should use std::aligned_storage to help calculate the necessary size of the array memory, eg: using string_storage = std::aligned_storage<sizeof(std::string), alignof(std::string)>::type; void *buffer = malloc(sizeof(string_storage) * 6); std::string* strings = reinterpret_cast<std::string*>(buffer); for(int i = 0; i < 6; ++i) { new (&strings[i]) std::string; } ... for(int i = 0; i < 6; ++i) { strings[i].~std::string(); } free(buffer); In C++17 and later, you should use std::aligned_alloc() instead of malloc() directly, eg: std::string* strings = static_cast<std::string*>( std::aligned_alloc(alignof(std::string), sizeof(std::string) * 6) ); for(int i = 0; i < 6; ++i) { new (&strings[i]) std::string; } ... for(int i = 0; i < 6; ++i) { strings[i].~std::string(); } std::free(strings);
73,367,127
73,367,168
std::binary_search curious issue with char array
So I i'm implementing a rot13 for fun const char lower[] = "abcdefghijklmnopqrstuvwxyz"; int main() { char ch = 'z'; if (std::binary_search(std::begin(lower), std::end(lower), ch)) { std::cout << "Yep\n"; } else { std::cout << "Nope\n"; } } This outputs nope. Any other character outputs yes.
Note that a c-string is not ordered increasingly unless empty (as it ends with '\0'). If you fix it to pass the preceding iterator (that points past 'z', not '\0'), it works: #include <iostream> #include <algorithm> const char lower[] = "abcdefghijklmnopqrstuvwxyz"; int main() { char ch = 'z'; if (std::binary_search(std::begin(lower), std::end(lower) - 1, ch)){ std::cout << "Yep\n"; } else { std::cout << "Nope\n"; } }
73,367,205
73,367,587
Why cpp std::function can hold capture-lambda, while function pointer cannot?
I've got this code snippet: int x = 3; auto fauto = [=](){ cout<<'x'; }; function<void()> func{fauto}; func(); void (*rawPf)() = fauto; // fail to compile rawPf(); I knew the syntax that only non-capture lambda can be assigned to function pointer. But: (1) Why std::function can hold capture-lambda? (2) as both std::function and function pointers are callable, what's the core difference that makes std::function able to hold capture-lambda, while function pointer cannot? Any detailed explanation on language design for this?
Why can a function pointer not hold a lambda with a capture : because a Lambda is NOT a function ,it's an object! Why can a lambda without a capture be converted to a function pointer ? A Lambda is just an ordinairy object (a piece of data) of a compiler generated class (with a unique classname that only the compiler knows) with a function-operator member (i.e. auto operator() ( ??? )) that the compiler defines for you with the parameter definitions (if any) you provide. The data-members of a lambda-object are defined by the capture-list and/or usage of variables of its enclosing scope. All non-static member functions when called on an object get a implicit hidden argument called this. This is also the case when you 'call' the lambda. Now ,when you don't capture something ,the lambda has no data (empty class) and the compiler doesn't have to generate an implicit this pointer for the call ,which makes the function operator just like an ordinairy function and the compiler can convert it to function pointer. So it not the lambda that is converted to a function-pointer ,it's the lambda's function-operator that is converted. Why can std::function hold both : because it's a template and with templates and specializations you can do almost anything.
73,367,255
73,367,326
How to pass c++ function/lambda as none-type parameter to a typedef/using template?
I've got a need to write RAII wrapper functions/classes to some C library. I know we can use a smart pointer and pass a deleter function, like this: FILE* pf = fopen("NoSuchFile", "r"); shared_ptr<FILE> p1{pf, fclose}; // OK. But, for more complex scenarios other than fopen()/fclose(), I don't wish to write code to pass deleter functions each time I declare such a wrapper. Especially if we decide to update/replace the deleter function, a lot of code has to be changed. What I wish to have, is something like this (to make code cleaner): template<typename T, fn ???? > // how to specify this "fn" parameter? using sp_with_deleter = shared_ptr<T, fn>; Then in client code, I can do this: using smartFp = sp_with_deleter<FILE*, fclose>; ... FILE* f1 = fopen(xxx); FILE* f2 = fopen(yyy); smartFp sf1(f1); // no need to pass deleter function. smartFp sf2(f2); ... Is there a way to achieve this sp_with_deleter type?
What you propose will NOT work for std::shared_ptr, simply because the deleter is not a template parameter of std::shared_ptr. So, you can't specify a deleter in a typedef/using statement when aliasing a std::shared_ptr type. It can only be specified in the std:::shared_ptr's constructor. If you don't want to specify a deleter on every std::shared_ptr variable declaration, then you will need to write a wrapper function instead, eg: auto make_smartFp(FILE* f) { return std::shared_ptr<FILE>{f, &fclose}; // alternatively: auto deleter = [](FILE* f){ fclose(f); }; return std::shared_ptr<FILE>{f, deleter}; } ... auto sf1 = make_smartFp(fopen(xxx)); // no need to pass deleter function. auto sf2 = make_smartFp(fopen(yyy)); ... You can do something similar for std::unique_ptr, too. Even though the type of the deleter is a template argument, when using a function or lambda as the deleter then the actual deleter must be passed in the constructor, eg: auto make_smartFp(FILE* f) { return std::unique_ptr<FILE, decltype(&fclose)>{f, &fclose}; // alternatively: auto deleter = [](FILE *f){ fclose(f); }; return std::unique_ptr<FILE, decltype(deleter)>{t, deleter}; } ... smartFp sf1(fopen(xxx)); // no need to pass deleter function. smartFp sf2(fopen(yyy)); ... Otherwise, you can instead make the deleter be a default-constructable class type, then you don't need to pass it in a parameter to std::unique_ptr's constructor, eg: struct FILE_deleter { void operator()(FILE *f) { fclose(f); } }; using smartFp = std::unique_ptr<FILE, FILE_deleter>; ... smartFp sf1(fopen(xxx)); // no need to pass deleter function. smartFp sf2(fopen(yyy)); ...
73,367,535
73,396,399
How to instruct Google Test to expect std::abort()?
I am using Google Test on code I expect to fail. As part of this failure the code calls a custom assert macro, which contains std::abort(). Unfortunately Google Test's EXPECT_EXIT() is not "catching" the std::abort(). This is a self-contained example to emulate what I'm trying to achieve: // A placeholder for my assert macro void MyFunction() { std::abort(); } TEST(TestGroup1, TestName) { EXPECT_EXIT(MyFunction(), ::testing::ExitedWithCode(SIGABRT), ".*"); } I get this failure output: Death test: MyFunction() Result: died but not with expected exit code: Terminated by signal 6 (core dumped) Actual msg: [ DEATH ] Is this possible to achieve?
I needed to use ::testing::KilledBySignal(SIGABRT)
73,367,767
73,368,726
how to get `compile_commands.json` right for header-only library using cmake?
I'm learning CMake and clangd, but I can't find a way to make CMake generate a proper compile_commands.json for clangd to parse third party libraries. Here's what I've tried: add_library(date_fmt INTERFACE) target_include_directories( date_fmt INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> $<INSTALL_INTERFACE:include>) target_sources( date_fmt INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>$<INSTALL_INTERFACE:include>/date_fmt/date_fmt.hpp ) target_link_libraries(date_fmt INTERFACE date) target_link_libraries(date_fmt INTERFACE fmt)
The issue is that compile_commands.json is only used for things that are actually being compiled. Since your CMakeLists.txt only creates an INTERFACE library and nothing uses it, there's no need to generate the compilation database. Add something like this to your CMakeLists.txt add_executable(smoke_test smoke_test.cpp) target_link_libraries(smoke_test date_fmt) smoke_test.cpp can be as simple as int main() { return 0; }, just something that'll compile.
73,367,843
73,368,150
How to block a message using WH_GETMESSAGE hook?
In the CBTProc hook, there's: return 0 to allow the msg, 1 to deny. What about the WH_GETMESSAGE hook? How I could 'block' a message from being executed? In this example: LRESULT CALLBACK GetMsgProc(_In_ int nCode, _In_ WPARAM wParam, _In_ LPARAM lParam ) { if (nCode < 0) return CallNextHookEx(nullptr, nCode, wParam, lParam); MSG* pMsg = (MSG*)lParam; if ((pMsg->message == WM_KEYDOWN) && (wParam == PM_REMOVE)) { } return CallNextHookEx(g->getmsgproc, nCode, wParam, lParam); } When the code gets inside of the block if ((pMsg->message == WM_KEYDOWN), how i could deny it from executing the WM_KEYDOWN msg? Do I need to replace pMsg->message with something else or what? Inside of both return CallNextHookEx(... the first parameter must be nullptr?
What about the WH_GETMESSAGE hook? How I could 'block' a message from being executed? You can't block the message. Once all hook procedures in the chain have exited, the message is then passed to the original caller of (Get|Peek)Message(). There is no option to avoid that. Do I need to replace pMsg->message with something else or what? Yes, you can modify the message. For instance, you could set its message field to WM_NULL so the caller will effectively ignore it. Inside of both return CallNextHookEx(... the first parameter must be nullptr? It doesn't really matter what you set it to. In very old versions of Windows (Win9x/ME), it had to be set to the actual HHOOK, but that hasn't been true for a very long. Since NT4/Win2K, the parameter is completely ignored. So yes, setting it to nullptr is fine.
73,367,992
73,369,600
Why is ptrdiff_t signed?
If ptrdiff_t were unsigned, it would be able to refer to twice as many elements. On my machine PTRDIFF_MAX is expanded to 9223372036854775807i64, whereas ULLONG_MAX is 18446744073709551615Ui64. I know that these values are huge themselves, but if The type (ptrdiff_t)'s size is chosen so that it can store the maximum size of a theoretically possible array of any type. ref then doesn't making it unsigned make more sense?
If ptrdiff_t were unsigned, it would be able to refer to twice as many elements. That is not correct. Making a type unsigned does not magically increase the amount of information it can hold. Signed and unsigned integers of the same size have exactly the same number of different states. In the signed version, half the states represent negative numbers. And you do need negative numbers to handle the result of subtracting a pointer with a higher address value from one with a lower address value. For instance: int arr[42]; int* p1 = arr; int* p2 = arr + 42; auto diff = p1 - p2; // what should the result be?
73,368,382
73,369,311
zsh: bus error ./array_stack on using pointers to access the stack elements
the code run fine when I used the dot operator for accessing the elements of the stack. But on using pointers to access the stack structure, I was getting this error. zsh: bus error ./array_stack. Can anyone help me in resolving this.The code is as follows: #include<iostream> using namespace std; //implementing the stack using an array struct Stack{ int size;//size of the array int top;//points to the last element of the array int * arr; }; int IsEmpty(struct Stack *ptr){ if(ptr->top == -1){ return 1; } else{ return 0; } } int main(){ //one way of making the stack // struct Stack S; // S.size=43; // S.top=-1; // S.arr=(int *)malloc(S.size*sizeof(int)); //second way of making the stack struct Stack *S; S->size=54; S->top=-1; S->arr=(int *)malloc(S->size*sizeof(int)); if(IsEmpty(S)){ cout<<"The array is empty."; } return 0; }
EDIT: This question was originally tagged as C (not C++). I'm still not sure which way it will go. I will modify this answer to use C++ when it's clear. The problem is you're defining S as a pointer to a Stack, but you never tell it to point to anything. So S is pointing to somewhere in memory (you probably don't own), and the S->size = 54 is trying to modify the content of that memory by writing 54. The fact that the code is generating a "Bus Error" indicates that S actually contains a memory address that is outside of valid memory range. To fix it, S should be pointing at a stack: struct Stack myStack; // myStack is an actual stack struct Stack *S = &myStack; // a pointer to myStack Obviously this method creates a Stack that is uninitialised. A nice way to do this sort of thing is to make a function that creates a new Stack, initialises it, then returns a pointer to it: struct Stack *createStack( int capacity ) { assert( capacity > 0 ); struct Stack *new_stack = malloc( sizeof( struct Stack ) ); if ( new_stack != NULL ) { new_stack->size = capacity; new_stack->top = -1; new_stack->arr = malloc( capacity * sizeof( int ) ); // If we failed to allocate array memory: clean-up & return NULL if ( new_stack->arr == NULL ) { free( new_stack ); new_stack = NULL; } } return new_stack; } // Matching function to free a stack allocated by createStack() void freeStack( struct Stack *s ) { assert( s != NULL ); assert( s->arr != NULL ); free( s->arr ); // release the array part first free( s ); // release the struct itself } Then in your code, it can be called: struct Stack *s = createStack( 54 ); // ... freeStack( s ); // clean up when done
73,368,437
73,369,710
How to get the HWND of the taskbar MSTaskListWClass?
How i could retrieve the MSTaskListWClass hWnd? I mean the "Running applications" tool bar which shows the button of each window in the taskbar. I have tried to get it with: HWND mstask = FindWindow(L"MSTaskListWClass", NULL); DWORD err = GetLastError(); But mstask return null, err outputs 0
FindWindowW retrieves a handle to the top-level windows only. not for child windows. so need first search for parent window - "Shell_TrayWnd" and than use EnumChildWindows BOOL CALLBACK EnumChild(HWND hwnd, LPARAM lParam) { WCHAR name[32]; if (GetClassNameW(hwnd, name, _countof(name)) && !wcscmp(name, L"MSTaskListWClass")) { *(HWND*)lParam = hwnd; return FALSE; } return TRUE; } HWND GetMSTaskListW() { HWND hwnd = 0; if (HWND hWndParent = FindWindowW(L"Shell_TrayWnd", 0)) { EnumChildWindows(hWndParent, EnumChild, (LPARAM)&hwnd); } return hwnd; }
73,368,532
73,368,618
Get istream_iterator from ifstream
I tried to get an istream iterator from an ifstream, but failed... void Test_CH_3_1::set_up() { std::ifstream file_in("makefile-dependencies.dat"); typedef boost::graph_traits<Graph>::vertices_size_type size_type; size_type n_vertices; file_in >> n_vertices; // read in number of vertices if (file_in) { std::cout << n_vertices << std::endl; } std::istream_iterator<std::pair<size_type, size_type> > input_begin, input_end; input_begin=std::istream_iterator<std::pair<size_type, size_type> >(file_in); g_ = Graph(input_begin, input_end, n_vertices); } And I got below error: no match for "operator>>" (operand types are std::istream_iterator<std::pair<long unsigned int, long unsigned int> >::istream_type {aka std::basic_istream<char> and std::pair<long unsigned int, long unsigned int>)
The error message is quite clear. There is no operator>> defined for reading std::pair from a std::istream. Define one in your application code and all should be well. std::istream& operator>>(std::istream& in, std::pair<std::size_type, std::size_type>& p) { return in >> p.first >> p.second; }
73,368,541
73,645,782
get image dimension from blob column in MySQL database
I want to read image from a database, image column is a MYSQL_TYPE_BLOB type and I read column using this code. Currently, Blob image converted as a char * array //Get the total number of fields int fieldCount = mysql_num_fields(result); //Get field information of a row of data MYSQL_FIELD *fields = mysql_fetch_fields(result); while (m_row = mysql_fetch_row(result)) { for (int i = 0;i < fieldCount; ++i) { if (fields[i].type == MYSQL_TYPE_BLOB) { unsigned long length = mysql_fetch_lengths(result)[i]; char* buffer = new char[length + 1]; memset(buffer, 0x00, sizeof(buffer)); memcpy(buffer, m_row[i], length); } } } In order to do some tests on image, I should know the image dimension without writing image on disk and reading it again? Another way to read data from Mysql database is : res = stmt->executeQuery("MY QUERY TO DATABASE"); while (res->next()) { std::istream *blobData = res->getBlob("image"); std::istreambuf_iterator<char> isb = std::istreambuf_iterator<char>(*blobData); std::string blobString = std::string(isb, std::istreambuf_iterator<char>()); tempFR.image = blobString; blobData->seekg(0, ios::end); tempFR.imageSize = blobData->tellg(); std::istream *blobIn; char buffer[tempFR.imageSize]; memset(buffer, '\0', tempFR.imageSize); blobIn = res->getBlob("image"); blobIn->read((char*)buffer, tempFR.imageSize); } Notice: imageSize and length are the overall image size, for example 1000. Update#1: How image will be reconstruct meanwhile writing it to disk? In the first case it's possible to write the blob_image to disk via this codes: stringstream pic_name; pic_name << "car.jpeg"; ofstream outfile(pic_name.str(), ios::binary); outfile.write(buffer, length); and in the second ones: std::ofstream outfile ("car.jpeg",std::ofstream::binary); outfile.write (buffer, tempFR.imageSize); outfile.close(); In both cases image writed to disk correctly. But I want to find image dimension without writing it to disk and reading it again?
By decoding buffered image: length = mysql_fetch_lengths(result)[i]; buffer = new char[length + 1]; memset(buffer, 0x00, sizeof(buffer)); memcpy(buffer, m_row[i], length); matImg = cv::imdecode(cv::Mat(1, length, CV_8UC1, buffer), cv::IMREAD_UNCHANGED); At first, copy array to buffer, then convert it to a cv::Mat and finally decode it. It will be a cv::Mat image.
73,369,841
73,370,169
Move constructor for vec3 class
I'm trying to improve my cpp lately, and I want to write my own vec3 class to represent a 3D vector and point. I want it to hold 3 values of the same type and have some standard operations like addition and things... I'm trying to learn more about move semantics and I'd like to create a move constructor that would take 3 literal ints like this: vec3<int> a(1, 2, 3); But this shows me error that more than one instance of constructor matches the argument list. Here is my code: template <typename T> class vec3 { T x, y, z; // standard copy ctor vec3(T _x, T _y, T _z): x(_x), y(_y), z(_z) {} // move ctor for rvalue references like vec3(1, 2, 3) vec3(T &&_x, T &&_y, T &&_z): x(_x), y(_y), z(_z) {} vec3<T> operator+(const vec3<T> &vec) { // I don't want to create 3 int's just to copy them return vec3<T>(this.x + vec.x, this.y + vec.y, this.z + vec.z); } }; int main() { vec3<int> b(1, 2, 3); // more than one instance of constructor // "vec3<T>::vec3 [with T=int]" matches the argument list:C/C++(309) int x, y, z = 5; vec3<int> c(x, y, z); // OK, it matches copy ctor } I'd like to know if my understanding of copy ctors is correct. Can I use it for moving simple, temporary int values into functions? Or is move semantics only for more complex types like std::vector? Is my way of thinking about moving temporary values directly into constructor correct? I'd greatly appreciate help in this matter, and gladly read more about this topic. Any good articles with use cases would be helpful, as reading cpp reference doesn't help me a lot right now.
You didn't write a move constructor, nor a copy constructor. They would have to look like vec3(vec3 &&) and vec3(const vec3 &) respectively. You shouldn't write them manually if possible (including in this case), the compiler will generate them for you. The same applies to copy/move assignment, and to the destructor. Regarding your element-wise constructors, you have multiple options: Use only the first constructor: vec3(T _x, T _y, T _z), and remove the other one. Note that you forgot to move the elements; it should look like this: vec3(T _x, T _y, T _z): x(std::move(_x)), y(std::move(_y)), z(std::move(_z)) {} Moving scalar types is the same as copying them, but for more complex types (if you decide to use them with your vector), moving should be faster. Use the second constructor and remove the first, but then you also need 7 other constructors (23 total), to cover all combinations of const T & and T && parameter types. When the parameter type is T &&, you need to std::move it: vec3(const T &_x, const T &_y, const T &_z): x(_x), y(_y), z(_z) {} vec3(T &&_x, const T &_y, const T &_z): x(std::move(_x)), y(_y), z(_z) {} vec3(const T &_x, T &&_y, const T &_z): x(_x), y(std::move(_y)), z(_z) {} // And so on, 5 move constructors. But having to write so many constructors is not practical. You can replace them with a single template (look up "perfect forwarding"): template <typename A, typename B, typename C> vec3(A &&_x, B &&_y, C &&_z) : x(std::forward<A>(_x)), y(std::forward<B>(_y)), z(std::forward<C>(_z)) {} Despite those looking like the usual rvalue references, they're also forwarding references, meaning they can take both lvalues and rvalues. std::forward then acts as a conditional std::move, which only happens if you passed an rvalue (and the reference resolved to &&, instead of &). As for what option to choose: (2) is not practical. I would start with (1), since it's easier to write. If you decide it's not fast enough, you can replace it with (3). Note that you forgot to const-qualify your operator+. It should be: vec3<T> operator+(const vec3<T> &vec) const
73,369,864
73,370,292
Why does overloading operator< for std::tuple not seem to work in priority_queue?
Here is the MWE: #include <iostream> #include <tuple> #include <queue> using namespace std; bool operator<(tuple<int, int, int> lhs, tuple<int, int, int> rhs) { return get<1>(lhs) < get<1>(rhs); } int main() { priority_queue<tuple<int, int, int>> q; q.push(make_tuple(2, 5, 3)); q.push(make_tuple(2, 3, 3)); cout << get<1>(q.top()); return 0; } The weird part is that whether I type < or > in the sentence return get<1>(lhs) < get<1>(rhs);, the output is always 5. Why does this happen?
Your overload of operator< is not selected because it's in a different namespace than both std::priority_queue and std::tuple. It's not in the candidate set, so it is never even considered as an overload candidate. The search for a suitable overload happens in the namespace where the operator is called from, which is the namespace priority_queue lives in, i.e. std. Argument-dependent lookup causes an additional search in the namespaces of the arguments, but because tuple is also in the std namespace, that doesn't help either. There is no reason for the compiler to ever consider the global namespace at all. Instead, the standard library's definition of std::operator< for tuples is used. You can see that if you put your own implementation in a namespace std block: // !!!!!!!!!!!!!!!!!!!!!!!! // BAD SOLUTION, DO NOT USE // !!!!!!!!!!!!!!!!!!!!!!!! namespace std { bool operator<(tuple<int, int, int> lhs, tuple<int, int, int> rhs) { return get<1>(lhs) > get<1>(rhs); // Changed to > so we can see the difference. } } Now the output is 3. Your operator is now considered and takes precedence over the default one, because non-template functions come before template functions. But it is forbidden by the standard to put your own code into namespace std (with some small exceptions), so what to do? The solution is to pass a comparator functor explicitly: #include <iostream> #include <tuple> #include <queue> using namespace std; struct element_1_greater { bool operator()(tuple<int, int, int> lhs, tuple<int, int, int> rhs) { return get<1>(lhs) > get<1>(rhs); } }; int main() { priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, element_1_greater> q; q.push(make_tuple(2,5,3)); q.push(make_tuple(2,3,3)); cout << get<1>(q.top()) << '\n'; return 0; } Notice that we need to pass the second argument to priority_queue as well; you can shorten this with a typedef or using declaration of course.
73,370,346
73,370,439
How template argument deduction is performed in this example?
Consider the following example: template <class T> void f(const T&&) { std::cout << __PRETTY_FUNCTION__; }; int main(void){ const int *cptr = nullptr; f(std::move(cptr)); } Per [temp.deduct.call]/1: Template argument deduction is done by comparing each function template parameter type (call it P) that contains template-parameters that participate in template argument deduction with the type of the corresponding argument of the call (call it A) [..] and [temp.deduct.call]/3: If P is a cv-qualified type, the top-level cv-qualifiers of P's type are ignored for type deduction. If P is a reference type, the type referred to by P is used for type deduction. Considering the given paragraphs, I'm deducing the template argument for T to be int* as follows: P = const T&&, A = const int*; // replacing 'const T&&' with 'const T' P = const T, A = const int* T = int* // what's wrong with these steps? But when I compile this code with gcc and clang, it shows that the deduced T is const int* My Question: Why the deduced template argument is const int* and not int* as I expect?
Why the deduced template argument is const int* and not int* as I expect? The const in P = const T is a top level const and applies to T while the const in A = const int* is a low-level const meaning it does not apply to the pointer. This in turn means that you can't directly compare const T with const int* the way you have done. Therefore, T will be deduced as the simplest argument type const int* and the function parameter will be of type const int *const &&.
73,370,401
73,370,767
How to get int from a line of a text and add them together in c++?
Hi I have got an text file and inside writing: 15 7 152 3078 178 352 1 57 What I want to do is get the int's from first line, sum up the numbers and make it an integer. And than do it for the second line with another int. How can I do that with c++? Thanks for your help.
You can use stringstream to convert a string into integer. And to sum a vector of integer, use accumulate algorithm. You can pass a filename as first argument to the program, by default the program assume the filename as input.txt. Here is a complete program to demonstrate this. #include <iostream> #include <fstream> #include <sstream> #include <numeric> // for accumulate #include <vector> int main(int argc, char *argv[]) { std::string filename{"input.txt"}; if(argc > 1) { filename = argv[1]; } // open the input file std::ifstream inputFile(filename); if(!inputFile.is_open()) { std::cerr << "Unable to open " << filename << std::endl; return 1; } std::string line; // read the file line by line while(getline(inputFile, line)) { if(line.empty()) continue; std::stringstream ss(line); std::vector<int> v; int x; // extract the content as integer from line while(ss >> x) { v.push_back(x); } // add them all auto total = std::accumulate(v.begin(), v.end(), 0); std::cout << total << std::endl; } }
73,370,550
73,370,645
[[maybe_unused]] for a function
I don't quite understand when [[maybe_unused]] on a function itself could be useful. By reading the paper, it only said the attribute may be applied to the declaration of a function. My question is that if it implies compiler will raise warning on an unused function, then for any public header of a library, everything should have the attribute to avoid warning as users might only use parts of the library. Is my understanding correct? Thank you.
Inspired from here: namespace { [[maybe_unused]] void foo() {} void bar() {} } int main() {} Functions declared in the unnamed namespace can only be used in this translation unit, hence the compiler can warn when the functions are not used. And indeed gcc warns for bar (error because of -Wall -Werror) but due to [[maybe_unused]] not for foo : <source>:5:10: error: 'void {anonymous}::bar()' defined but not used [-Werror=unused-function] 5 | void bar() {} | ^~~ Live The original example in the page linked above is a little more motivating, as it uses conditional compilation where depending on some symbols being set a function is used or not.
73,370,956
73,372,017
Sleek way to use template function as function argument?
What I really want to do is to compare the performance of different algorithms which solve the same task in different ways. Such algorithms, in my example called apply_10_times have sub algorithms, which shall be switchable, and also receive template arguments. They are called apply_x and apply_y in my example and get int SOMETHING as template argument. I think the solution would be to specify a template function as template parameter to another template function. Something like this, where template_function is of course pseudo-code: template<int SOMETHING> inline void apply_x(int &a, int &b) { // ... } template<int SOMETHING> inline void apply_y(int &a, int &b) { // ... } template<template_function APPLY_FUNCTION, int SOMETHING> void apply_10_times(int &a, int &b) { for (int i = 0; i < 10; i++) { cout << SOMETHING; // SOMETHING gets used here directly as well APPLY_FUNCTION<SOMETHING>(a, b); } } int main() { int a = 4; int b = 7; apply_10_times<apply_x, 17>(a, b); apply_10_times<apply_y, 19>(a, b); apply_10_times<apply_x, 3>(a, b); apply_10_times<apply_y, 2>(a, b); return 0; } I've read that it's not possible to pass a template function as a template parameter, so I can't pass APPLY_FUNCTION this way. The solution, afaik, is to use a wrapping struct, which is then called a functor, and pass the functor as a template argument. Here is what I got with this approach: template<int SOMETHING> struct apply_x_functor { static inline void apply(int &a, int &b) { // ... } }; template<int SOMETHING> struct apply_y_functor { static inline void apply(int &a, int &b) { // ... } }; template<typename APPLY_FUNCTOR, int SOMETHING> void apply_10_times(int &a, int &b) { for (int i = 0; i < 10; i++) { cout << SOMETHING; // SOMETHING gets used here directly as well APPLY_FUNCTOR:: template apply<SOMETHING>(a, b); } } This approach apparently works. However, the line APPLY_FUNCTOR:: template apply<SOMETHING>(a, b); looks rather ugly to me. I'd prefer to use something like APPLY_FUNCTOR<SOMETHING>(a, b); and in fact this seems possible by overloading the operator(), but I couldn't get this to work. Is it possible and if so, how?
As it is not clear why you need APPLY_FUNCTION and SOMETHING as separate template arguments, or why you need them as template arguments at all, I'll state the obvious solution, which maybe isn't applicable to your real case, but to the code in the question it is. #include <iostream> template<int SOMETHING> inline void apply_x(int a, int b) { std::cout << a << " " << b; } template<int SOMETHING> inline void apply_y(int a, int b) { std::cout << a << " " << b; } template<typename F> void apply_10_times(int a, int b,F f) { for (int i = 0; i < 10; i++) { f(a, b); } } int main() { int a = 4; int b = 7; apply_10_times(a, b,apply_x<17>); apply_10_times(a, b,apply_y<24>); } If you want to keep the function to be called as template argument you can use a function pointer as non-type template argument: template<void(*F)(int,int)> void apply_10_times(int a, int b) { for (int i = 0; i < 10; i++) { F(a, b); } } int main() { int a = 4; int b = 7; apply_10_times<apply_x<17>>(a, b); apply_10_times<apply_y<24>>(a, b); } In any case I see no reason to have APPLY_FUNCTION and SOMETHING as separate template arguments. The only gain is more complex syntax which is exactly what you want to avoid. If you do need to infer SOMETHING from an instantiation of either apply_x or apply_y, this is also doable without passing the template and its argument separately, though again you'd need to use class templates rather than function templates. PS: Ah, now I understand what you mean. Yes, apply_10_times() also uses SOMETHING directly. Sorry, I simplified the code in the question too much. As mentioned above. This does still not imply that you need to pass them separately. You can deduce SOMETHING from a apply_x<SOMETHING> via partial template specialization. This however requires to use class templates not function templates: #include <iostream> template <int SOMETHING> struct foo {}; template <int X> struct bar {}; template <typename T> struct SOMETHING; template <template <int> class T,int V> struct SOMETHING<T<V>> { static constexpr int value = V; }; int main() { std::cout << SOMETHING< foo<42>>::value; std::cout << SOMETHING< bar<42>>::value; }
73,371,120
73,372,305
How to do action when QStringListModel changed?
Basically, I have 2 listviews and when I drag&drop one listview to another one,I want to execute a sql query. I tried to override dropEvent but it does not getting called. However the drop action happening.(I go through the model data with for loop and I can print the items in the model) Why the dropEvent not called when drop happens ? protected: void mousePressEvent(QMouseEvent *event)override; void mouseMoveEvent(QMouseEvent *event)override; void dragEnterEvent(QDragEnterEvent *event)override; void dragMoveEvent(QDragMoveEvent *event)override; void dragLeaveEvent(QDragLeaveEvent *event)override; void dropEvent(QDropEvent *event)override; void InformationMusteriDialog::dropEvent(QDropEvent *event) { QMessageBox::information(this,"x","xss"); event->acceptProposedAction(); }
I solve the problem if anyone curious about this problem. I thought I can connect QStringListModel with SIGNAL and SLOT. connect(ui->listViewMusteri->model(),&QAbstractItemModel::dataChanged,this, &InformationMusteriDialog::listViewMusteriChanged); connect(ui->listViewToplam->model(),&QAbstractItemModel::dataChanged,this, &InformationMusteriDialog::listViewToplamChanged); When model's data is changed, you can do something. (btw I'm keep searching about DnD methods.)
73,371,795
73,372,124
Linker error LNK2005/1169 when using smart pointer C++
So I'm separating class definition and implementation. Platform: Windows x64 Compiler: MSVC IDE: VS 2022 Error "resolves" when I use inline keyword before smart pointer, but I want to understand the problem- Error codes: "class std::unique_ptr<class Window,struct std::default_delete<class Window> > loaderWindow" (?loaderWindow@@3V?$unique_ptr@VWindow@@U?$default_delete@VWindow@@@std@@@std@@A) already defined" Removed all code unrelated to error. Header file: #pragma once class Window { public: Window() noexcept; }; auto loaderWindow = std::make_unique<Window>(); Source file: Window::Window() noexcept { MessageBox(NULL, L"Ctor called", L"OK", MB_OK); }
You include your header file in more than one source files. This is why you see this error message. Remove the definition of the global variable from your header file, or include it in one source file only.
73,371,835
73,371,898
C++ alternatives for libjpeg?
Are there any alternatives for libjpeg? This library requires complicated installation routines, but I cannot find another jpeg library. Those I managed to find (such as CImg) require libjpeg anyway.
The answer is yes: stb_image is a single-file, header-only image loader that supports most common JPEG files.
73,372,184
73,372,501
C++ sockets, how to send hexadecimal with asio?
I need help, I'm trying to send this data in hexadeciamal, but always the packet_byte.size() and date() says: the express needs to have type of calsse, but has the type "char". I dont now what i need do, if anyone can help me.and if you can indicate what to study to understand this error Thank you. #include <iostream> #define ASIO_STANDALONE #ifdef _WIN32 #define _WIN32_WINNT 0x0A00 #endif #include <asio.hpp> #include <asio/ts/buffer.hpp> #include <asio/ts/internet.hpp> int main() { asio::error_code ec; //pega erros especificos //Cria o "context" asio::io_context context; //Pega o endereΓ§o no qual estamos conectando1 asio::ip::tcp::endpoint endpoint(asio::ip::make_address("ip", ec), 15559); //Cria o socket, o context ira entregar a implementaΓ§ao asio::ip::tcp::socket socket(context); //Diz ao socket para tentar se conectar socket.connect(endpoint, ec); if (!ec) { std::cout << "Conectado!" << std::endl; } else { std::cout << "Falha de conecxao com o endereΓ§o: \n" << ec.message()/*pega mensagem associada ao erro */ << std::endl; } //Verifia se esta conectado if (socket.is_open()) { const unsigned char packet_bytes [] = { "0x1e, 0x00, 0xe0, 0x55, 0xc0, 0x52, 0x09, 0x00," "0x41, 0x00, 0x73, 0x00, 0x70, 0x00, 0x70, 0x00," "0x69, 0x00, 0x65, 0x00, 0x72, 0x00, 0x72, 0x00," "0x00, 0x00, 0x08, 0x9b, 0x95, 0x01" }; //Se conexΓ§ao for True, escreve: //asio::buffer e um container, contendo bytes da string e sizer. socket.write_some(asio::buffer(packet_bytes.data(), packet_bytes.size()), ec); //Estava dando erro pelo tempo de resposta, programa indo mais rapido que a resposta. socket.wait(socket.wait_read); size_t bytes = socket.available(); std::cout << "Bytes Available: " << bytes << std::endl; if (bytes > 0) { //adiciona dados recebidos em um vector std::vector<char> vBuffer(bytes); socket.read_some(asio::buffer(vBuffer.data(), vBuffer.size()), ec); // for (auto c : vBuffer) { std::cout << c; } } } system("pause"); return 0; }```
Your packet_bytes is a plain character array, it doesn't have data and size member function. Hence it is not possible to call packet_bytes.data() and packet_byte.size() on character array. To create a asio::buffer from an array of characters, you need to pass the character array and its length to asio::buffer. Please update your code as follows, then it should compile fine. socket.write_some(asio::buffer(packet_bytes, sizeof(packet_bytes)), ec);
73,372,625
73,372,796
Set values of a 2D array using specific coordinates
Disclaimer: This could apply to any programming langage but I am using C++, so I'm using the C++ tag. I have an array of an xyz structure: struct xyz { float x, y, z; }; In the array I create, at first I only initialize the x and y as I know the z value only later in the code like this: size = Width * Height; Cloud = new xyz[size]; // Remplissage des indices de Pixels for (int i = 0; i < size; i++) { Cloud[i].x = i % Width; Cloud[i].y = i / Width; } }; This results in an array that looks like that: x; y; z 0; 0; 0 1; 0; 0 2; 0; 0 3; 0; 0 0; 1; 0 1; 1; 0 2; 1; 0 3; 1; 0 0; 2; 0 1; 2; 0 2; 2; 0 3; 2; 0 So after that, I want to set a z value for such x and y values but I don't know how to do that in an effective way (I don't want to use a loop that goes through my whole array until I find the right x and y set). My problem I guess is how to do the inverse math of Cloud[i].x = i % Width and Cloud[i].y = i / Width into something to do Cloud[??].z = someValue. Thank you in advance!
That is simple mathematics. If you have x and y and want to know the index to address the z-value later, then you may calculate "y * width + x". So: Cloud[y * Width + x].z = zValue;
73,372,820
73,374,147
Setup/Configuring unit-testing with google test in C++ using Visual Studio 2020
If you can't get your solution to compile, for example by receiving an unresolved externals error, take a look at the answer section and recreate the steps listed there.
Our example header: #pragma once #include <string> std::string testfunc(); Our example sourcefile: #include "to_test.h" std::string testfunc() { return "test worked"; } After creating our example project, we wanna check some things on our list beforehand. add google test adapter via visual studio installer (under individual components, search for "google") right click our test project inside of our solution and click on "manage NuGet Packages", switch to the Browse tab and search for "gtest" and add it. It looks sorta like this: we then want to add a unit test project to our solution. we right-click our solution in the solution explorer and choose add->new project. We search for "google" and add the one things that pops up which is named "Google Test". For a start we keep every setting on default, except for the path which we are going to change from the parent-folder of the solution to the folder of the project we are going to test (bacially just one depth deeper). We will open our test.cpp and add it somewhat like this: (note: the #include of your custom header shouldn't be copy-pasted to make sure its the right path in your case) #include "pch.h" #include "../to_test.h" TEST(test, TestName) { //This Test will work EXPECT_TRUE(testfunc() == "test worked"); //This Test will fail EXPECT_TRUE(testfunc() == "test not worked"); } now for the configuration: right-click on your test-project and open the properties. under VC++ Directories, add the location of your header files under the "Include Directories" under Linker->General, add the Debug-Folder of your Project which is to be tested under the "Addtional Library Directories" under Linker->Input simple add the name of your headerfile without the filetype to the "Additional Dependencies" in our case that would be "to_test" (without the quotes) We can then right-click our solution and rebuild it. After that we can choose our GTest-1 Project as the Startproject via right-clicking it and then debug it as usual. The Terminal popping up should look sorta like this: DISCLAIMER: This definietly isn't the only way to do this.. if someone cares to correct me i would highly appreciate it :)
73,372,875
73,372,876
CMake [build] stuck on one percentage throughout build yet still builds
When building with cmake no longer getting increasing percentages, just stuck at 40%. The build still works. [build] [ 40%] ... [build] [ 40%] ... [build] [ 40%] ...
This was a permissions issue. Solved by changing the build/CMakeFiles/Progress directory to have correct ownership, e.g. using chown or chmod. Same issue spotted in 2006: https://cmake.org/pipermail/cmake/2006-October/011544.html
73,372,959
73,372,985
Conditional constructor calling in C++
In the following code #include <iostream> enum class motorid{ M1, M2 }; enum class encoderid{ E1, E2 }; class encoder{ public : encoder(encoderid eid):Eid(eid){} private: encoderid Eid; }; class motor{ public: motor(motorid mid):Mid(mid){ if(mid == motorid::M1){ e(encoderid::E1); } e(encoderid::E2); } private: motorid Mid; encoder e; } I want to initialize encoder class with value based on value given to motor class from main, I don't want to expose the encoder details to main,but I am forced to give the encoder type also. How to achieve this? Since no heap is involved using new and creating object is not an option.
Syntax would be: motor(motorid mid):Mid(mid), e(mid == motorid::M1 ? encoderid::E1 : encoderid::E2) { } For more complex case (or for readability), creating function might help: encoderid create_encoderid(motorid mid) { if (mid == motorid::M1){ return encoderid::E1; } return encoderid::E2; } motor::motor(motorid mid):Mid(mid), e(create_encoderid(mid)) { }
73,373,388
73,373,465
How to construct some classes in a vector?
I'm working on a class, and I need to have vector of the class. I would like to have objects constructed in place rather than using copy construction. It seems that use of copy construction is inevitable. #include <iostream> #include <string> #include <vector> class MyData { public: int age; std::string name; MyData(int age, std::string name) : age(age), name(name) { std::cout << "MyData::MyData(int, std::string)\n"; } MyData(const MyData& myData) : age(myData.age), name(myData.name) { std::cout << "MyData::MyData(const MyData&)\n"; } MyData(MyData&& myData) :age(std::move(myData.age)), name(std::move(myData.name)) { std::cout << "MyData::MyData(MyData&&)\n"; } ~MyData() { std::cout << "MyData::~MyData()\n"; } }; #define DEBUG(...) std::cout << "Exec: " #__VA_ARGS__ << ";\n"; __VA_ARGS__ int main() { DEBUG(std::vector<MyData> sb1); DEBUG(sb1.emplace_back(MyData{ 32, "SJ" })); DEBUG(sb1.emplace_back(MyData{ 42, "SJ" })); } The output of the code is as follows : Exec: std::vector<MyData> sb1; Exec: sb1.emplace_back(MyData{ 32, "SJ" }); MyData::MyData(int, std::string) MyData::MyData(MyData&&) MyData::~MyData() Exec: sb1.emplace_back(MyData{ 42, "SJ" }); MyData::MyData(int, std::string) MyData::MyData(MyData&&) MyData::MyData(const MyData&) MyData::~MyData() MyData::~MyData() MyData::~MyData() MyData::~MyData() C:\Users\XOXOX\source\repos\cpp_stack\x64\Debug\cpp_stack.exe (process 12832) exited with code 0. Press any key to close this window . . . I'm using C++ 2020 and MSVC.
First when you write DEBUG(sb1.emplace_back(MyData{ 32, "SJ" })); You create a temporary object that gets passed to the emplaced_back function. The point of emplace_back is that it calls the costructor in-place. So you have to give it the arguments for creating an object, not a temporary object or it will have to use the copy/move constructor. Second sb1 is a vector with a capacity of 0. So adding items to it will have to resize and that means copying since the move constructor is not noexcept. std::vector can not handle exceptions during a resize so it can't risk using your move constructor. You should reserve the right side to avoid resize.
73,374,011
73,376,616
Rationale for const ref binding to a different type?
I recently learned that it's possible to assign a value to a reference of a different type. Concrete example: const std::optional<float>& ref0 = 5.0f; const std::optional<float>& ref1 = get_float(); That's surprising to me. I would certainly expect this to work with a non-reference, but assumed that references only bind to the same type. I found a pretty good chunk of the c++ standard which talks about all kinds of ways this works: https://eel.is/c++draft/dcl.init.ref#5. But I would appreciate some insight: When is this ever desirable? A particular occasion where this hurt me recently was this: auto get_value() -> std::optional<float>{ /* ... */ } const std::optional<float>& value = get_value(); // check and use value... I later then changed the return value of the function to a raw float, expecting all uses with a reference type to fail. They did not. Without paying attention, all the useless checking code would have stayed in place.
The basic reason is one of consistency. Since const-reference parameters are very widely used not for reference semantics but merely to avoid copying, one would expect each of void y(X); void z(const X&); to accept anything, rvalue or otherwise, that can be converted to an X. Initializing a local variable has the same semantics. This syntax also once had a practical value: in C++03, the results of functions (including conversions) were notionally copied: struct A {A(int);}; struct B {operator A() const;}; void g() { A o=B(); // return value copied into o const A &r=3; // refers to (lifetime-extended) temporary } There was already permission to elide these copies, and in this sort of trivial case it was common to do so, but the reference guaranteed it.
73,374,946
73,375,021
Import headers from c++ library in swift
I am learning how to communicate between swift and c++ for ios. As a first step I have looked on this example: https://github.com/leetal/ios-cmake There is an example-app that I have managed to compile and run. Took some time to get it to work. That is an objective-c project. The next step is to create a new swift project and try and import the compiled library and use the headers in swift instead. I have not managed to do that. I think the current problem is that I cannot include the header HelloWorldIOS.h. import SwiftUI import HelloWorldIOS.h <- No such module found struct ContentView: View { var body: some View { Text(sayHello()) .padding() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } I have tried to create a bridging file example-Bridging-Header.h as suggested here: https://developer.apple.com/documentation/swift/importing-objective-c-into-swift It looks like: // // example-Bridging-Header.h // example-swift // #ifndef example_Bridging_Header_h #define example_Bridging_Header_h #import "HelloWorldIOS.h" #endif /* example_Bridging_Header_h */ I have also added the path to the headers in Target - Build Settings - Header Search Paths The Objective-C Bridging Header looks like example-swift/example-Bridging-Header.h. Are there any good instructions for how to call c++ code from a compiled library? I hoped this example I found would be easy to get to work. The comment below helped me plus that I had to link to libc++.tbd.
You don't import anything in your Swift code when Objective-C headers are imported in the bridging header. All public interfaces available from the imported files get available in the entire Swift module by default after that. Sample listing TDWObject.h #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface TDWObject : NSObject - (void)someCPPCode; @end NS_ASSUME_NONNULL_END TDWObject.mm #include <iostream> #import "TDWObject.h" @implementation TDWObject - (void)someCPPCode { std::cout << "Hello from CPP cout" << std::endl; } @end Some-Bridging-Header.h #import "TDWObject.h" main.swift TDWObject().someCPPCode() Provided the main.swift file is the entry point of the program, it will print Hello from CPP cout.
73,375,173
73,375,439
What happens if member functions of a class in a header file are implemented in two cpp files?
What happens if member functions of a class in a header file are implemented in two cpp files which are both compiled by the compiler? I mean, lets say I have this code: //header file A.hpp class A { public: int funcA(); } //implementation file A1.cpp #include "A.hpp" int A::funcA(){/* whatever*/} //implementation file A2.cpp #include "A.hpp" int A::funcA(){/* whatever*/} Will the compiler trigger an error?
What happens if member functions of a class in a header file are implemented in two cpp files which are both compiled by the compiler? It would be Undefined Behavior, as defined by the one definition rule. Will the compiler trigger an error? No. A compiler's job is to compile a single translation unit (a cpp file) and neither of your translation units violate this one definition rule. The linker might inform you, but it is not required to do so. In the case of gcc, for example, ODR violations are only reported when link-time optimization is enabled.
73,375,771
73,377,818
Why Launch-VsDevShell.ps1 set my working directory to source\repos
Why my working directory is modified by Launch-VsDevShell.ps1 and how can we prevent this from happening? I'm writting a script building a C++ programm and I need MSVC on Windows. MSVC tools (cl.exe, ...) are not definded in PATH by default and you need to execute Launch-VsDevShell.ps1 to get this tools. After executting Launch-VsDevShell.ps1 in my script the current working directory is defined to C:\Users\USERNAME\source\repos. I just want Launch-VsDevShell.ps1 to add environement variable, not to change my pwd.
You need to use -SkipAutomaticLocation $vsWhere = "${Env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" $vsInstallationPath = & $vsWhere -products * -latest -property installationPath & "${vsInstallationPath}\Common7\Tools\Launch-VsDevShell.ps1" -Arch amd64 -SkipAutomaticLocation Doc: https://learn.microsoft.com/en-us/visualstudio/ide/reference/command-prompt-powershell?view=vs-2022#skipautomaticlocation
73,375,776
73,377,939
No Matching Function Begin Multicast - Arduino/cpp
I was given a project to convert from ESP8266 to ESP32, and I'm definitely not a coder, but it needs to get done. So I was hoping I could get some guidance/help on how to solve this issue. I'm basically taking previous code from an old project using an ESP8266 WiFi module and converting it over to a more updated module using ESP32. Been compiling and troubleshooting code as I go the best I can, but this one has stumped me. The error message I'm getting is "No matching function for call to 'WiFiUDP::beginMulticast(IPAddress, IPAddress&, const unsigned int&)' There are several pages of code, but this is the .cpp file that is currently throwing up an error, and hoping it's able to be resolved with something on this page. Like I said, I'm not a coder, but I have the basics down. Any help on this would be greatly appreciated. Thanks! #include "Switch.h" #include <functional> // Multicast declarations IPAddress ipMulti(239, 255, 255, 250); const unsigned int portMulti = 1900; char packetBuffer[512]; #define MAX_SWITCHES 14 Switch switches[MAX_SWITCHES] = {}; int numOfSwitchs = 0; //#define numOfSwitchs (sizeof(switches)/sizeof(Switch)) //array size //<<constructor>> UpnpBroadcastResponder::UpnpBroadcastResponder(){ } //<<destructor>> UpnpBroadcastResponder::~UpnpBroadcastResponder(){/*nothing to destruct*/} bool UpnpBroadcastResponder::beginUdpMulticast(){ boolean state = false; Serial.println("Begin multicast .."); if(UDP.beginMulticast(WiFi.localIP(), ipMulti, portMulti)) { Serial.print("Udp multicast server started at "); Serial.print(ipMulti); Serial.print(":"); Serial.println(portMulti); state = true; } else{ Serial.println("Connection failed"); } return state; } //Switch *ptrArray; void UpnpBroadcastResponder::addDevice(Switch& device) { Serial.print("Adding switch : "); Serial.print(device.getAlexaInvokeName()); Serial.print(" index : "); Serial.println(numOfSwitchs); switches[numOfSwitchs] = device; numOfSwitchs++; } void UpnpBroadcastResponder::serverLoop(){ int packetSize = UDP.parsePacket(); if (packetSize <= 0) return; IPAddress senderIP = UDP.remoteIP(); unsigned int senderPort = UDP.remotePort(); // read the packet into the buffer UDP.read(packetBuffer, packetSize); // check if this is a M-SEARCH for WeMo device String request = String((char *)packetBuffer); if(request.indexOf('M-SEARCH') > 0) { if(request.indexOf("urn:Belkin:device:**") > 0) { Serial.println("Got UDP Belkin Request.."); // int arrSize = sizeof(switchs) / sizeof(Switch); for(int n = 0; n < numOfSwitchs; n++) { Switch &sw = switches[n]; if (&sw != NULL) { sw.respondToSearch(senderIP, senderPort); } } } } }```
The Arduino UDP API as defined by the UDP base class in Arduino core has uint8_t beginMulticast(IPAddress, uint16_t); In esp8266 Arduino WiFi the UDP is modified and the first parameter of beginMulticast specifies the network interface to listen to. (Network interfaces are STA, SoftAP, Ethernet etc) In esp32 Arduino WiFi library beginMulticast has only the standard parameters and listens on all network interfaces. Your solution is to remove the first parameter in the beginMulticast call.
73,376,371
73,376,949
Cannot find the definition of a constant
I am trying to add a new accelerator to the Nvidia Triton inference server. One of the last thing I need to do it add a new constant like this one (kOpenVINOExecutionAccelerator) but for some reason I cannot find where it is defined: https://github.com/triton-inference-server/onnxruntime_backend/search?q=kOpenVINOExecutionAccelerator I'm quite new to cmake, is this some kind of cmake trick?
It's in the Triton Inference Server Backend here.
73,376,436
73,381,831
std::launder reachability rules
std::launder example has this block of code: int x2[2][10]; auto p2 = std::launder(reinterpret_cast<int(*)[10]>(&x2[0][0])); // Undefined behavior: x2[1] would be reachable through the resulting pointer to x2[0] // but is not reachable from the source What? Example from std::aligned_storage makes it seem to me like that's not the case: std::aligned_storage_t<sizeof(T), alignof(T)> data[N]; // Access an object in aligned storage const T& operator[](std::size_t pos) const { // Note: std::launder is needed after the change of object model in P0137R1 return *std::launder(reinterpret_cast<const T*>(&data[pos])); } Here's where confusion comes in: &data[pos] is just &data[pos][0], because &p == &p[0] where p is an array. How come this is okay if std::aligned_storage can hardly if at all be implemented in any other way but something like alignas(T) std::byte[sizeof (T)];? Does the array being in a struct somehow magically make it okay? Why? Let's say I have template <typename T> using uninitialized = alignas(T) std::byte[sizeof (T)]; constexpr auto N = 5; uninitialized<int> array[N]; for (std::size_t i = 0; i < N; i++) { new (&array[i]) int(i); } Now what? Isn't any cast like auto laundered_value_ptr = std::launder(reinterpret_cast<int*>(&array[i])); identical to the first example? What about this: auto laundered_array_ptr = std::launder(reinterpret_cast<int*>(array)); laundered_array_ptr[0] = 9; laundered_array_ptr[2] = 76; If I follow, it seems like there's no way to use this memory correctly, because using a std::byte(*)[sizeof (int)] means that basically anything around it is reachable, and following first example, everything written in this question is may aswell be UB. I compiled these examples using g++ -g -O0 -Wextra -Wall -Wpedantic -std=c++20 -fsanitize=undefined -fsanitize=address and curiously had gotten not even a warning which leaves me completely stumped. I doubt this matters at all, but here's the version of compiler that I am using. g++ (GCC) 12.1.1 20220730
You wrote: &data[pos] is just &data[pos][0], because &p == &p[0] where p is an array. In fact, that's not true. If p is an array (call its type T[N]), the expression &p == &p[0] will not compile. The left-hand side has type T(*)[N], and the right-hand side has type T*. These cannot be compared directly, any more than you could compare an int* with a char*. However, static_cast<void*>(&p) == static_cast<void*>(&p[0]) will be true. The two pointers represent the same address, but they are not substitutable for each other. &data[pos] is a pointer to one element of data, and all other elements of data are reachable through it. On the other hand, (supposing that std::aligned_storage_t is an alias for an array of unsigned char) &data[pos][0] points only to a single element of an element of data; it does not point to the entire element of data. So all other elements of data[pos] are reachable through it, but other elements of data are not. Since all elements of data are reachable through &data[pos], it follows that all bytes in data are reachable through &data[pos]. After this pointer is converted to const T*, the other T's that are stored inside the other elements of data are also reachable from the resulting pointer, but the bytes of those T's were also reachable from the original pointer, so the preconditions of std::launder are met. If we used &data[pos][0] as the argument to reinterpret_cast, only the bytes in the single element data[pos] would be reachable from that pointer, and the preconditions would not be met.
73,376,508
73,377,963
How to interpret std::vector<unsigned char> as a double?
I have a std::vector<unsigned char> containing values representing the bytes coming from the network. I want to interpret every 8 elements as a double, similar to this but for extracting a double instead of a uint32_t: uint32_t extractUint32From(vector<unsigned char> const& from, uint32_t startIndex) { uint32_t value = 0; for (int i = 0; i < sizeof(uint32_t); i++) { value |= from[startIndex + i] << (i * 8); } return value; } I have tried: double extractDoubleFrom(vector<unsigned char> const& from, uint32_t startIndex){ uint64_t d; for (int i = 0; i < sizeof(double); i++) { //std::cout << (int)from[startIndex + i] << "\n"; d |= from[startIndex + i] << (i*8); } //std::cout << d << "\n"; return static_cast<double>(d); } And some other variations... is there something I am doing wrong? EDIT: The following solution worked for me: double d; std::vector<unsigned char> test = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x3f}; // this is 1.5 memcpy(test.data(), &d, sizeof(double)); std::cout << d;
The 'byte order' in which it is sent from the network is important. (Big or Little endian Endianness) Hopefully, the example below may help you find a solution to your issue. // CppConsoleApplication1.cpp // #include <stdio.h> #include <tchar.h> #include <stdint.h> #include <assert.h> #include <vector> #define MAX_DOUBLE 1.7976931348623157E+308 #define DOUBLE_SIZE ((int)sizeof(double)) int GetPlatformByteOrder(void); const int LITTLE_ENDIAN = 1234; const int BIG_ENDIAN = 4321; const int BYTE_ORDER = GetPlatformByteOrder(); int GetPlatformByteOrder(void) { const unsigned int cbuffer = sizeof(unsigned int); unsigned int value = 0x0A0B0C0D; unsigned char buffer[cbuffer]; memcpy_s((void*)buffer, cbuffer, (const void*)&value, cbuffer); return (buffer[0] == 0x0A) ? BIG_ENDIAN : LITTLE_ENDIAN; } double ToDouble(const std::vector<unsigned char>& from, uint32_t startIndex, int byteOrder = BYTE_ORDER) { assert((from.size() - startIndex) >= DOUBLE_SIZE); double retVal = 0; unsigned char* p = (unsigned char*)&retVal; if (byteOrder != BYTE_ORDER) { for (int32_t i = 0; i < DOUBLE_SIZE; i++) { p[i] = from[(DOUBLE_SIZE - (i + 1)) + startIndex]; } } else { for (int32_t i = 0; i < DOUBLE_SIZE; i++) { p[i] = from[i + startIndex]; } } return retVal; } std::vector<unsigned char> ToArray(double value, int byteOrder = BYTE_ORDER) { std::vector<unsigned char> retVal; unsigned char* p = (unsigned char*)&value; if (byteOrder != BYTE_ORDER) { for (int32_t i = 0; i < (int32_t)DOUBLE_SIZE; i++) { retVal.push_back(p[DOUBLE_SIZE - (i + 1)]); } } else { for (int32_t i = 0; i < (int32_t)DOUBLE_SIZE; i++) { retVal.push_back(p[i]); } } return retVal; } int _tmain(int argc, _TCHAR* argv[]) { double value0 = MAX_DOUBLE; double value1; std::vector<unsigned char> datas; // Test1 datas = ToArray(value0); value1 = ToDouble(datas, 0); printf("Before: %1.16E\n", value0); printf("After : %1.16E\n", value1); printf("Result: %s\n", value1 == value0 ? "Correct" : "Incorrect"); printf("\n"); //assert(value1 == value0); // Test2 datas = ToArray(value0, BIG_ENDIAN); value1 = ToDouble(datas, 0, BIG_ENDIAN); printf("Before: %1.16E\n", value0); printf("After : %1.16E\n", value1); printf("Result: %s\n", value1 == value0 ? "Correct" : "Incorrect"); printf("\n"); //assert(value1 == value0); // Test3 (with error) // For example, We don't know the byte order of the source. datas = ToArray(value0, BIG_ENDIAN); // For example, we assume the byte order of the source is LITTLE_ENDIAN. value1 = ToDouble(datas, 0, LITTLE_ENDIAN); // ??? printf("Before: %1.16E\n", value0); printf("After : %1.16E\n", value1); printf("Result: %s\n", value1 == value0 ? "Correct" : "Incorrect"); printf("\n"); //assert(value1 == value0); printf("\nPress enter to exit."); getchar(); return 0; } The result will be as shown below. Before: 1.7976931348623157E+308 After : 1.7976931348623157E+308 Result: Correct Before: 1.7976931348623157E+308 After : 1.7976931348623157E+308 Result: Correct Before: 1.7976931348623157E+308 After : -1.#QNAN00000000000E+000 Result: Incorrect
73,376,883
73,377,670
MFC: How do I change background color in MFC?
By default the color is gray, I want to change it.I use OnEraseBkgnd in my MainFarm.h,this works, it changes color,but when somewhere further in the code mfc changes it to gray again. BOOL CMainFrame::OnEraseBkgnd(CDC* pDC) { CBrush backBrush(RGB(0, 0, 0)); CBrush* pPrevBrush = pDC->SelectObject(&backBrush); CRect rect; pDC->GetClipBox(&rect); pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATCOPY); pDC->SelectObject(backBrush); return TRUE; }
A MDI application doesn't just have frame windows and child windows. It also has a client window. The client window handles most of managing child windows. But it also draws the client area of the frame window. This is what's drawing the grey background after you draw your background when you handle OnEraseBkgnd in the frame window. Assuming your frame is derived from CMDIFrameWndEx, you should have a OnEraseMDIClientBackground virtual function that you can override to do the drawing you want. If you're modifying older code, it's possible it uses an old enough version of MFC that's not present. If so, you need to create a window class and do the correct drawing in its onEraseBkgnd, create an instance of that in your frame window class, and in the frame window's onCreate, you subclass the MDI child window: class MyBkgndErase : public CWnd { public: BOOL OnEraseBkgnd(CDC* pDC) { // drawing code here } }; class MyFrameWnd : public CMDIFrameWnd { MyBkgndErase eraser; int OnCreate(LPCREATESTRUCT lpCreateStruct) { // there's probably existing code you'll want to preserve here eraser.SubclassWindow(m_hWndMDIClient); return 0; } }; Or, if you can switch to a newer version of MFC, you can probably just change your frame window's parent class from CMDIFrameWnd to CMDIFrameWndEx, and use OnEraseMDIClientBackground (which is undoubtedly easier).
73,377,245
73,377,624
How to properly wait for condition variable in C++?
In trying to create an asynchronous I/O file reader in C++ under Linux. The example I have has two buffers. The first read blocks. Then, for each time around the main loop, I asynchronously launch the IO and call process() which runs the simulated processing of the current block. When processing is done, we wait for the condition variable. The idea is that the asynchronous handler should notify the condition variable. Unfortunately the notify seems to happen before wait, and it seems like this is not the way the condition variable wait() function works. How should I rewrite the code so that the loop waits until the asynchronous io has completed? #include <aio.h> #include <fcntl.h> #include <signal.h> #include <unistd.h> #include <condition_variable> #include <cstring> #include <iostream> #include <thread> using namespace std; using namespace std::chrono_literals; constexpr uint32_t blockSize = 512; mutex readMutex; condition_variable cv; int fh; int bytesRead; void process(char* buf, uint32_t bytesRead) { cout << "processing..." << endl; usleep(100000); } void aio_completion_handler(sigval_t sigval) { struct aiocb* req = (struct aiocb*)sigval.sival_ptr; // check whether asynch operation is complete if (aio_error(req) == 0) { int ret = aio_return(req); bytesRead = req->aio_nbytes; cout << "ret == " << ret << endl; cout << (char*)req->aio_buf << endl; } { unique_lock<mutex> readLock(readMutex); cv.notify_one(); } } void thready() { char* buf1 = new char[blockSize]; char* buf2 = new char[blockSize]; aiocb cb; char* processbuf = buf1; char* readbuf = buf2; fh = open("smallfile.dat", O_RDONLY); if (fh < 0) { throw std::runtime_error("cannot open file!"); } memset(&cb, 0, sizeof(aiocb)); cb.aio_fildes = fh; cb.aio_nbytes = blockSize; cb.aio_offset = 0; // Fill in callback information /* Using SIGEV_THREAD to request a thread callback function as a notification method */ cb.aio_sigevent.sigev_notify_attributes = nullptr; cb.aio_sigevent.sigev_notify = SIGEV_THREAD; cb.aio_sigevent.sigev_notify_function = aio_completion_handler; /* The context to be transmitted is loaded into the handler (in this case, a reference to the aiocb request itself). In this handler, we simply refer to the arrived sigval pointer and use the AIO function to verify that the request has been completed. */ cb.aio_sigevent.sigev_value.sival_ptr = &cb; int currentBytesRead = read(fh, buf1, blockSize); // read the 1st block while (true) { cb.aio_buf = readbuf; aio_read(&cb); // each next block is read asynchronously process(processbuf, currentBytesRead); // process while waiting { unique_lock<mutex> readLock(readMutex); cv.wait(readLock); } currentBytesRead = bytesRead; // make local copy of global modified by the asynch code if (currentBytesRead < blockSize) { break; // last time, get out } cout << "back from wait" << endl; swap(processbuf, readbuf); // switch to other buffer for next time currentBytesRead = bytesRead; // create local copy } delete[] buf1; delete[] buf2; } int main() { try { thready(); } catch (std::exception& e) { cerr << e.what() << '\n'; } return 0; }
A condition varible should generally be used for waiting until it is possible that the predicate (for example a shared variable) has changed, and notifying waiting threads that the predicate may have changed, so that waiting threads should check the predicate again. However, you seem to be attempting to use the state of the condition variable itself as the predicate. This is not how condition variables are supposed to be used and may lead to race conditions such as those described in your question. Another reason to always check the predicate is that spurious wakeups are possible with condition variables. In your case, it would probably be appropriate to create a shared variable bool operation_completed = false; and use that variable as the predicate for the condition variable. Access to that variable should always be controlled by the mutex. You can then change the lines { unique_lock<mutex> readLock(readMutex); cv.notify_one(); } to { unique_lock<mutex> readLock(readMutex); operation_completed = true; cv.notify_one(); } and change the lines { unique_lock<mutex> readLock(readMutex); cv.wait(readLock); } to: { unique_lock<mutex> readLock(readMutex); while ( !operation_completed ) cv.wait(readLock); } Instead of while ( !operation_completed ) cv.wait(readLock); you can also write cv.wait( readLock, []{ return operation_completed; } ); which is equivalent. See the documentation of std::condition_varible::wait for further information. Of course, operation_completed should also be set back to false when appropriate, while the mutex is locked.
73,377,738
73,378,433
Can my program use unallocated memory on the free store without my knowledge?
When defining a variable without initialization on either the stack or the free store it usually has a garbage value, as assigning it to some default value e.g. 0 would just be a waste of time. Examples: int foo;//uninitialized foo may contain any value int* fooptr=new int;//uninitialized *fooptr may contain any value This however doens't answer the question of where the garbage values come from. The usual explanation to that is that new or malloc or whatever you use to get dynamically allocated memory don't initialize the memory to some value as I've stated above and the garbage values are just leftover from whatever program used the same memory prior. So I put this explanation to the test: #include <iostream> int main() { int* ptr= new int[10]{0};//allocate memory and initialize everything to 0 for (int i=0;i<10;++i) { std::cout<<*(ptr+i)<<" "<<ptr+i<<std::endl; } delete[]ptr; ptr= new int[10];//allocate memory without initialization for (int i=0;i<10;++i) { std::cout<<*(ptr+i)<<" "<<ptr+i<<std::endl; } delete[]ptr; } Output: 0 0x1291a60 0 0x1291a64 0 0x1291a68 0 0x1291a6c 0 0x1291a70 0 0x1291a74 0 0x1291a78 0 0x1291a7c 0 0x1291a80 0 0x1291a84 19471096 0x1291a60 19464384 0x1291a64 0 0x1291a68 0 0x1291a6c 0 0x1291a70 0 0x1291a74 0 0x1291a78 0 0x1291a7c 0 0x1291a80 0 0x1291a84 In this code sample I allocated memory for 10 ints twice. The first time I do so I initialize every value to 0. I use delete[] on the pointer and proceed to immediately allocate the memory for 10 ints again but this time without initialization. Yes I know that the results of using an uninitialized variable are undefined, but I want to focus on the garbage values fro now. The output shows that the first two ints now contain garbage values in the same memory location. If we take the explanation for garbage values into consideration this leaves me only one conclusion: Between deleting the pointer and allocating the memory again something must have tampered with the values in those memory locations. But isn't the free store reserved for new and delete? What could have tampered those values? Edit: I removed the std::cout as a comment pointed it out. I use the compiler Eclipse 2022-06 comes with (MinGW GCC) using default flags on Windows 10.
One of the things you need to understand about heap allocations is that there is always a small control block also allocated when you do a new. The values in the control block tend to inform the compiler how much space is being freed when delete is called. When a block is deleted, the first part of the buffer is often overwritten by a control block. If you look at the two values you see from your program as hex values, you will note they appear to be addresses in the same general memory space. The first looks to be a pointer to the next allocated location, while the second appears to be a pointer to the start of the heap block. Edit: One of the main reasons to add this kind of control block in a recently deallocated buffer is that is supports memory coalescence. That two int signature will effectively show how much memory can be claimed if that space is reused, and it signals that it is empty by pointing to the start of the frame.
73,377,786
73,377,816
C++ concept that a type is same_as any one of several types?
I would like to define a concept that indicates a type is one of several supported types. I can do this by repeatedly listing the types with std::same_as<T, U>: #include <concepts> template <typename T> concept IsMySupportedType = std::same_as<T, int32_t> || std::same_as<T, int64_t> || std::same_as<T, float> || std::same_as<T, double>; Is there a more concise way to write this without repeating the std::same_as concept?
This can be done using a variadic helper concept (taken from the cppreference for std::same_as): template <typename T, typename... U> concept IsAnyOf = (std::same_as<T, U> || ...); This can be used to define the desired concept as follows: template <typename T> concept IsMySupportedType = IsAnyOf<T, std::int32_t, std::int64_t, float, double>; Note that the initial T on the right-hand side is important. The resulting concept can be used as expected: static_assert(IsMySupportedType<float>); static_assert(!IsMySupportedType<std::int8_t>); Compiling example: https://godbolt.org/z/6dE9r1EY6
73,378,251
73,378,678
lvalue reference on rvalue reference
I have an interesting example to understand lvalue reference, rvalue reference, and std::forward. Maybe it will be a useful example for a deep understating concept. void foo(int&& a){ cout<<"foo&&"<<endl; } void foo(int& a){ cout<<"foo&"<<endl; } template <typename T> void wrapper(T&& a){ cout<<"wrapperTemplate"<<endl; foo(forward<T>(a)); }; int main() { double&& a=5; double& t=a; wrapper(t); } The output is: wrapperTemplate foo&&
You can't call the lvalue reference version, as t is a double and foo() expects an int. And you can't bind the temporary generated by the implict cast from double to int to an lvalue reference. The temporary is an rvalue, so can be used to call the rvalue overload. The fact that a is an rvalue reference doesn't change the result: double a=5; double& t=a; wrapper(t); still prints: wrapperTemplate foo&& https://godbolt.org/z/89T7Wzc8e If the types do match, the lvalue reference function is called: int a=5; int& t=a; wrapper(t); prints: wrapperTemplate foo& https://godbolt.org/z/chnzaKhGf If you use std::move(), you get back to the rvalue reference version: int a=5; int& t=a; wrapper(std::move(t)); prints: wrapperTemplate foo&& https://godbolt.org/z/68KPYrhYP Removing wrapper also doesn't change the behaviour: double a=5; foo(a); int b=5; foo(b); foo(std::move(b)); prints: foo&& foo& foo&& https://godbolt.org/z/fds6sKvhW
73,378,933
73,379,061
declare extern class c++ in hpp file and use it cpp file
I have two classes : Individu and Cite and as u can see Individu is defined before //file.hpp #include <iostream> #include <stdexcept> #include <vector> extern Cite CITE; class Individu { protected: static int id; TYPE t; public: Individu(); virtual ~Individu(); static int & getCompteur(); virtual void afficher(std::ostream& ) const; virtual TYPE getType() const; }; class Cite { std::vector<const Individu *> tab; public: Cite(); ~Cite(); void addPersonne(const Individu *); int size() const; }; std::ostream& operator<<(std::ostream&, const Individu& ); #endif I need to add an Individu one it's instanciated to the tab vector of Cite and sisnce there is just one Cite I declared Exctern CITE Cite to work with just like that : // file.cpp #include <algorithm> #include "file.hpp" int Individu::id = 0; Individu::Individu() { CITE.addPersonne(*this); id++; } Individu::~Individu(){ } int& Individu::getCompteur() { return id; } void Individu::afficher(std::ostream& o) const{ o << id; } void Personne::afficher(std::ostream& o) const { o << nom << " " << id; } std::ostream& operator<<(std::ostream& o, const Individu& i ){ i.afficher(o); return o; } TYPE Individu::getType() const { throw IllegalException(); } Cite::Cite(){ } Cite::~Cite() { } void Cite::addPersonne(const Individu * i){ tab.push_back(i); } int Cite::size() const { return tab.size(); } and when I compile I got this error : file.hpp:13:8: error: β€˜Cite’ does not name a type 13 | extern Cite CITE; | ^~~~ file.cpp: In constructor β€˜Individu::Individu()’: file.cpp:30:5: error: β€˜CITE’ was not declared in this scope 30 | CITE.addPerconne(*this); | ^~~~ make: *** [makefile:15 : build/deviant.o] Erreur 1 I understand that Cite is not yet defined so that's why I got that error , so hwo can I fix it ?
You have two issues in your code: extern Cite CITE is declared before the class Cite is defined, so the compiler doesn't know what a Cite is at that point. You should move this declaration after the definition of Cite. You never define CITE. An extern variable declaration is a promise to the compiler that you will define that variable later. You're essentially saying "I promise a Cite object named CITE exists even though you can't see it right now". You broke that promise by never actually creating that object. You need to define a Cite CITE somewhere (most likely in file.cpp).
73,379,136
73,379,817
Most memory efficient way to remove duplicate lines in a text file using C++
I understand how to do this using std::string and std::unordered_set, however, each line and each element of the set takes up a lot of unnecessary, inefficient memory, resulting in an unordered_set and half the lines from the file being 5 -10 times larger than the file itself. Is it possible (and how, if so) to somehow reduce memory consumption, for example, so that you can remove duplicates from a 10 gigabyte file using no more than 20 gigabytes of RAM? In this case, of course, it is necessary to do this at a speed of O(n).
This code is reading the input file line by line, storing only hashes of the strings in memory. If the line was not seen before, it writes the result into the output file. If the line was seen before, it does not do anything. It uses sparsepp to reduce the memory footprint. Input data: 12 GB file size ~197.000.000 different lines line length < 120 characters Build: C++20 release build do not run within Visual Studio (no debugger attached) Processing: AMD Ryzen 2700X 32 GB of RAM Seagate SSD 190 seconds 954 MB virtual memory peak Is that good enough? I can't tell, because your performance requirements are quite vague and you didn't give proper performance comparison data. It may depend on your machine, your data, your RAM size, your hard disk speed, ... #include <chrono> #include <iostream> #include <fstream> #include <algorithm> #include <array> #include <cstring> #include <functional> #include <random> #include <string> #include "spp.h" int main() { std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); std::ifstream input; std::ofstream output; input.open("10gb.txt"); output.open("10gb_nodupes.txt"); std::string inputline; spp::sparse_hash_map<size_t, size_t> hashes; while (std::getline(input, inputline)) { std::size_t hash = std::hash<std::string>{}(inputline); if (!hashes.contains(hash)) { output << inputline << '\n'; hashes[hash]=0; } } input.close(); output.close(); std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now(); std::cout << "Time difference = " << std::chrono::duration_cast<std::chrono::seconds>(end - begin).count() << "[s]" << std::endl; std::cout << "Done"; }
73,379,193
73,379,319
Storing type information only of a class in std::vector
I would like to store an std::string and something in an std::tuple which is inside an std::vector for creating std::unique_ptr-s in runtime but not with an if/else. I would like something like this: class A { }; class B : public A { static const std::string name() { return "B"; } }; class C : public A { static const std::string name() { return "C"; } }; class D { public: D(); void addItem(std:string name); private: std::vector<std::unique_ptr<A>> my_items; std::vector<std::tuple<std::string, XXX something here XXX>> my_vector; }; D::D() { my_vector.emplace_back(std::make_tuple(B::name(), YYY something here YYY)); my_vector.emplace_back(std::make_tuple(C::name(), YYY something here YYY)); } void D::addItem(std::string name) { for (const auto &[typeName, YYY typeSomething YYY] : my_vector) { if (name == typeName) { my_items.emplace_back(std::make_unique<YYY typeSomething YYY>()); break; } } } I have tried typeid and std::type_info, std::type_index but that is not for my case I think.
Probably looking for std::function: class D { public: D(); void addItem(std:string name); private: std::vector<std::unique_ptr<A>> my_items; std::vector<std::tuple<std::string, std::function<std::unique_ptr<A>()>>> my_vector; }; D::D() { my_vector.emplace_back(std::make_tuple(B::name(), []{ return std::make_unique<B>(); })); my_vector.emplace_back(std::make_tuple(C::name(), []{ return std::make_unique<C>(); })); } void D::addItem(std::string name) { for (const auto& [typeName, f] : my_vector) { if (name == typeName) { my_items.emplace_back(f()); break; } } }
73,379,625
73,384,453
c++ - implementing a multivariate probability density function for a likelihood filter
I'm trying to construct a multivariate likelihood function in c++ code with the aim of comparing multiple temperature simulations for consistency with observations but taking into account autocorrelation between the time steps. I am inexperienced in c++ and so have been struggling to understand how to write the equation in c++ form. I have the covariance matrix, the simulations I wish to judge and the observations to compare to. The equation is as follows: f(x,ΞΌ,Ξ£) = (1/√(∣Σ∣(2Ο€)^d))*exp(βˆ’1/2(x-ΞΌ)Ξ£^(-1)(x-ΞΌ)') So I need to find the determinant and the inverse of the covariance matrix. Does anyone know how to do that in c++ if x,ΞΌ and Ξ£ are all specified?
I have found a few examples and resources to follow https://github.com/dirkschumacher/rcppglm https://www.youtube.com/watch?v=y8Kq0xfFF3U&t=953s https://www.codeproject.com/Articles/25335/An-Algorithm-for-Weighted-Linear-Regression https://www.geeksforgeeks.org/regression-analysis-and-the-best-fitting-line-using-c/ https://cppsecrets.com/users/489510710111510497118107979811497495464103109971051084699111109/C00-MLPACK-LinearRegression.php https://stats.stackexchange.com/questions/146230/how-to-implement-glm-computationally-in-c-or-other-languages
73,379,759
73,380,344
Is shared pointer thread-safety zero-cost?
I recently found out that the control block for shared pointers (the thing that manages the reference count) is thread-safe, so things like copying and passing shared pointers are safe for multithreaded uses. However, I also know that one of the ideals of C++ is that you shouldn't have to pay for features you don't use. To me, it seems that the thread-safety of the control block would require some mutex locks, which is some overhead. Given that it is perfectly reasonable to use shared pointers in non-multithreaded applications, I don't see why this overhead is accepted. So my question is whether the C++ language designers decided to take the bullet and accept this additional overhead for all cases, or if this thread-safe control block can be implemented in a way that it is zero-cost (unlike my naive mutex lock assumption).
No, std::shared_ptr's thread-safety is not zero-cost. The alternative, however, would be a shared_ptr that is essentially unusable in a multithreaded environment. It would be impossible for multiple threads to safely hold multiple shared_ptrs to the same object without the possibility of creating data races on the control block. To solve that problem, the standard library would need separate thread-safe and non-thread-safe shared_ptr types, which would significantly complicate the interfaces of anything that uses std::shared_ptr. I assume this complication was deemed to outweigh the fairly minimal overhead of simply always performing atomic updates on the control block's reference counts.
73,379,990
73,380,223
How to check if a c++ typeid(T) call is compile time or runtime determined?
C++ keyword typeid has a magic: it know when to use compile-time type info and when to use runtime type info: #include <iostream> #include <typeinfo> using namespace std; struct Interface { virtual void f() = 0; }; struct S1 : Interface { void f() { cout << "S1\n"; }}; struct S3 : S1 { void f() { cout << "S3\n"; }}; int main() { S1 s1; cout << typeid(s1).name() << endl; S1* ps = new S3; cout << typeid(ps).name() << endl; cout << typeid(*ps).name() << endl; delete ps; return 0; } The program prints: struct S1 struct S1 * __ptr64 struct S3 My question: does gcc/clang compiler has any compiler macro, or type_traits : that exposes typeid magic and tells us whether typeid(*ps) is compile-time determined or runtime-determined?
Check this out: template<typename T> constexpr auto my_typeId(const T& value) { auto compileTimeChecked{ true }; const auto& typeId = typeid(compileTimeChecked = false, value); return std::pair< decltype(compileTimeChecked), decltype(typeId) >{ compileTimeChecked, typeId }; } The first argument of the pair has true if typeid is resolved at compile time. false otherwise. The second member is the reference to the resolved type information const std::type_info & The trick here is that typeid semantic changes depending on the argument it takes. If argument is an instance of a polymorphic class, then typeid actually evaluates the expression in runtime, and the side effect of compileTimeChecked = false comes into play. Otherwise typeid does not evaluate the expression (thus, compileTimeChecked = false never happens), but just takes the static type of value resolved at compile-time. Edit: as pointed out by user17732522 in the comments, be advised that when value is a polymorphic prvalue, my_typeId function actually evaluates it in runtime, unlike the typeid which, if passed directly, resolves the type statically. This difference is apparently impossible to get rid of when using functions, just because of how function call work in C++.
73,381,271
73,381,314
Exception thrown: read access violation. this->top was nullptr
I am currently trying to develop a RPM Calculator using C++ but I am running into this error message whenever I try to run my code Exception thrown: read access violation. this->top was nullptr. Here is what I have in my .h file: template<class T> struct MyStack { T data; // this is going to store the number MyStack<T>* link; // used to point to the next element in the stack private: MyStack<T>* top = NULL; // this will represent the top of the stack when the stack is empty this is set to null public: void push(T operand); void value(); void pop(); }; template<class T> void MyStack<T>::push(T value) { MyStack<T>* ptr = new MyStack<T>; // create a new pointer ptr->data = value; // set data to whatever the value that is passed in ptr->link = top; top = ptr; } template<class T> void MyStack<T>::value() { if (top->data != NULL) { // here is where the error occurs cout << top->data << ">" << endl; } else { cout << "X>"; }// prints out the current top value } template<class T> void MyStack<T>::pop() { MyStack<T>* ptr = top; // creating the pointer top = top->link; //. top is now equal to the link delete(ptr); // I can now delete the top value as top is now equal to the link which is the previos value } And here is what I have in my main int main() { MyStack<double> s; string input; while (true) { // display prompt s.value(); // cout << "VALUE>"; // get input cin >> input; // check for numeric value double num; if (istringstream(input) >> num) { s.push(num); } // check for operator else if (isOperator(input)) { performOp(input, s); } // check for quit else if (input == "q") { return 0; } else { cout << "Invalid Input" << endl; } } } Could anyone please help me with this? I have been trying to fix this all day but haven't been able to do it. NOTE: I have removed some other functions I had so the code was not too long any help will be very much appreciated
Your while loop is calling s.value() on its 1st iteration when s is empty, so the s.top field is still NULL, but value() (and also pop()) tries to access top->data (and top->link) regardless of whether top is NULL or not. You need to fix your MyStack methods to work correctly on an empty stack, ie: In value(): if (top->data != NULL) should be if (top != NULL) and in pop(): top = top->link; should be if (top != NULL) top = top->link; Otherwise, simply don't call value() (or pop()) when the stack is empty. Add an isEmpty() method that returns true when top is NULL, and then call value() (or pop()) only when isEmpty() returns false: if (!s.isEmpty()) s.value();
73,382,644
73,382,717
Visual Studio 2022 intellisense includePath errors
when using the intellisense prompt of VS2022 to automatically include the header file in the code in the Cpp file, the following error always occurs #include "../Config/UGConfigManager.h" Is there any way to replace the path "../" with a full path? Like this: #include "Game/Config/UGConfigManager.h" EDIT: In UE5, you need to change NMake's IncludeSearchPath instead of VC++ Directories in Properties -> NMake
You need to add an include path to the "Game" folder. To set an include path you now must right-click a project and go to: Properties -> VC++ Directories -> General -> Include Directories Then add the include directory like so: C:/foobar/Game First try using an absolute path. And if that works you will want to use a Macro. Macros allow users to define paths without being specific to their own computer (So other people can use it). Perhaps what you need is $(ProjectDir) but I can't tell since I don't know where "Game" is relative to your project files. But as an example: $(ProjectDir)/Game It's worth pointing out that what you are doing is interacting with the compiler option /I on the MSVC compiler. Visual Studio is just a gui abstracting it away for you. Here are the docs on /I (Additional include directories)
73,382,672
73,382,763
Can't cast type int to char using function parameters C++
Hello im trying to understand why i can't cast type int To a char using a user defined function with parameters. Im following along with learncpp. And i am a beginner, So please could i have the simplified versions. If i create a user function, And try a return the value back it will just output the integer instead of an ASCII character. Here is my following code. int ascii(int y) { return static_cast<char>(y); } int main() { std::cout << ascii(5) << std::endl; return 0; }
The issue is the type of your return value. It should be a char. Not an int char ascii(int y) { return static_cast<char>(y); }
73,383,217
73,383,361
How to link my project library to my pybind module?
I'm am new to pybind11 and I'm struggling with this : I have a cpp program called my_exec. I want to create a python-binding for it. (with pybind11) In my exec I have 1 simple function : int add(int i, int j) { return i+j; } And this is my pybind .cpp file : #include <pybind11/pybind11.h> #include "lib.h" // my add function is defined here and implement in lib.cpp PYBIND11_MODULE(cpp, m) { m.doc() = "first python binding."; m.def("add", &add, "A function that adds 2 numbers"); m.def("mul", &mul, "A function that multiply 2 numbers"); } So here is my problem : I can't build my pybind module with CMake because I can't (I don't know how) link my program my_exec (containing the add function implementation) to it. This is my CMakeLists.txt file : # only for cmake --version >= 3.5.1 cmake_minimum_required(VERSION 3.5.1) if (CMAKE_BUILD_TYPE MATCHES Debug) message("Cmake in debug mode.") else () message("Cmake in release mode.") endif (CMAKE_BUILD_TYPE MATCHES Debug) # project name project(my_exec) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) #lsp file set(CMAKE_EXPORT_COMPILE_COMMANDS 1) # I../includes include_directories( src /media/romain/Donnees/Programmation/C++/frameworks /media/romain/Donnees/Programmation/C++/frameworks/files /media/romain/Donnees/Programmation/C++/libs/json /media/romain/Donnees/Programmation/C++/libs/boost-install/include ) #Link directories link_directories(build/libs) # puts all .cpp files inside src to the SOURCES variable file(GLOB SOURCES src/*.cpp /media/romain/Donnees/Programmation/C++/frameworks/debug.cpp /media/romain/Donnees/Programmation/C++/frameworks/str.cpp ) if (CMAKE_BUILD_TYPE MATCHES Debug) add_compile_definitions(mydebug) add_compile_options(-Og) else() add_compile_options(-O3) endif(CMAKE_BUILD_TYPE MATCHES Debug) # compiles the files defined by SOURCES to generate the executable defined by EXEC add_executable(${PROJECT_NAME} ${SOURCES}) add_subdirectory(pybind) #where is the pybind CMakeLists file #make the executable linkable by other libs (runtime ones - here for my module pybind) set_target_properties(${PROJECT_NAME} PROPERTIES ENABLE_EXPORTS on) # linkers target_link_libraries(${PROJECT_NAME} pthread stdc++fs ) And this is my pybind CMakeLists.txt (locate in the subdir pybind) : cmake_minimum_required(VERSION 3.5) project(pybind) include_directories(/media/romain/Donnees/Programmation/C++/libs/pybind11/include) add_subdirectory(/media/romain/Donnees/Programmation/C++/libs/pybind11 ./pybind11_build) pybind11_add_module(cpp ../src/pybind/cpp.cpp) target_link_libraries(${PROJECT_NAME} PRIVATE my_exec) I can't compile because CMake give a error when trying to link my_exec : Cannot specify link libraries for target "pybind" which is not built by this project. So, how to link an external lib/exec to a pybind Cmake project ? Thank you in advance ! :) EDIT : Thanks to @David Fong anwser, I managed to compiled. But unfortunatly, I think python does not support module linked to an executable. It has to be a static or shared library. So I had to compile my program my_exec as a library like that : add_library(my_exec SHARED ${SOURCES}) I hope it will help some of you if you have the same issue. :)
The first parameter of target_link_libraries is the name of a target. You have passed the name of your project, which will only work if you happen to name a target with the same name as your project. Here, your target is named cpp, which you specified as the first argument to pybind11_add_module.
73,383,266
73,384,084
Convert boost::multiprecision::cpp_dec_float_100 to string with precision
In my code I want to have a function which performs some calculations based on boost::multiprecision::cpp_dec_float_100 and returns string as a result with some precision, but the question is how I should set the precision ? e.g. If the precision is 9, then I expect the following results for the following numbers: for 2345.12345678910111213 I expect string "2345.123456789" but I have 12345.1235 for 1.12345678910111213 I expect string "1.123456789" but I have 1.12345679 So it always returns my exact number of characters provided to str() function with round. I know that I can do it like e.g. this: std::stringstream ss; ss << std::fixed << std::setprecision(9) << my_value; return ss.str(); or use cout(but this is not my case) or do some find on string to find "." and take only 9 characters after it, but can I do it in an easier way ? maybe in boost is some function to do it correctly ? #include <iostream> #include <boost/multiprecision/cpp_dec_float.hpp> namespace bmp = boost::multiprecision; std::string foo_1() { bmp::cpp_dec_float_100 val{"12345.12345678910111213"}; return val.str(9); } std::string foo_2() { bmp::cpp_dec_float_100 val{"1.12345678910111213"}; return val.str(9); } int main() { auto const val_1 = foo_1(); auto const val_2 = foo_2(); std::cout << "val_1: " << val_1 << std::endl; std::cout << "val_2: " << val_2 << std::endl; return 0; } online version: https://wandbox.org/permlink/HTAHsE5ZE3tgK9kf
Change the line: return val.str(9); To: return val.str(9, std::ios::fixed); You will get the expected strings.
73,383,403
73,385,377
Is there a better way to serialize NTL ZZ?
I'm currently using the NTL library to store big integers (NTL::ZZ). It looks like the only serialization way in lib is from ZZ to std::string (and std::string to ZZ for deserialization). But if I want to store and transfer a large number of integers, it becomes too slow. And the size of the transferred text is too large. Is there a better way to serialize and deserialize NTL::ZZ? such as binary?
It is easy to miss, but ZZ provides conversions to and from byte sequences: void ZZFromBytes(ZZ& x, const unsigned char *p, long n); ZZ ZZFromBytes(const unsigned char *p, long n); // x = sum(p[i]*256^i, i=0..n-1). // NOTE: in the unusual event that a char is more than 8 bits, // only the low order 8 bits of p[i] are used void BytesFromZZ(unsigned char *p, const ZZ& a, long n); // Computes p[0..n-1] such that abs(a) == sum(p[i]*256^i, i=0..n-1) mod 256^n. long NumBytes(const ZZ& a); long NumBytes(long a); With simple length-prefix framing, you can thus have: void writeZZ(ostream& os, const ZZ& a) { long size = htobe32(NumBytes(a)); std::string buf(size, 0); BytesFromZZ(buf.data(), a, buf.size()); os.write(&size, sizeof(long)); os.write(buf.data(), buf.size()); } ZZ readZZ(istream& is) { long size; is.read(&size, sizeof(long)); size = be32toh(size); std::string buf(size, 0); is.read(buf.data(), size); return ZZFromBytes(buf.data(), size); } This can obviously be improved with error checking and by using a single thread-local buf instead of creating a fresh one every time.
73,383,545
73,383,591
I think this is bad C++ coding ('new' in a function to point to a local variable). Am I correct?
I want to create a class that contains a pointer, and upon initialization, the pointer can be dereferenced to give an integer assigned at initialisation. This was my first attempt to write this code. This passed compiler and gave me the correct result without warning. However I later think this code has a potential problem. That is in the constructor, the integer a is created on a stack framed to the constructor function. I am however making 'ptr' pointing to this stack memory address. The problem is this memory can be reused upon maybe calling other functions, so I might get garbage value if I am not lucky. #include <iostream> using namespace std; class P { public: int *ptr; P(int); }; P::P(int a){ int *ptr = new int (0); ptr = &a; } int main() { P p(99); cout <<*(p.ptr) <<endl; } A better way would be to create an integer variable on heap, copy the value of a to that variable, and make ptr pointing to that memory space on heap. P::P(int a){ int *i = new int (0); *i = a; ptr = i; } Is my analysis correct? Thanks!
The statements int *ptr = new int (0); ptr = &a; are problematic, but probably not because of the reasons you think. The reason it's problematic is because you define a new and distinct local variable ptr inside the function. This is not the same as the P::ptr member variable. There's also a second problem, which is a memory leak. You allocate memory with new, but you never free the memory with delete. If you really is required to use a raw and non-owning pointer to a single int value, I recommend you do it using a constructor initializer list: P(int a) : ptr{ new int(a) } { // Empty } Here new int(a) will create a new int value and copy the value of a into it. Remember to then create a destructor which free's the memory you have allocated. And then you need to learn about the rules of three, five and zero. To use the rule of zero, and to avoid memory leaks and make life simpler, use a smart pointer like std::unique_ptr: struct P { std::unique_ptr<int> ptr; P(int a) : ptr{ std::make_unique<int>(a) } { } }; And of course, since it's just about a single int value, and you don't need a reference to the original value, there's no need for pointers at all.
73,383,609
73,383,841
gcc 12 suggesting to add the "pure" attribute
I have written a container class very similar to std::vector. It has a size() member function, which I declared noexcept, const and constexpr. class my_vector { ... constexpr auto size() const noexcept -> size_type { assert(stride_ != 0); return nelems_/stride_; } }; Since I switched to GCC 12, the compiler suggests me to add the __attribute__ ((pure)). error: function might be candidate for attribute 'pure' if it is known to return normally [-Werror=suggest-attribute=pure] I would be happy to add the attribute but, first, is the function really pure? I mean, this is passed by reference and I think functions that take reference can't be "pure" because their arguments can be changed externally to the function (e.g. by another thread). Is that the case? Is it in generally safe to follow this recommendation by the compiler? Finally, I don't understand the logic of this recommendations: if the compiler can determine the function is pure, then it should go ahead and do all the optimizations it can, instead of suggesting adding a non-standard language extension.
According to the gcc documentation Even though hash takes a non-const pointer argument it must not modify the array it points to, or any other object whose value the rest of the program may depend on. However, the caller may safely change the contents of the array between successive calls to the function (doing so disables the optimization). The restriction also applies to member objects referenced by the this pointer in C++ non-static member functions So it seems that member functions can be pure as long as they don't modify member variables. If they depend on member variables, the compiler will take care of recalling the method if those members change.
73,384,755
73,386,224
rust emulating variadic serialisation of PODs
In C++ I have the following template: template<typename UBO> std::pair<uint, std::vector<std::byte>> SerializeUniform(UBO& ubo, uint binding) { // Create raw binary buffers of the uniform data std::vector<std::byte> ubo_buffer(sizeof(UBO)); memcpy(ubo_buffer.data(), (void*)&ubo, sizeof(UBO)); return {binding, ubo_buffer}; } inline void SerializeArguments(NECore::UniformBufferDataContainer& data) {} template<typename T1, typename... Ts> inline void SerializeArguments( NECore::UniformBufferDataContainer& data, T1& uniform, uint binding, Ts&... args) { data.push_back(SerializeUniform(uniform, binding)); SerializeArguments(data, args...); } template<class... Ubos> void ModuleStorage::Draw(const NECore::RenderRequest& render_request, const Ubos&... args) { size_t arg_num = _details::ArgNum(args...); NECore::UniformBufferDataContainer ubos; ubos.reserve(arg_num); _details::SerializeArguments(ubos, args...); if(render_request.image_outputs.empty()) DrawToScreen(vk_meta_data.vulkan_data, render_request, ubos); else DrawOffScreen(vk_meta_data.vulkan_data, render_request, ubos); } A bit hard to read so let me walk you through them. The first template takes a POD and copies it's data into a vector of bytes and then creates a tuple to associate the data with an integer. The next template is the base case of a recursive template, no parameters, do nothing. Next we have a recursive template, take the first two parameters, assumed to be a POD and an integer, And serialize the POD. Recurse on the tail. I.e. this template allows me to serialize an arbitrary number of PODs. Finally I have a variadic template that allows me to serialize any number of PODs. You might be wondering why go through all this trouble. It;s so that I can write things like this: modules.Draw( { gltf_shader, {gallery.GetGpuMeshData(model_names[selected_model])}, textures, ssbos }, mvp, 0, gltf_info, 1); This way the render command accepts any arbitrary number of uniform parameters which means I can use the same pattern and syntax to call any arbitrary shader my heart desires with any inputs I want (as long as they are byte compatible with the shader declaration) I am porting this library to rust and I want to achieve a similar thing with macros. i.e. I want to be abble to define things such that I can call draw(render_request, macro!(ubo1, 0, ubo2, 1)) Or better yet (but I am almost certain this cannot be done in rust) draw(render_request, ubo1, 0, ubo2, 1) I am having a very hard time trying to come up with the macro. The primary issue is, macros are not functions and rust doesn't support variadic arguments. I am not entirely sure how to define the macro to achieve what I want.
I managed to get it to work by hacking the vec! macro from the standard library macro_rules! UBO { () => {Vec::<UniformBufferData>::new()}; ($($ubo:expr, $binding : expr),* $(,)?) => { [$(serialize_uniform(&$ubo, $binding)),+].to_vec() } } This lets you call the macro UBO!(dummy2, 0, dummy, 1, dummy3, 3) Which expands into [ serialize_uniform(&dummy2, 0), serialize_uniform(&dummy, 1), serialize_uniform(&dummy3, 3), ] .to_vec() So now you can do: draw(render_request, UBO!(var1, 0, var2, 2, var3, 7)); And it should work (UB and other shennanigans aside).
73,384,774
73,385,549
How to selectively enable or disable -Werror argument for entire directories in my project?
I have a project in witch I would like to use -Werror, lets call its directory proj. There is a directory within proj/external and that is an exception so I don't want to use the -Werror for that. Is there a way to create an exception for an entire directory in cmake for using or not using a compiler argument?
CMake 2.34+ Solution If your minimum required CMake version for the project is equal to or greater than v3.24, you can use the CMAKE_COMPILE_WARNING_AS_ERROR variable: This variable is used to initialize the COMPILE_WARNING_AS_ERROR property on all the targets. So just set the variable to a desired value at the top of each variable scope where you want a specific value to be used inside that scope. CMake non-cache variables are scoped to directories and functions. For the specific case of variable scoping for external projects, if you are adding it with add_subdirectory, I'm assuming you don't want to touch the external project's CMakeLists.txt file, so you can instead wrap your call to add_subdirectory with a fuction, and set the variable inside the function, and then call the function. There are several benefits to this approach: Cross-Platform with Less boilerplate: No more explicitly written generator expressions to use the right flag for each compiler. Allows user-override: Not all users will want to build with warnings as errors. This new feature comes with a --compile-no-warning-as-error command-line flag that users can use to disable any effects of this variable/target-property when set by a dev in a CMakeLists.txt file. Pre-3.24 Solution: If you are adding the external directory via add_subdirectory or FetchContent In the CMakeLists.txt file at the subdirectory for proj, do # add `-Werror` to the current directory's `COMPILE_OPTIONS` add_compile_options(-Werror) # retrieve a copy of the current directory's `COMPILE_OPTIONS` get_directory_property(old_dir_compile_options COMPILE_OPTIONS) # modify the actual value of the current directory's `COMPILE_OPTIONS` (copy from above line remains unchanged). subdirectories inherit a copy of their parent's `COMPILE_OPTIONS` at the time the subdirectory is processed. add_compile_options(-Wno-error) # add you subdirectory (whichever way you do it) # add_subdirectory(external ...) # FetchContent_MakeAvailable(...) # restore the current directory's old `COMPILE_OPTIONS` set_directory_properties(PROPERTIES COMPILE_OPTIONS "${old_dir_compile_options}") Docs: COMPILE_OPTIONS add_compile_options get_directory_property set_directory_properties. If you are adding it via ExternalProject_Add You probably don't need to do anything unless the external project itself is adding -Werror, in which case I don't know if you can do anything about it. Obligatory caveats / comments: -Werror is a flag for gcc and friends (clang, etc.). If you want to support MSVC, you need to put guards in either via if(...), or via generator expressions. whether or not to use -Werror is not without controversy. If you want to support other users using your project and you want to satisfy both sides of the debate, use some mechanism to either guard these lines of configuration behind a CMake options, or isolate them to your local build only.
73,385,797
73,385,994
Can I naively check if a/b == c/d?
I was doing leetcode when I had to do some arithmetic with rational numbers (both numerator and denominator integers). I needed to count slopes in a list. In python collections.Counter( [ x/y if y != 0 else "inf" for (x,y) in points ] ) did the job, and I passed all the tests with it. ((edit: they've pointed out in the comments that in that exercise numbers were much smaller, not general 32 bit integers)) I wonder if this is correct, that is, python correctly recognizes if a/b == c/d as rationals, for a,b,c,d 32 bit integers. I am also interested the case for c++, and any additional facts that may be useful (footguns, best practices, theory behind it if not too long etc). Also this question seems frequent and useful, but I don't really find anything about it (give me the duplicates!), maybe I am missing some important keywords?
It's not safe, and I've seen at least one LeetCode problem where you'd fail with that (maybe Max Points on a Line). Example: a = 94911150 b = 94911151 c = 94911151 d = 94911152 print(a/b == c/d) print(a/b) print(c/d) Both a/b and c/d are the same float value even though the slopes actually differ (Try it online!): True 0.9999999894638303 0.9999999894638303 You could use fractions.Fraction(x, y) or the tuple (x//g, y//g) after g = math.gcd(d, y) ( if I remember correctly, this is more lightweight/efficient than the Fraction class).
73,386,231
73,386,391
Type trait to check if istream operator>> exists for given type
I found this type trait which can be used to check if a certain type T supports operator<<: template<class Class> struct has_ostream_operator_impl { template<class V> static auto test(V*) -> decltype(std::declval<std::ostream>() << std::declval<V>()); template<typename> static auto test(...) -> std::false_type; using type = typename std::is_same<std::ostream&, decltype(test<Class>(0))>::type; }; template<class Class> struct has_ostream_operator : has_ostream_operator_impl<Class>::type {}; Source: https://gist.github.com/szymek156/9b1b90fe474277be4641e9ef4666f472 This works fine. Now I'm trying to do the same thing for operator>> using c++11, but I don't get it to work: template<class Class> struct has_istream_operator_impl { template<class V> static auto test(V*) -> decltype(std::declval<V>() >> std::declval<std::istream>()); template<typename> static auto test(...) -> std::false_type; using type = typename std::is_same<std::istream&, decltype(test<Class>(0))>::type; }; /** * @brief Type trait to check if operator>>(std::istream, Type) is defined for a given type. */ template<class Class> struct has_istream_operator : has_istream_operator_impl<Class>::type {}; Here is a simplified test for my use case: #include <sstream> #include <type_traits> #include <iostream> // <include snippet 2> template<typename T> typename std::enable_if<has_istream_operator<T>::value, T>::type fromString(const std::string& str) { T value; std::istringstream stream(str); stream >> value; return value; } int main() { std::cout << fromString<long>("123") + 1 << std::endl; // expecting 124 return 0; } Error is: has_istream_operator.cpp: In function β€˜int main()’: has_istream_operator.cpp:57:38: error: no matching function for call to β€˜fromString<long int>(const char [4])’ std::cout << fromString<long>("123") + 1 << std::endl; // expecting 124 ^ has_istream_operator.cpp:49:1: note: candidate: β€˜template<class T> typename std::enable_if<has_istream_operator<Class>::value, T>::type fromString(const string&)’ fromString(const std::string& str) { ^~~~~~~~~~ has_istream_operator.cpp:49:1: note: template argument deduction/substitution failed: has_istream_operator.cpp: In substitution of β€˜template<class T> typename std::enable_if<has_istream_operator<Class>::value, T>::type fromString(const string&) [with T = long int]’: has_istream_operator.cpp:57:38: required from here has_istream_operator.cpp:49:1: error: no type named β€˜type’ in β€˜struct std::enable_if<false, long int>’ From which I understand that the SFINAE condition is false and therefore no definition of fromString exists. What I have tried is to play around with the line static auto test(V*) -> decltype(std::declval<V>() >> std::declval<std::istream>()); inside my definition of struct has_istream_operator_impl. This is the variation which makes most sense to me, because when I use the operator>>, I usually do it this way: stream >> value for example and from my (limited) understanding, the test(V*) should test this generically for V: static auto test(V*) -> decltype(std::declval<std::istream>() >> std::declval<V>()); But it does also not work (same error). How do get I this to work?
Long story short, you should change static auto test(V*) -> decltype(std::declval<V>() >> std::declval<std::istream>()); to static auto test(V*) -> decltype(std::declval<std::istream>() >> std::declval<V&>()); There were two errors in the code, due to the following. The >> operator takes the stream as first argument, not as second argument, whereas you are passing the two arguments the other way around. declval<V>() is generating an rvalue (well, not really a value because we are in an unevaluated context), to which you can't assign a value via >> (just like you can't cin >> 123;), so you have to change it to declval<V&>().(ΒΉ) ΒΉ To understand more in depth why that's the case, look at the possible implementation of std::declval as shown at the documentation page on cppreference: as you can see, it returns the type typename std::add_rvalue_reference<T>::type (which, incidentally, can be written as std::add_rvalue_reference_t<T> since C++14), i.e. std::declval<T>() returns T&&, which is (by reference collapsing) an lvalue reference if you provide an lvalue reference T to std::declval (e.g. std::declval<int&>()), an rvalue reference otherwise (e.g. std::declval<int>()). In your usecase you are passing long as the T to std::declval, so we are in the second case, i.e. std::declval<long>() returns long&&. From the page on value categories you can see that an example of xvalue (which is, just like a prvalue, an rvalue) is the following (my emphasis): a function call or an overloaded operator expression, whose return type is rvalue reference to object, such as std::move(x); And that's exactly what std::decltype<long>() is: it has a rvalue reference to object as its return type, hence it returns an rvalue. If you call, instead, std::decltype<T&>() and pass long as T, the call will be std::decltype<long&>(), in which case the return type will be long&, hence the call will return an lvalue. See the following quote, from the same page, of an example of lvalue a function call or an overloaded operator expression, whose return type is lvalue reference; To give an example of what std::decltype is doing, these both pass static_assert(std::is_same_v<decltype(std::declval<int>()), int&&>); static_assert(std::is_same_v<decltype(std::declval<int&>()), int&>); and this fails to compile int x; std::cin >> static_cast<int&&>(x); // XXX where the // XXX line is what std::declval<std::istream>() >> std::declval<V>() is "emulating".
73,386,336
73,498,193
C++ Read values from the registry
I want to display these registry key values: MSSQL12.MSSQLSERVER MSSQL15.SQLEXPRESS MSSQL11.TEW_SQLEXPRESS Code: if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Microsoft SQL Server\\Instance Names\\SQL"), 0, KEY_READ | KEY_WOW64_64KEY, &hKey) == ERROR_SUCCESS){ DWORD i, retCode, cchName, buflen; TCHAR achKey[MAX_KEY_LENGTH]; // buffer for subkey name DWORD cbName; // size of name string TCHAR achClass[MAX_PATH] = TEXT(""); // buffer for class name DWORD cchClassName = MAX_PATH; // size of class string DWORD cSubKeys = 0; // number of subkeys DWORD cbMaxSubKey; // longest subkey size DWORD cchMaxClass; // longest class string DWORD cValues; // number of values for key DWORD cchMaxValue; // longest value name DWORD cbMaxValueData; // longest value data DWORD cbSecurityDescriptor; // size of security descriptor FILETIME ftLastWriteTime; // last write time retCode = RegQueryInfoKey( hKey, // key handle achClass, // buffer for class name &cchClassName, // size of class string NULL, // reserved &cSubKeys, // number of subkeys &cbMaxSubKey, // longest subkey size &cchMaxClass, // longest class string &cValues, // number of values for this key &cchMaxValue, // longest value name &cbMaxValueData, // longest value data &cbSecurityDescriptor, // security descriptor &ftLastWriteTime); // last write time result = RegGetValue( hKey, NULL, L"MSSQLSERVER", RRF_RT_REG_SZ, 0, buf, &bufsz); if (result != ERROR_SUCCESS) { printf("Failed read value"); _getch(); return -1; } wprintf(L"%s\n", buf); } I need to replace L"MSSQLSERVER" with the variable keyName, but I don't understand how to do that. I'm trying to write the name of the key to a variable. LPWSTR aResult; LPSTR keyName; RegEnumKeyExA(hKey, i, keyName, &cchName, NULL, NULL, NULL, NULL); MultiByteToWideChar(0, 0, keyName, -1, aResult, 0); result = RegGetValue( hKey, NULL, aResult, RRF_RT_REG_SZ, 0, buf, &bufsz); But I think it's wrong. Here keyName is NULL. And keyName is LPSTR, but RegGetValue() needs LPCWSTR.
It turned out that my task needed names, not values. And only SQL Express. Here is the code: if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Microsoft SQL Server\\Instance Names\\SQL", 0, KEY_READ | KEY_WOW64_64KEY, &hTestKey) == ERROR_SUCCESS ) while (RegEnumValueW(hTestKey, index, (wchar_t*)valueName.c_str(), &lppchValueName, 0, 0, 0, 0) == ERROR_SUCCESS) { lppchValueName = MAX_PATH; buffSize = MAX_PATH; if (RegQueryValueExW(hTestKey, valueName.c_str(), 0, 0, (LPBYTE)value.c_str(), &buffSize) == ERROR_SUCCESS) { if (value.find(L"Express") != std::wstring::npos || value.find(L"EXPRESS") != std::wstring::npos || value.find(L"express") != std::wstring::npos) { // Here is an array entry. } } index++; memset((void*)valueName.c_str(), 0, MAX_PATH); memset((void*)value.c_str(), 0, MAX_PATH); }
73,386,584
73,390,267
"transform apply" - using tuple elements as parameters to one function to construct a parameter pack for another
Given the following: constexpr auto t = std::make_tuple(3, 2, 1); template<auto x> auto InnerF() {return -x;} auto OuterF(auto... args) {return (args + ...);} I can use the elements of t as parameters to InnerF directly: InnerF<std::get<0>(t)>(); But I want to be able to write std::apply([](auto... arg) { return OuterF(InnerF<arg>()...); }, t); But this does not work, I get <source>:29:44: error: no matching function for call to 'InnerF' std::apply([](auto... arg) { return OuterF(InnerF<arg>()...) ;}, t); . . . <source>:29:44: error: no matching function for call to 'InnerF' std::apply([](auto... arg) { return OuterF(InnerF<arg>()...) ;}, t); ^~~~~~~~~~~ <source>:23:6: note: candidate template ignored: invalid explicitly-specified argument for template parameter 'x' auto InnerF() {return -x;} I don't understand why the arg is considered invalid, I tried modifying the syntax a number of ways and reimplementing apply myself, but couldn't crack it - is there any way to make this work?
The error is because InnerF is expecting a non-type template parameter. Those must be compile-time constants, which auto... arg are not. Using gcc 12.1, I get this more helpful error message: <source>:10:59: error: no matching function for call to 'InnerF<arg#0>()' 10 | std::apply([](auto... arg) { return OuterF(InnerF<arg>()...); }, t); | ~~~~~~~~~~~^~ <source>:4:6: note: candidate: 'template<auto x> auto InnerF()' 4 | auto InnerF() {return -x;} | ^~~~~~ <source>:4:6: note: template argument deduction/substitution failed: <source>:10:59: error: 'arg#0' is not a constant expression 10 | std::apply([](auto... arg) { return OuterF(InnerF<arg>()...); }, t); | ~~~~~~~~~~~^~ <source>:10:59: note: in template argument for type 'int' The solution is to write InnerF like so: auto InnerF(auto x) { return -x; } And call std::apply like this: std::apply([](auto... arg) { return OuterF(InnerF(arg)...); }, t);
73,386,720
73,386,823
Is the increment (operator++) thread-safe in C++?
Is the following function thread-safe (in C++) or do I have to add a mutex? int example() { return g_maxValue++; } where int g_maxValue is some global integer. If yes, does the same hold true for all integer types such as std::uint64_t?
Thread safety is guaranteed only for atomic variables (std::atomic). From C++ standard: The execution of a program contains a data race if it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other. Any such data race results in undefined behavior. The compiler doesn't have to consider thread safety for non-atomic variables, so it is allowed to translate ++ to multiple operations (pseudo code): Read g_maxValue to a register Increment the value in the register Store the value to g_maxValue
73,386,798
73,387,404
Passing template parameter pack to type_traits and std::enable_if
I am trying to create a class holding std::variant with a member function that would only accept types held by the nested variant object. That function works basically the same way as variant's operator=. However, the question is - how do I use std::enable_if and type_traits together with template parameter pack? The example below (attempting to check if any of the Types is contractible from T) obviously doesn't compile: template<typename... Types> class Wrapper { public: template<typename T, std::enable_if_t<std::is_constructible_v<Types..., T>, bool> = true> void Set(const T& data) { m_data = data; } private: std::variant<Types...> m_data; }; int main() { Wrapper<int, float> wrapper; wrapper.Set(123); return 0; }
How do I use std::enable_if and type_traits together with template parameter pack? You might do as follows: #include <type_traits> template<typename T, typename... Types> inline constexpr bool areAllowedTypes = (std::is_constructible_v<T, Types> && ...); // && -> if all the types must be convertable, otherwise use || now template<typename T> auto Set(const T& data) ->std::enable_if_t<areAllowedTypes<T, Types...>> { m_data = data; } Or since you have c++17 compiler support, using if constexpr template<typename T> void Set(const T& data) { if constexpr (areAllowedTypes<T, Types...>) m_data = data; }
73,386,984
73,387,576
How to run Python script from QT creator and print output to GUI
void MainWindow::on_pushButton_clicked() { QProcess p; // get values from ini file settings->setValue("EMail", ui->lineEditEMail->text()); settings->setValue("Password", ui->lineEditPassword->text()); settings->setValue("Chronological", ui->checkBox->isChecked()); settings->setValue("Current_info", ui->checkBox_2->isChecked()); settings->endGroup(); settings->sync(); // launch python code for login QString program( "C:/projects/build-test3-Desktop_Qt_6_4_0_MinGW_64_bit-Debug/venv/Scripts/python.exe"); QStringList args = QStringList() << "index.py"; QProcess::execute( program, args ); } I have this function that is executed after a button is clicked and I need to print the output of "index.py" in to my app. What widget should I use and how? From what I read QTextBrowser should do the trick but I'm not sure how to use it. This is how my GUI looks like. I'd like to use to output my results somewhere in button right. I didn't add the widget yet, because I'm not sure QTextBrowser is the one I need
The widget you could use for this purpose is QTextEdit (you can set it to be read-only from the graphical user interface). But if you want to get the output of the execution, you will need a proper instance of QProcess and call the QProcess::readAllStandardOutput() member function to get the standard output. You may also be interested by QProcess::readAllStandardError() to get the errors in case of failure. Edit (simple/basic example): QProcess p; p.start("path/to/python.exe", QStringList("script.py")); p.waitForFinished(); QByteArray p_stdout = p.readAllStandardOutput(); QByteArray p_stderr = p.readAllStandardError(); // Do whatever you want with the results (check if they are not empty, print them, fill your QTextEdit contents, etc...) Note: If you don't want to be blocking with QProcess::waitForFinished(), you can use a signal/slots connection on QProcess::finished() signal.
73,387,038
73,390,137
cv::cuda::NvidiaOpticalFlow_2_0::create takes about 30 seconds
To use the official example script for NvidiaOpticalFlow, I built OpenCV from source following the instructions from the Nvidia Optical Flow SDK (with slightly modified build flags to enable JPEG, OPENEXR, and Eigen). The OpenCV version is 4.5.2. I can post the CMake options on request. This line from the example script takes about 30 seconds. Is this normal or could there be an issue with my setup? Other details: I'm on Ubuntu 20.04 nvidia-smi gives Driver Version: 470.141.03 CUDA Version: 11.4 To compile the example script I use CMake with: cmake_minimum_required(VERSION 3.16) and set(CMAKE_CXX_STANDARD 20).
According to user @RobertCrovella in the comments, the delay may have been to do with JIT compilation. Indeed, when calling create twice in one script, the second time does not have a delay. Whether or not that's the real reason, the root cause was that I had incorrectly specified the arch for my GPU in the OpenCV build flags. They were set as -DCUDA_ARCH_BIN:STRING=7.5 -DCUDA_ARCH_PTX:STRING=7.5 whereas for my GPU (Nvidia RTX 3090) they should have been set as -DCUDA_ARCH_BIN:STRING=8.6 -DCUDA_ARCH_PTX:STRING=8.6. I rebuilt OpenCV with the correct flags and the delay went away.
73,387,598
73,387,961
Trigonometric Equation only works with specific input ( 5 ) doesn't work with other inputs
I try to write code for that calculation angles from lengths of triangle. formula is cos(a)=b^2+c^2-a^2/2bc. (Triangle is here) angle1 = acosf((powf(length2,2) + powf(length3,2) - powf(length1,2)) / 2 * length2 * length3)* 180 / 3.14153; angle2 = acosf((powf(length1,2) + powf(length3,2) - powf(length2,2)) / 2 * length1 * length3)* 180 / 3.14153; angle3 = 180 - (angle2 + angle1); Everything is float. When entered 5-4-3 inputs outcome this. angle one is 90.0018 angle two is nan angle three is nan changing order doesn't matter, only gives output for 5.
You are doing: angle1 = acosf((powf(length2,2) + powf(length3,2) - powf(length1,2)) / 2 * length2 * length3)* 180 / 3.14153; You should be doing: angle1 = acosf((powf(length2,2) + powf(length3,2) - powf(length1,2)) / (2 * length2 * length3))* 180 / 3.14153; Explanation: The problem is caused by the following formula, which is in fact badly written: cos(a)=b^2+c^2-a^2/2bc // This, obviously, is wrong because // you need to group the firt three terms together. // Next to that, everybody understands that the last "b" and "c" are divisors, // yet it would be better to write it as: cos(a)=(b^2+c^2-a^2)/(2bc) The brackets, I added in the code, are similar to the replacement of /2bc by /(2bc).
73,387,765
73,387,897
Why are C++ features unable to be used in extern "C" prototypes but able to be used in the implementation to link in C?
Functions in extern "C" are interpreted in C manners, e.g. no name mangling. However, why do C++ features, such as STL, std::string, smart pointer and so on, can be used in the function definition but cannot be used in the function declaration (to link with other C code)? For example, I want to use std::vector in extern "C". As far as I know, if it's used in the implementation, the .obj file will have such instructions to jump to the ctor, etc; if it's used in the prototypes, it should do so too, and there seems to be no difference between them. Besides, there is a related question for currently I'm studying ABI. What's the relationship between so-called ABI and language linkage in C++? How does ABI influence linking with extern "C" C++ code in C?
Why are C++ features unable to be used in extern "C" prototypes but able to be used in the implementation to link in C? Because the C compiler doesn't understand C++ specific code. The implementation of the extern "C" function that uses C++ classes is compiled with a C++ compiler. The C compiler only sees the function declaration, which can not contain C++ specific things, like std::vectors. header.h - seen by both C and C++ compilers #pragma once #ifdef __cplusplus extern "C" { #endif int foo(const char*); // works in both C and C++ // int bar(std::vector<int>&); // a C compiler can't compile this #ifdef __cplusplus } #endif impl.cpp - never seen by the C compiler, only the C++ compiler #include "header.h" int foo(const char* something) { std::vector<int> bar; // use bar and do stuff return result; }
73,388,430
73,388,492
Is there any C++ STL function to process i and i+1 elements?
Currently my code is something like this std::vector<int> listOfItems; // Assume the listOfItems is filled here for(std::size_t i=0; i<listOfItems.size()-1; i++) { doSomething(listOfItems[i], listOfItems[i+1]); } I was wondering if I could avoid this code and use any STL algorithms for better readibility. Thank you
I have this in my utility library. Feel free to use it: /** Iterates over each adjacent pair of the range. * * For the sequence [1, 2, 3, 4], it invokes fn(1, 2), fn(2, 3), fn(3, 4). * Nothing is invoked if the sequence is only one element long. * * @returns The final state of fn. */ template <typename FwdIt, typename BinFn> BinFn for_pairs(FwdIt first, FwdIt last, BinFn fn) { if (first == last) { return fn; } for (FwdIt it = std::next(first); it != last; ++first, ++it) { fn(*first, *it); } return fn; }
73,388,631
73,396,667
Collapse all lines to one line in VS2019?
I there any way to do the following in VS2019? Say I have code that looks like this: Somefunction(); SomeStatement; SomeOtherFunction(); I want to select these lines, and quickly and easily press a button or key and have it produce this (based on semicolon): Somefunction();SomeStatement;SomeOtherFunction(); ...And also reverse it. It's sort of like collapsing the code except it'll be remembered between instances and also compatible with other systems. Is there any way to make this happen without writing a whole extension?
Use Eidt->Advanced->Join Lines: Shift+Alt+L,Shift+Alt+J
73,389,666
73,391,341
Is there a benefit for functions to take in a forwarding reference to a range instead of a view?
Pre-C++20, it is necessary to use forwarding references in template functions when a std::ranges::range is expected as a parameter. Since concepts are available in C++20, it is now possible to pass a std::ranges::view by value to a generic function. Per the standard, a view is a range. Consider the following code. #include <vector> #include <ranges> #include <iterator> #include <iostream> template <std::ranges::range Range> void fn1(Range range) // intentionally not a forwarding reference { for (auto& elem : range) { ++elem; } } template <std::ranges::view View> void fn2(View view) { for (auto& elem : view) { ++elem; } } int main() { std::vector<int> v{1,2,3}; fn1(v); // doesn't increment, since a copy of 'v' is used in 'fn1'. /* fn2(v); // fails to compile, since 'v' cannot be implicitly converted to a view */ fn1(std::views::all(v)); // increments, since a ref_view is passed to fn1 fn2(std::views::all(v)); // increments, as expected for (int val : v) std::cout << val << ' '; // 3 4 5 return 0; } I have nothing specifically against forwarding references. One can make the claim of a readability benefit to being able to directly pass an object that models a range into a generic function (e.g. fn1(v)). Is this purely a matter of preference, or are there other considerations when making the decision to implement the generic function parameter as Range&& or View?
There are basically several ways that you could conceive of declaring an algorithm that takes some kind of range: constrain on range vs constrain on view take by T&&, T const&, T&, or T That cartesian product gives you 8 options to consider. The problem with T const&, even for non-mutating algorithms, is that we have non-const-iterable ranges (range<R> doesn't necessitate range<R const>). There may a hypothetical alternative design where view actually requires const-iteration, but that's not the design we have. So while T const& seems like the obviously right choice for non-mutating algorithms, it ends up limiting functionality a lot. The problem with T& is that Ranges leads to many situations of having rvalue ranges, and taking a T& would prevent users from writing algo(r | views::transform(f)) -- and it's basically the selling point of the library to be able to write that. That leaves T and T&&. By-value range -- template <ranges::range R> void f(R r) -- is problematic since ranges can be arbitrarily expensive to copy (bad for performance) and can be owning (in which case your algorithm probably isn't doing what you think it's doing -- it may do the right thing for some types but not others). Forwarding-reference view -- template <ranges::view V> void g(V&& v) -- actually disallows passing lvalues, because V& is never a view, so likewise is surprisingly limited in functionality. This effectively reduces the universe to two options: template <ranges::range R> void f(R&& r); template <ranges::view V> void g(V v); These do have functional differences. If I have a non-copyable view, then f(move_only_view) would work while g(move_only_view) would not. But then the reason you'd have a move-only view is that it's an input view, so perhaps g(std::move(move_only_view)) would be syntactically better anyway. Otherwise, f(copyable_view) doesn't copy the view while g(copyable_view) does. Copying views is cheap, as in doesn't copy all the elements, but it's not necessarily free (consider a transform_view with an arbitrarily fat projection, or just many layers of adaptors). So the forwarding-reference-range version does offer the most functionality, and is the cheapest. Other than that, these two are quite similar. f(e) and g(views::all(e)) , when they both compile, are basically the same? Which kind of begs the question of why you'd write the value-view version over the forwarding-range one. There's not really a significant motivator for doing so. The primary place where you need view, specifically, rather than range is when constructing range adaptors. Those need to have member views (not ranges), since they themselves need to be views. But even there, the entry-point isn't: template <ranges::view V> auto make_adaptor(V ); It's, instead: template <ranges::viewable_range R> auto make_adaptor(R&& ); That is, we still take a forwarding range - it's a refined version of range that ensures that we can actually convert it to a view.
73,390,329
73,390,454
abort() is called when I try to terminate a std::thread
Note: I'm using WinForms & C++17. So I was working on a school project. I have this function: bool exs::ExprSimplifier::simplify() { bool completed = false; std::thread thread1(&ExprSimplifier::internalSimplity, this, std::ref(completed)); while (true) { if (completed) { thread1.~thread(); // calls abort() return true; } if (GetAsyncKeyState(27)) { thread1.~thread(); // calls abort() return false; } } } Basically what I want is to run the following function: // at the end of this function, I set completed = true void exs::ExprSimplifier::internalSimplity(bool& completed) ..on another thread. I also want to check while the function's doing it's thing and the user pressed esc key, the thread terminates. But there's where I'm facing issues. This: thread1.~thread(); ..is calling abort(), crashing the application. Now what I think is that this is due to some scope thing of std::thread, but I'm not really sure. Questions: What's the reason for this? What can I do to fix this?
You can't terminate threads - end of story. In the past, they tried to make it so you could terminate threads, but they realized it's impossible to do it without crashing, so now you can't. (E.g. Windows had a TerminateThread function, because it's old. C++ doesn't have it, because C++ threads are new) The only thing you can do is set a variable that tells the thread to stop, and then wait for it to stop. ~thread doesn't terminate threads, anyway. All it does is check that you remembered to call join or detach, and if you forgot to call one of them, it aborts, as you are seeing.
73,390,528
73,391,786
Alternative of boost::asio::executor_work_guard for older boost version (1.57)
I need my boost::asio::io_service object prevent from exiting when there is no more work to do. The boost.asio library version that we are using is outdated and we are not yet allowed to upgrade. The 1.57 version we are using seems not to contain the boost:asio::executor_work_guard that could prevent the io_service object from exiting. Are there any known alternatives to it in the old boost.asio version 1.57 (Linux)?
In older versions you'd use a io_service::work object: boost::asio::io_service io; boost::asio::work work(io); Note that to get reset() like functionality you'd wrap that in boost::optional<> or std::unique_ptr<> This is actually still in the documentation for the 1.57.0 version in the same place(s) where you'd find executor_work_guard in newer versions, e.g. https://www.boost.org/doc/libs/1_57_0/doc/html/boost_asio/reference/io_service.html#boost_asio.reference.io_service.stopping_the_io_service_from_running_out_of_work
73,390,640
73,390,797
Number of steps to reduce a number in binary representation to 1
Given the binary representation of an integer as a string s, return the number of steps to reduce it to 1 under the following rules: If the current number is even, you have to divide it by 2. If the current number is odd, you have to add 1 to it. It is guaranteed that you can always reach one for all test cases. Step 1) 13 is odd, add 1 and obtain 14. Step 2) 14 is even, divide by 2 and obtain 7. Step 3) 7 is odd, add 1 and obtain 8. Step 4) 8 is even, divide by 2 and obtain 4. Step 5) 4 is even, divide by 2 and obtain 2. Step 6) 2 is even, divide by 2 and obtain 1. My input = 1111011110000011100000110001011011110010111001010111110001 Expected output = 85 My output = 81 For the above input, the output is supposed to be 85. But my output shows 81. For other test cases it seems to be giving the right answer. I have been trying all possible debugs, but I am stuck. #include <iostream> #include <string.h> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { string s = "1111011110000011100000110001011011110010111001010111110001"; long int count = 0, size; unsigned long long int dec = 0; size = s.size(); // cout << s[size - 1] << endl; for (int i = 0; i < size; i++) { // cout << pow(2, size - i - 1) << endl; if (s[i] == '0') continue; // cout<<int(s[i])-48<<endl; dec += (int(s[i]) - 48) * pow(2, size - 1 - i); } // cout << dec << endl; // dec = 278675673186014705; while (dec != 1) { if (dec % 2 == 0) dec /= 2; else dec += 1; count += 1; } cout << count; return 0; }
This line: pow(2, size - 1 - i) Can face precision errors as pow takes and returns doubles. Luckily, for powers base 2 that won't overflow unsigned long longs, we can simply use bit shift (which is equivalent to pow(2, x)). Replace that line with: 1LL<<(size - 1 - i) So that it should look like this: dec += (int(s[i]) - 48) * 1ULL<<(size - 1 - i); And we will get the correct output of 85. Note: as mentioned by @RSahu, you can remove (int(s[i]) - 48), as the case where int(s[i]) == '0' is already caught in an above if statement. Simply change the line to: dec += 1ULL<<(size - 1 - i);
73,390,707
73,391,233
Initializing a member with type std::shared_ptr<B> of a class A with a pointer to class B in a member function of B
I have the following code: class Cohomology; struct EMField { std::shared_ptr<Cohomology> coh; std::array<DIM> data; // other methods } class Cohomology { private: // private members public: Cohomology(PList params) { // Constructor of the class } virtual ~Cohomology() {std::cout << "Cohomology destroyed" << std::endl;} void initializeField(EMField& field) { field.coh.reset(this); // other methods to initialize field.data using the private members } } But the class Cohomology also has virtual methods that are implemented by SubCohomology: class SubCohomology : public Cohomology { public: SubCohomology(PList params) {} ~Cohomology() {std::cout << "SubCohomology destroyed" << std::endl;} // Implementation of the virtual methods } So a test code to check whether EMFields are initialized and can be manipulated looks like: int main(int argc, char *argv[]) { // variables needed to initialize PList params PList params(); // construct params SubCohomology coh(params); EMField field; coh.initializeField(field); } The code compiles, but running it yields this error: SubCohomology destroyed Cohomology destroyed free(): invalid pointer [machine:324808] *** Process received signal *** [machine:324808] Signal: Aborted (6) [machine:324808] Associated errno: Unknown error 32767 (32767) [machine:324808] Signal code: (24) [machine:324808] [ 0] /usr/lib/libc.so.6(+0x38a40)[0x7f4ac0054a40] [machine:324808] [ 1] /usr/lib/libc.so.6(+0x884dc)[0x7f4ac00a44dc] [machine:324808] [ 2] /usr/lib/libc.so.6(gsignal+0x18)[0x7f4ac0054998] [machine:324808] [ 3] /usr/lib/libc.so.6(abort+0xd7)[0x7f4ac003e53d] [machine:324808] [ 4] /usr/lib/libc.so.6(+0x7c67e)[0x7f4ac009867e] [machine:324808] [ 5] /usr/lib/libc.so.6(+0x9226c)[0x7f4ac00ae26c] [machine:324808] [ 6] /usr/lib/libc.so.6(+0x940bc)[0x7f4ac00b00bc] [machine:324808] [ 7] /usr/lib/libc.so.6(__libc_free+0x73)[0x7f4ac00b2a33] [machine:324808] [ 8] /home/user/builddir/test_fields(_ZN13EMFieldILi0ELi1EED2Ev+0x83)[0x556db1fc0f73] [machine:324808] [ 9] /home/user/builddir/test_fields(main+0x36e)[0x556db1fa205e] [machine:324808] [10] /usr/lib/libc.so.6(+0x232d0)[0x7f4ac003f2d0] [machine:324808] [11] /usr/lib/libc.so.6(__libc_start_main+0x8a)[0x7f4ac003f38a] [machine:324808] [12] /home/user/builddir/test_fields(_start+0x25)[0x556db1fa3ba5] [machine:324808] *** End of error message *** Aborted (core dumped) which happens after the function initializeField. It is a memory problem, which might be related to trying to free() a non-existing resource. I suspect that using std::enable_shared_from_this might be helpful to address this problem but I don't know how to implement the mandatory inheritance considering my particular problem, as I am trying to initialize the std::shared_ptr<Cohomology> coh class member of a field in the Cohomology class. The example outlined here is very helpful to understand how to use this, but I don't know if I would have to nest another struct in EMField to implement this. I also understand the problem solved in this question: when should we use std::enable_shared_from_this, but I cannot put it in the context where a struct has a std::shared_ptr as a member. Please understand that many EMField objects might be added, whose std::shared_ptr<Cohomology> member points for all fields to the same object Thank you.
std::shared_ptr exists to manage the lifetime of dynamically-allocated objects. No such management is needed (or possible) for an object with automatic storage duration (like coh). Its lifetime is tied to its enclosing scope. Therefore a pointer to coh must never be managed by a std::shared_ptr. Instead, you should consider creating a constructor in EMField that accepts a std::shared_ptr<Cohomology> and having the caller create an appropriate dynamically-allocated object: struct EMField { std::shared_ptr<Cohomology> coh; // ... EMField(std::shared_ptr<Cohomology> c) : coh{c} {} // ... }; int main(int argc, char *argv[]) { // variables needed to initialize PList params PList params(); // construct params auto coh = std::make_shared<SubCohomology>(params); EMField field(coh); // No longer needed since EMField's constructor initializes its // fields now // coh.initializeField(field); } Demo If you absolutely don't want to have to pass your Cohomology object into EMField from the caller, and all Cohomology objects should be dynamically-allocated, and they should all be managed by std::shared_ptrs, then, and only then, is std::enable_shared_from_this the tool for the job. Example: class Cohomology : public std::enable_shared_from_this<Cohomology> { private: // private members protected: Cohomology(PList params) { // Constructor of the class } Cohomology(const Cohomology&) = delete; public: virtual ~Cohomology() { std::cout << "Cohomology destroyed\n"; } static std::shared_ptr<Cohomology> create(PList params) { return std::shared_ptr<Cohomology>(new Cohomology(params)); } void initializeField(EMField& field) { field.coh = shared_from_this(); // ... } // ... }; class SubCohomology : public Cohomology { private: SubCohomology(PList params) : Cohomology(params) {} public: ~SubCohomology() { std::cout << "SubCohomology destroyed\n"; } static std::shared_ptr<SubCohomology> create(PList params) { return std::shared_ptr<SubCohomology>(new SubCohomology(params)); } // Implementation of the virtual methods }; int main(int argc, char *argv[]) { // variables needed to initialize PList params PList params; // construct params std::shared_ptr<SubCohomology> coh = SubCohomology::create(params); EMField field; coh->initializeField(field); } Demo Note that Cohomology and SubCohomology now have non-public constructors. If you inherit from std::enable_shared_from_this you should not allow any objects to ever not be managed by a std::shared_ptr, so separate factory functions are needed to ensure that fact.
73,391,012
73,393,514
How to use Gtk::CssProvider with gtkmm-4.0?
I'm trying to use Gtk::CssProvider with gtkmm-4.0 but it don't work. I would like to change background color button. //CSS style Glib::ustring data = "GtkButton {color: #00ffea;}"; auto provider = Gtk::CssProvider::create(); provider->load_from_data(data); auto ctx = m_button.get_style_context(); ctx->add_provider(provider, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); I think I forget something but I don't understand what. Any ideas ?
I add a style class to context, so later uses of the style context will make use of this new class for styling. Now it works as i want. //CSS style Glib::ustring data = ".button {background-color: #00FF00;}"; auto provider = Gtk::CssProvider::create(); provider->load_from_data(data); auto ctx = m_button.get_style_context(); ctx->add_class("button"); ctx->add_provider(provider, GTK_STYLE_PROVIDER_PRIORITY_USER);
73,391,436
73,391,915
Why is move assignment of unordered_map slow?
I am trying to understand how the move/rvalue assignment operator works. I know that it is largely implementation-specific, but assuming that move assignment in unordered_map works by only swapping the underlying data pointer or size attributes, I suppose it should be extremely fast? This is the code that I tried to run: #include <chrono> #include <functional> #include <iostream> #include <memory> #include <string> #include <unordered_map> using namespace std; void time_it(function<void()> f) { auto start = chrono::steady_clock::now(); f(); auto end = chrono::steady_clock::now(); auto diff = end - start; cout << chrono::duration<double, milli>(diff).count() << " ms" << endl; } using umap = unordered_map<string, string>; static const size_t MAP_SIZE = 1000000; int main() { umap m; for (int i = 0; i < MAP_SIZE; i++) { auto s = to_string(i); m[s] = s; } time_it([&]() { cout << "copy\n"; auto c = m; }); time_it([&]() { cout << "move\n"; auto c = move(m); }); } It returns: copy 204.4 ms move 98.568 ms How come that the move assignment operator takes so long (~100 ms)? I compiled using g++ test.cpp -O3. This is what my g++ -v returns: Using built-in specs. COLLECT_GCC=g++ COLLECT_LTO_WRAPPER=c:/mingw/bin/../libexec/gcc/mingw32/6.3.0/lto-wrapper.exe Target: mingw32 Configured with: ../src/gcc-6.3.0/configure --build=x86_64-pc-linux-gnu --host=mingw32 --with-gmp=/mingw --with-mpfr=/mingw --with-mpc=/mingw --with-isl=/mingw --prefix=/mingw --disable-win32-registry --target=mingw32 --with-arch=i586 --enable-languages=c,c++,objc,obj-c++,fortran,ada --with-pkgversion='MinGW.org GCC-6.3.0-1' --enable-static --enable-shared --enable-threads --with-dwarf2 --disable-sjlj-exceptions --enable-version-specific-runtime-libs --with-libiconv-prefix=/mingw --with-libintl-prefix=/mingw --enable-libstdcxx-debug --with-tune=generic --enable-libgomp --disable-libvtv --enable-nls Thread model: win32 gcc version 6.3.0 (MinGW.org GCC-6.3.0-1)
As MilesBudnek explained in his comment, I only counted the runtime for unordered_map destructor (i.e. the object c) inside my second time_it inner function. I changed it to: time_it([&]() mutable { cout << "copy\n"; auto c = m; m = c; }); time_it([&]() mutable { cout << "move\n"; auto c = move(m); m = move(c); }); to make the underlying object of c not getting deallocated, and now it says ~0.6 ms using -O0 to not let the compiler do undesirable stuff. Thanks everyone, really sorry for my mistakes in the post!
73,391,823
73,391,947
How to add a library to a project so that if the library changes, it (the lib) gets recompiled first before the program in CMake?
I'm developing a simple library and in the past I've been using Premake. Now, I want to change that and use CMake. I've been struggling with 'porting' my workflow to CMake. I want to have 2 projects, one for the library and one for the testing program. The library should not be dependent on the testing program but the testing program should include the library and be dependent on it. For example, if I change something in the library and compile my testing program, I want the library to recompile and then the testing program, so that it uses the latest library version. I was able to do that in Premake but I just can't seem to figure it out yet in CMake. From my understanding, there should a top level CMake file and then the library should have one and the program should have one, just like I did in Premake. Currently I only managed to create my library CMake file, but nothing else. A little help would be appreciated, especially as I'm noob in CMake. My project structure looks like this Root β”œβ”€β”€β”€Application β”‚ β”œβ”€β”€β”€Assets/ β”‚ └───src/ β”‚ └───Scenes/ β”œβ”€β”€β”€Library β”œβ”€β”€β”€BUILD/ β”œβ”€β”€β”€include/ └───src/ └───CMakeLists.txt
Have just one project with a single CMakeLists.txt in the root, something like this cmake_minimum_required( VERSION 3.0 ) project( MainProject ) add_subdirectory( Library ) add_subdirectory( Application ) Once you add the Library as a dependency of Application it all should work. Example: # in Library/CMakeLists.txt add_library( mylib SHARED file1.cpp file2.cpp ) Then in the app # in Application/CMakeLists.txt add_executable( myapp main.cpp ) target_link_libraries( myapp mylib ) that should recompile both mylib and relink myapp as soon as either file1.cpp or file2.cpp change. UPDATE (to address comments) I typically set up both debug and release folders with a shell script prior, something like this: #!/usr/bin/bash # put this on the root together with your CMakelists.txt SCRIPT_NAME=${BASH_SOURCE:-$0} SCRIPT_DIR=$(readlink -f $(dirname "$SCRIPT_NAME") ) BUILD_DIR=${SCRIPT_DIR}/build for build_type in release debug relwithdebinfo; do echo ">>>>> Build Type:" $build_type "<<<<<<" rm -rf ${BUILD_DIR}/${build_type} mkdir -p ${BUILD_DIR}/${build_type} cd ${BUILD_DIR}/${build_type} cmake -G Ninja \ -DCMAKE_BUILD_TYPE=$build_type \ ${SCRIPT_DIR} done Then you just switch to cd build/debug and run ninja (or make). When you are done debugging, switch to release folder cd ../release and build it again/install.
73,391,981
73,392,152
Debugging C/C++ library used by another library which in turn is used by a python executable
I have a python executable: pyExec.py. This program utilizes a C/C++ shared library: abc.so. This abc library requires another C/C++ library: xyz. Once xyz is built, it generates multiple static library files and one shared library file, which are then used to build abc. I want to investigate a function ffn which is present in one of the source files for xyz. None of these libraries throw any error during the compilation. The error I am investigating occurs when I run a particular function in pyExec.py. So far, this error has been traced back to ffn. However, to proceed further, I would like to use a debugger. I tried this answer, along with a few variants of it. I tried setting break points in the source files of both xyz and abc using both line numbers and function names, just to test things out. The debugger, gdb, does ask if the break point is pending on a future shared library load to which I answer yes. But unfortunately the break point is ignored when I run the (python) program. The debugger is called as shown here. Is gdb the best tool for such an investigation? What could be the best overall approach in this context? Can static libraries be investigated with this approach?
gdb should be very capable but you need to be aware of versions. I was recently using clang to compile and gdb to debug and hit this exact case. Ends up clang supports more debug formats. When I switched to lldb (clang's debugger) all symbols came clean. Try lldb and see what happens. Unit tests. They help set up edge cases. Try to eliminate all the environment complexity and isolate in the smallest reproducible example you can. Yes, absolutely. You need to be sure you are compiling with debug information though.
73,392,097
73,407,528
TOTP implementation using C++ and OpenSSL
I am trying to implement TOTP in C++ using OpenSSL. I know there are vast amounts of existing implementations; however, I would like to implement it myself. Currently. I have the following code: bool verifyTOTP(char* code, char* key, int codeLen, int keyLen) { if (codeLen != 6 || keylen != 20) { return false; } unsigned long long intCounter = floor(time(NULL)/30); char md[20]; unsigned int mdLen; HMAC(EVP_sha1(), key, keylen, (const unsigned char*)&intCounter, sizeof(intCounter), (unsigned char*)&md, &mdLen); OPENSSL_cleanse(key, keylen); int offset = md[19] & 0x0f; int bin_code = (md[offset] & 0x7f) << 24 | (md[offset+1] & 0xff) << 16 | (md[offset+2] & 0xff) << 8 | (md[offset+3] & 0xff); bin_code = bin_code % 1000000; char correctCode[7]; snprintf((char*)&correctCode, 7,"%06d", bin_code); int compR = compHash(&correctCode, code, 6); // Compares the two char arrays in a way that avoids timing attacks. Returns 0 on success. delete[] key; delete[] code; if (compR == 0) { return true; } std::this_thread::sleep_for(std::chrono::seconds(5)); return false; } This code does not give any error but fails to produce the correct TOTP, and therefore it returns false when the correct TOTP is verified. For example, when running the below it should return true: char* newKey = new char[20]; char* key = "aaaaaaaaaaaaaaaaaaaa"; memcpy(newKey, key, 20); verifyTOTP(newKey, code, 6, 20); Where code is the token from the TOTP Generator (when using the generator please ensure that the secret key is set to MFQWCYLBMFQWCYLBMFQWCYLBMFQWCYLB). Can anyone spot where I went wrong? I have looked at how other people implemented it but could not find where the problem is. Thank you so much for your attention and participation.
After dividing the Unix timestamp by 30, it is necessary to ensure that intCounter is big endian: unsigned long long endianness = 0xdeadbeef; if ((*(const uint8_t *)&endianness) == 0xef) { intCounter = ((intCounter & 0x00000000ffffffff) << 32) | ((intCounter & 0xffffffff00000000) >> 32); intCounter = ((intCounter & 0x0000ffff0000ffff) << 16) | ((intCounter & 0xffff0000ffff0000) >> 16); intCounter = ((intCounter & 0x00ff00ff00ff00ff) << 8) | ((intCounter & 0xff00ff00ff00ff00) >> 8); }; Credit: I found the solution in this GitHub Gist.
73,392,675
73,392,742
Replacing std::bind with lambda with a member function to fill vector of function pointer
I have implemented function pointer list that i want to past the function and the object i want to convert the bind to a lambda function but i failed, any help? #include <iostream> #include <functional> #include <vector> using namespace std; class Red { public: template <typename F, typename M> void addToVector(F f, M m) { list.push_back(std::bind(f, m)); cout<<"Function added."; } std::vector<std::function<void()>> list; }; class Blue { public: Blue() { r.addToVector(&Blue::someFunc, this); } void someFunc(){ cout<<"Some print."; } Red r; }; int main() { Blue b; return 0; } I have tried this list.push_back([=](){ return m->f(); });
I have tried this list.push_back([=](){ return m->f(); }); The correct syntax to call the member function using a pointer to object would be: //----------------------------vvvvvv------->correct way to call member function using a pointer to object list.push_back([=](){ return (m->*f)(); }); Working demo
73,392,986
73,405,156
In Qt and cmake, how can I moc files generate with my API( dll export) macro
In my case, I have a macro for dll export like this:(very very brief version of the declaration) #ifdef EXPORTDLL #define MMAPI _declspec(export) ... And my class like this: Class MMAPI myClass: public qobject{ Q_Object() ... Generally, mmapi is assigned as export. And I take a linker error because of (in my opinion) staticmetaobject which created by auto moc and cmake for not declered as export dll. I found out some solutions for this. That solutions advice that, include some macro line to cmake file for generate export file. Unfortunately, I don't want to do that. I want use my mmapi. On short, how can I generate staticmetaobject with my macro. From now, thank you all for your helps. Edit: when I change library type to static project build but qrc file not found by qml and qt libs
I find out what is the problem. When I define exportdll macro separately and private for each library in cmake, problem solved. My main app lib somehow see the macro.
73,393,207
73,394,526
Using python within C code and passing list as an argument
I am using Python code within C++ code and trying to pass a list argument to a function written in Python. I tried the normal way of executing the Python code without passing any argument and it was all working fine but when I pass a list as an argument, I get a segmentation fault. Here is my code: #define PY_SSIZE_T_CLEAN #include</usr/include/python3.6/Python.h> #include <bits/stdc++.h> using namespace std; int callModuleFunc(int array[], size_t size) { PyObject *mymodule = PyImport_ImportModule("test"); PyObject *myfunc = PyObject_GetAttrString(mymodule, "get_lists"); cout<<"Imported"<<endl; PyObject *mylist = PyList_New(size); cout<<"Imported3"<<endl; for (size_t i = 0; i != size; ++i) { PyList_SET_ITEM(mylist, i, PyLong_FromLong(array[i])); } PyObject *arglist = Py_BuildValue("(O)", mylist); cout<<"Imported1"<<endl; PyObject *result = PyObject_CallObject(myfunc, arglist); // getting segmentation fault here cout<<"Imported5"<<endl; int retval = (int)PyLong_AsLong(result); Py_DECREF(result); Py_DECREF(arglist); Py_DECREF(mylist); Py_DECREF(myfunc); Py_DECREF(mymodule); return retval; } int main(int argc, char const *argv[]) { wchar_t * program = Py_DecodeLocale(argv[0], NULL); if(!program){ cout<<"***Error***"<<endl; exit(1); } Py_SetProgramName(program); Py_Initialize(); PyObject *module = NULL, *result = NULL; PyRun_SimpleString("print('Hello from python')\n" "print('Hiii')"); int arr[5] = {1,3,4,5,6}; callModuleFunc(arr, 5); if(Py_FinalizeEx() < 0){ cout<<"***Error***"<<endl; exit(120); } PyMem_RawFree(program); return 0; } When I call PyObject_CallObject(myfunc, arglist), I get a segmentation fault. I am totally new to it so I'm just trying stuff from the internet. I'm using Python version 3.6 with g++ compiler 7.5. Here is my test.py: def get_lists(l1): print("Lists: ", l1) return 10 Please let me know how I can resolve this. Thanks
The Python function get_lists is not known during execution. Note: The test package is meant for internal use by Python only. It is documented for the benefit of the core developers of Python. Any use of this package outside of Python’s standard library is discouraged as code mentioned here can change or be removed without notice between releases of Python. see https://docs.python.org/3/library/test.html If the name of the imported Python file is renamed to another name (e.g. list.py) the Python function can be found. Additional Hints For the environment of the OP the problem is then solved. For my environment (Python 3.9.5) I need additionally replace the PyRun_SimpleString with: PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append(\".\")"); Otherwise the module can't be imported. Finally, it is advisable to check each function call for errors (e.g. whether it returns NULL) and to use PyErr_Print so that the actual cause of the error is printed instead of a crash due to a segmentation fault. For example an error message could look like this: AttributeError: module 'test' has no attribute 'get_lists' Test The output of the line Lists: [1, 3, 4, 5, 6] on the console shows that the Python function is called correctly when the above points are taken into account.
73,393,489
73,393,577
How can sizeof determine size of an array, if it's length is determined on runtime?
As much as I know, sizeof can only know size of something, if the size is determined at runtime. int a1; cin>>a1; int x2[a1]; cout<<sizeof(x2)/4<<"\n"; If I give input 10, sizeof says the size of the array is:40/4=10 How can sizeof know this?
So in C, sizeof can only know the size on compile-time and in c++ it can know the size even if it is determined on runtime? No, it is wrong. C && C++ (C++ VLA is a GCC extension) Compiler will emit the constant value if sizeof is used on something whose size can be determined compiler time, or will emit some code to calculate it at runtime if it is not possible to evaluate it compile time.
73,394,062
73,394,128
How to call a function from a function pointer?
How can you call a function from only a pointer to the function? For example: void print() { std::cout << "Hello World!" << std::endl;; } void run_func(void* func) { func(); // what im trying to do (doesnt actually work) } int main() { run_func(print); } Expected output: Hello World! It's a bit like how std::thread creates a thread from the pointer of a variable.
Function pointers in function parameter lists need to be wrapped in parentheses. Change the one line, either by wrapping with parentheses or using the typedef'ed function parameter, and your sample works. // Simplifies arcane function parameter synax. typedef void (*FUNC_TO_RUN)(); void print() { std::cout << "Hello World!" << std::endl;; } // Change your parameter as follows. You need to wrap function // pointers in parantheses.Or, use a typedef. // void run_func(void *func()) // void run_func(void (*func)()) // Works, but harder to read void run_func(FUNC_TO_RUN func) // Works, easier to read { func(); // what im trying to do (and now works) } int main() { run_func(print); }
73,394,348
73,394,590
How to overload 2 versions of operator<< in a C++ class
I am overloading operator<< as follows : std::ostream& operator<<(std::ostream& o, const MyClass& myobj); Now, I would like to have 2 versions of operator<<, one that would display a short description of my object, and another that would display a longer version. For example, MyClass could contain information about a client. In the short version I would display just the name, and in the long version I would display more details like birthday, address, etc. Is there a way to do that in C++ ? I know I could have a method of MyClass that receives the stream, but it would be called like this : myObj.DisplayShort(cout) or myObj.DisplayLong(cout) but I would like to stay with a syntax similar to the usual form : cout << myObj << endl;
The standard way is to create a custom formatting flag and a custom manipulator using std::ios_base::xalloc and std::ios_base::iword. So you have class MyClass { static int fmt_flag_index; enum fmt_flag { output_short, output_long }; } You initialize fmt_flag_index somewhere at the program startup: int MyClass::fmt_flag_index = std::ios_base::xalloc(); Here's your custom formatting flag ready to use. Now IO manipulators can set it: std::ios_base& myclass_short(std::ios_base& os) { os.iword(MyClass::fmt_flag_index) = static_cast<int>(MyClass::output_short); return os; } std::ios_base& myclass_long(std::ios_base& os) { os.iword(MyClass::fmt_flag_index) = static_cast<int>(MyClass::output_long); return os; } And operator<< access it: std::ostream& operator<<(std::ostream& os, MyClass& f) { switch (static_cast<MyClass::fmt_flag>(os.iword(MyClass::fmt_flag_index))) { case MyClass::output_short: ...; case MyClass::output_long: ...; } } Use it like this: MyClass myobj; std::cout << myclass_long << myobj; std::cout << myclass_short << myobj; Demo
73,394,742
73,394,967
How do I get clang/gcc to vectorize looped array comparisons?
bool equal(uint8_t * b1,uint8_t * b2){ b1=(uint8_t*)__builtin_assume_aligned(b1,64); b2=(uint8_t*)__builtin_assume_aligned(b2,64); for(int ii = 0; ii < 64; ++ii){ if(b1[ii]!=b2[ii]){ return false; } } return true; } Looking at the assembly, clang and gcc don't seem to have any optimizations to add(with flags -O3 -mavx512f -msse4.2) apart from loop unrolling. I would think its pretty easy to just put both memory regions in 512 bit registers and compare them. Even more surprisingly both compilers also fail to optimize this(ideally only a single 64 bit compare required and no special large registers required): bool equal(uint8_t * b1,uint8_t * b2){ b1=(uint8_t*)__builtin_assume_aligned(b1,8); b2=(uint8_t*)__builtin_assume_aligned(b2,8); for(int ii = 0; ii < 8; ++ii){ if(b1[ii]!=b2[ii]){ return false; } } return true; } So are both compilers just dumb or is there a reason that this code isn't vectorized? And is there any way to force vectorization short of writing inline assembly?
"I assume" the following is most efficient memcmp(b1, b2, any_size_you_need); especially for huge arrays! (For small arrays, there is not a lot to gain anyway!) Otherwise, you would need to vectorize manually using Intel Intrinsics. (Also mentioned by chtz.) I started to look at that until i thought about memcmp.
73,394,820
73,395,478
Constructing std::function from extern functions gives std::bad_function_call
I am experimenting with making pure Haskell-style I/O in C++. It's working correctly, but when I reorganize some definitions, I run into a std::bad_function_call. This is about as much as it takes to trigger the problem: //common.h #include <functional> #include <iostream> #include <utility> #include <string> class Empty {}; class State {}; template <class A> class IOMonad { public: typedef std::function<std::pair<A, State> (State)> T; }; template <class A, class B> const auto bind(typename IOMonad<A>::T ma, std::function<typename IOMonad<B>::T (A)> f) { return [ma, f] (State state) { const auto x = ma(state); return f(x.first)(x.second); }; } extern const IOMonad<std::string>::T getLine; IOMonad<Empty>::T putLine(std::string str); //externs.cpp #include "common.h" const IOMonad<std::string>::T getLine = [](State s) { (void)s; std::string str; std::cin >> str; return std::make_pair(str, State()); }; IOMonad<Empty>::T putLine(std::string str) { return [str] (State s) { (void)s; std::cout << str; return std::make_pair(Empty(), State()); }; } //main.cpp #include "common.h" const auto putGet = bind<std::string, Empty>(getLine, putLine); int main() { (void)putGet(State()); return 0; } With this setup, I get a std::bad_function_call when putGet is called. Previously, I had the contents of externs.cpp in main.cpp between including common.h and defining putGet, and everything worked fine. Something about having those functions in a different translation unit seems to be causing this problem. Also, if I keep the functions in externs.cpp, but I make putGet a local variable to main instead of a global variable, this does not happen. Another thing that makes the exception go away is folding the definition of bind into the definition of putGet, like so: const auto putGet = [] (State state) { const auto x = getLine(state); return putLine(x.first)(x.second); }; Why is this happening? Does std::function have some limitations I don't know about?
You've run afoul of the static initialization order fiasco. In your case, getLine is yet uninitialized when it's used to initialize putGet. The cardinal rule of C++ global variables is: Global variables must not depend on global variables in other compilation units for their initialization. While global variables in a single compilation unit are initialized in the order they're defined, the order in which global variables in different compilation units are initialized is unspecified. There is no guarantee that getLine will be initialized before putGet (and indeed, it seems it wasn't). To work around this, you need to either (two of which you've already found): A. Move the initialization of putGet into main so that getLine is guaranteed to be initialized before it's used or B. Don't use getLine directly in the initialization of putGet (i.e. wrap it in an extra layer of lambda). or C. Make getLine an actual function instead of a std::function holding a lambda. Objects and functions are fundamentally different in C++ and have different rules governing their lifetime. Despite their name, std::functions are objects, not functions.
73,395,003
73,395,488
A better than O(N) solution for searching a vector of sorted intervals
Given a set of sorted intervals (first >= second), sorted by the first element of the interval: {1, 3}, {1, 2}, {2, 4}, {2, 2}, {2, 3}, {3, 5}, {3, 3}, {3, 7} is there an efficient algorithm for determining the first interval that intersects a given input interval? For example: Query ({0, 0}) = returns end() Query ({2, 4}) = returns iterator to element 0 Query ({3, 8}) = returns iterator to element 0 Query ({4, 9}) = returns iterator to element 2 Query ({7, 8}) = returns iterator to element 7 Query ({8, 9}) = returns end() By efficient I mean better than O(N). I have a vague feeling there's a lower_bound or upper_bound solution to this problem but I don't have the mental horsepower to work out what it is. This is the O(N) solution that I'm unsatisfied with. #include <iostream> #include <algorithm> #include <vector> #include <string> int main() { using Interval = std::pair<int, int>; using Sequence = std::vector<Interval>; using Iterator = Sequence::const_iterator; auto Query = [](Sequence const & sequence, Interval const & interval) -> Iterator { return std::find_if(sequence.begin(), sequence.end(), [interval](Interval const & other) { return interval.first <= other.second && interval.second >= other.first; }); }; auto Print = [](Sequence const & sequence, Iterator const & iterator) -> void { if (iterator == sequence.cend()) { std::cout << "end()\n"; } else { std::cout << std::to_string(std::distance(sequence.cbegin(), iterator)) << "\n"; } }; Sequence sequence = { {1, 3}, { 1, 2 }, { 2, 4 }, { 2, 2 }, { 2, 3 }, { 3, 5 }, { 3, 3 }, { 3, 7 } }; auto result = Iterator(); result = Query(sequence, { 0, 0 }); Print(sequence, result); result = Query(sequence, { 2, 4 }); Print(sequence, result); result = Query(sequence, { 3, 8 }); Print(sequence, result); result = Query(sequence, { 4, 9 }); Print(sequence, result); result = Query(sequence, { 7, 8 }); Print(sequence, result); result = Query(sequence, { 8, 9 }); Print(sequence, result); } Output: end() 0 0 2 7 end()
There cannot be a faster than linear algorithm. Consider the input where the first value of each element is 0 and the second value is random uniform over some range. Consider the query to be {x,x+1} where x is in the same range. Since you want "the first interval that intersects a given input", the sorting is now useless. You must scan it all. Hence, you cannot beat O(N).
73,395,594
73,415,175
Generic function template deduction over existing function overloads
I'm writing an extensible library where it has become convenient to overload STL's to_string() for custom types. For that I've designed a generic overload template that throws an exception if not specialized: namespace std { // ... template < typename T > inline std::string to_string(const T& in, const std::string& separator = ",") { throw std::runtime_error("invalid call to " + std::string(__func__) + "(): missing template specialization for type " + typeid(T).name()); } } // namespace std This is useful mainly because the description will provide a clear explanation on the issue and how to solve it, and avoids having to use polymorphism to implement derived implementations (the function is only marginally/optionally required for certain applications such as serialization, I/O, etc.). However, the issue with this approach is that the overload template will be deduced even with types where <string> already provides an overload for. My question is if is there a way to force the non-template overload to be used only when there is no non-template definition available?
I recommend that you do not generate a runtime exception for something that should be a compilation failure. It could look like this: #include <string> #include <type_traits> namespace extra { template <class T> inline std::string to_string(const T& in) { static_assert(std::is_arithmetic_v<T>, "T needs extra::to_string overload"); return std::to_string(in); } } // namespace extra ... and then you don't need to check if it's an arithmetic type at the call site: template <class T> void func(const T& arg) { std::cout << extra::to_string(arg); } Demo
73,395,658
73,395,889
Xmemory Access violation reading location 0xFFFFFFFFFFFFFFFF
Whenever I run this code, I get Exception thrown at 0x00007FF6CA077375 in console test.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF. coming from a file named "xmemory", what it is supposed to do is loop through different folders looking for a specified file, so it uses a bit of recursion, I'm not sure if that's part of the problem, it's still a WIP but I need to do something about the Exception first. I am using Visual Studio 17.3.0, C++20 Standard (/std:c++20) and MinGW gcc compiler, in case that helps #include <string> #include <vector> #include <iostream> #include <filesystem> using std::filesystem::directory_iterator; namespace fs = std::filesystem; using namespace std; string endstr(string str, string delim) { int i = str.length(); while (str[i] != delim[0]) { if (i == 0) break; i--; } return str.substr(i + 1, str.length()); } string start = "C:\\"; vector<string> explored; string fl; string *dir; string getFile(const char* item, string startPath) { for (const auto& file : directory_iterator(startPath)) { fl = file.path().string(); cout << fl << endl; if (fl == endstr(item, "\\")) { return fl; } else if (file.is_directory()) { if (find(explored.begin(), explored.end(), fl) != explored.end()) { getFile(item, fl); } } else { break; } } explored.push_back(fl); } int main() { getFile("Terraria.exe", "C:\\"); } Edit: debeg logs n stuff Debug 'console test.exe' (Win32): Loaded 'C:\Users\willk\source\repos\console test\x64\Debug\console test.exe'. Symbols loaded. 'console test.exe' (Win32): Loaded 'C:\Windows\System32\ntdll.dll'. 'console test.exe' (Win32): Loaded 'C:\Windows\System32\kernel32.dll'. 'console test.exe' (Win32): Loaded 'C:\Program Files\Avast Software\Avast\aswhook.dll'. 'console test.exe' (Win32): Loaded 'C:\Windows\System32\KernelBase.dll'. 'console test.exe' (Win32): Loaded 'C:\Windows\System32\msvcp140d.dll'. 'console test.exe' (Win32): Loaded 'C:\Windows\System32\vcruntime140d.dll'. 'console test.exe' (Win32): Loaded 'C:\Windows\System32\vcruntime140_1d.dll'. 'console test.exe' (Win32): Loaded 'C:\Windows\System32\ucrtbased.dll'. The thread 0x5cec has exited with code 0 (0x0). Exception thrown at 0x00007FF703A47415 in console test.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF. Build Build started... 1>------ Build started: Project: console test, Configuration: Debug x64 ------ 1>console test.cpp 1>C:\Users\willk\source\repos\console test\console test\console test.cpp(14,25): warning C4267: 'initializing': conversion from 'size_t' to 'int', possible loss of data 1>C:\Users\willk\source\repos\console test\console test\console test.cpp(45): warning C4715: 'getFile': not all control paths return a value 1>console test.vcxproj -> C:\Users\willk\source\repos\console test\x64\Debug\console test.exe 1>Done building project "console test.vcxproj". ========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
What goes wrong here is that getFile returns a bad string (uninitialized/garbage due to not returning any string) after it reaches explored.push_back(fl);. Then back in main, that string is destroyed, but that fails, so you're seeing an access violation coming out of the deep parts of the implementation of the destructor of basic_string. In general, not returning something from a function that is supposed to return something, is a recipe for Bad Things happening. While "debug output" rarely contains anything useful (unless you've put it there yourself), stack trace is generally useful because it helps you pin-point what the program was doing when it died:
73,395,826
73,399,150
C++ templates as predicates for std::find_if: auto for parameters in lambdas vs free in functions vs templated functions
Please do help to understand why auto for parameter in equivalent lambda will build correctly, but if I will use free function with auto for parameters, or templated functions, it won't. It's something I forgot about template deduction? Or new changes in C++? Example to run (builts on MSVS 2022 compiler): import <string>; import <algorithm>; auto isAllowedHandlerSymbolLambda = [](auto const& s) { if (std::isalnum(s)) return true; if (s == '_') return true; return false; }; auto isAllowedHandlerSymbolFreeFunc(auto const& s) { if (std::isalnum(s)) return true; if (s == '_') return true; return false; } template< class Symbol > auto isAllowedHandlerSymbolTemplateFunc(Symbol const& s) { if (std::isalnum(s)) return true; if (s == '_') return true; return false; } int main() { std::string str{ "Something something, thank you for your time!" }; std::find_if_not(str.cbegin(), str.cend(), isAllowedHandlerSymbolLambda); // yes! //std::find_if_not(str.cbegin(), str.cend(), isAllowedHandlerSymbolFreeFunc); // no //std::find_if_not(str.cbegin(), str.cend(), isAllowedHandlerSymbolTemplateFunc); // nope! }
lambda are similar to functor class, not function: struct lamba_unique_name { template <typename T> auto operator()(const T& s) const { /* ...*/ } // ... }; lamba_unique_name isAllowedHandlerSymbolLambda; It is its operator which is templated, not the class, So deduction for std::find_if_not predicate is just that type. For your template functions, you would need to specify which specialization you provide: std::find_if_not(str.cbegin(), str.cend(), &isAllowedHandlerSymbolTemplateFunc<char>);
73,395,878
73,399,600
Is it advisable to inherit from std::optional?
I understand that it the most of the time not good to inherit from STL classes (except for std::exception, etc.) because for example of the lacking virtual destructor and probably other reasons. However, I have the following code: typedef std::optional<uint64_t> ID; struct IDS { static ID create(); static void doSomething(ID id); // more static methods }; Inheriting from the optional would allow me to reuse the same name IDS vs ID while using it as above (except for removing the static before doSomething). Basically it makes using the class easier without loosing the capabilities of optional. Is this still a bad idea? And if yes, what can go wrong?
Is this still a bad idea? And if yes, what can go wrong? As you already stated, inheriting from classes without virtual destructor leads to UB when destroyed from base class. In addition, when inheriting from 3rd party library classes, you also depends of future interface. You might be in trouble when/if std::optional adds functions with same name (especially constructors). Depending of the "conflicts", your code might no longer compile, or worst, select the wrong overload and behave not as you expect. Note that it is not only member functions, but also apply to free functions and so ADL. So it also applies when removing methods/function/overload (unlikely for std though). Less immediate problematic, even without conflicts, is that interface of your class change with function not necessary matching your expected interface.