question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
71,859,064
71,859,223
Are pointer to member functions not callable object
I am reading C++ Primer 5th edition and there I came across the following statement: As a result, unlike ordinary function pointers, a pointer to a member is not a callable object; these pointers do not support the function-call operator. So my question is: Is the highlighted part correct according to the standard? My current understanding and intuition are that functionally they behave in the same manner, so a pointer to a member function should also be a callable object(as its name suggest). Note that I am not asking whether the book is correct in saying that member function pointers do not support the function call operator. Because I already know that that part of the statement is correct. What I am asking is whether the pointer to the member function is a callable object according to the standard.
What i am asking is that whether pointer to member function are callable object according to the standard. Yes, a pointer to a member function is a callable object according to the standard. From func.def#4: A callable object is an object of a callable type. And from func.def#3: A callable type is a function object type ([function.objects]) or a pointer to member. Thus, the highlighted part of the quoted statement that says "a pointer to member is not a callable object" from C++ Primer is incorrect according the standard.
71,859,149
71,878,538
Creating a DLL using MSVC's cl
I am attempting to get an understanding of how building and linking works, since there's a library I want to compile into a DLL. I do not have control over the tool that will be used to compile - It's going to be the msvc tools invoked via command line. To that end, I've managed to locate a tutorial on creating DLLs that does not use Visual Studio. it's for mingw, but I've managed to make it work with cl I've managed to translate part of the process to use with the msvc tools: gcc -c -o add.o add.c -D ADD_EXPORTS was translated into cl /c /D ADD_EXPORTS add.c I was unable to fully translate the line that follows: gcc -o add.dll add.o -s -shared -Wl,--subsystem,windows But the following worked: link /DLL /NOENTRY add.obj and created .exp, .lib, and .dll files. The -s switch doesn't seem important (it strips some info, so I'm guessing at worst I'll get a slightly larger file) I then managed to create a .obj file from addtest.c, link it (against the .lib file), and got an .exe that runs perfectly fine as long as the dll is keeping it company in the same folder. On to a harder problem: The library I ultimately want to have compiled after playing around with the #includes and moving some files around to make sure everyone can find their header, I compiled each source file (for windows - to my understanding, _WIN32 is automatically defined when preprocessing) the same way I did add.c (sans ADD_EXPORTS), plus a file of my own, called Source.cpp (I did not create a header for it) #include "serial/serial.h" #include <combaseapi.h> using serial::Serial; using std::string; using std::vector; using serial::PortInfo; Serial* sp = NULL; extern "C" { __declspec(dllexport) bool __cdecl createConnection(const char* port, uint32_t baudrate) { try { sp = new Serial(port, baudrate); return true; } catch (...) { return false; } } } After making a .obj file of them all, I attempted to invoke the linker, with all of the .obj files I've generated, using link /DLL /NOENTRY Source.obj list_ports/list_ports_win.obj win.obj serial.obj for which I got 134 errors Information on how to create a DLL without visual studio seems to be quite scarce, and I can't find anything useful about the errors I've looked up (no common mistake I could find when looking up the error + symbol) What's the problem here? Edit: Thanks to a comment I managed to find out I have a problem linking to CRT libraries. This helped me cut down on the number of errors, I will see if I can figure anything out about the new output I get and edit further new linking commands: link /DLL /NOENTRY Source.obj list_ports/list_ports_win.obj win.obj serial.obj /LIBPATH:"C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Redist/MSVC/14.29.30036/x64/Microsoft.VC142.CRT" Edit 2: compiling the source files with cl /c /clr source_file led to significantly fewer errors when linking without specifying the LIBPATH. I think I might even be able to resolve all those by myself. I will continue to work on this later.
Note that Serial last official version (v1.2.1) was released in April 2015 (20150422), and the activity has dropped significantly since then. Please check [SO]: Linking to CRT (unresolved external symbol WinMainCRTStartup) (@CristiFati's answer) (just posted) before going further. I just built the package and placed the artefacts at [GitHub]: (master) CristiFati/Prebuilt-Binaries - Prebuilt-Binaries/Serial/v024f80634f40073a41be43e956b5ebaca17f6167 (the original code only builds a static library, I enhanced it to also build a dynamic one). Follow the download and "install" instructions. The attempted scenario is building a .dll from your source code, that uses the downloaded Serial library. Output: [cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q071859149]> sopr.bat ### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ### [prompt]> "c:\Install\pc032\Microsoft\VisualStudioCommunity\2019\VC\Auxiliary\Build\vcvarsall.bat" x64 >nul [prompt]> dir /b Source.cpp [prompt]> set LIBSERIAL_DIR=c:\Program Files\WjwWood\Serial\024f80634f40073a41be43e956b5ebaca17f6167 [prompt]> :: Build with static libserial [prompt]> cl /nologo /I"%LIBSERIAL_DIR%\include" /EHsc /MD /c Source.cpp /FoSource_stat.obj Source.cpp [prompt]> link /NOLOGO /DLL /LIBPATH:"%LIBSERIAL_DIR%\lib" Source_stat.obj libserialstatic.lib Creating library Source_stat.lib and object Source_stat.exp [prompt]> dir /b Source.cpp Source_stat.dll Source_stat.exp Source_stat.lib Source_stat.obj [prompt]> :: Build with dynamic libserial [prompt]> cl /nologo /I"%LIBSERIAL_DIR%\include" /EHsc /MD /DLIBSERIAL_DYNAMIC /c Source.cpp /FoSource_dyn.obj Source.cpp [prompt]> link /NOLOGO /DLL /LIBPATH:"%LIBSERIAL_DIR%\lib" Source_dyn.obj libserial.lib Creating library Source_dyn.lib and object Source_dyn.exp [prompt]> [prompt]> dir Volume in drive E is SSD0-WORK Volume Serial Number is AE9E-72AC Directory of e:\Work\Dev\StackOverflow\q071859149 22/04/15 01:58 <DIR> . 22/04/15 01:58 <DIR> .. 22/04/15 01:50 394 Source.cpp 22/04/15 01:58 17,920 Source_dyn.dll 22/04/15 01:58 704 Source_dyn.exp 22/04/15 01:58 1,778 Source_dyn.lib 22/04/15 01:57 47,856 Source_dyn.obj 22/04/15 01:55 41,472 Source_stat.dll 22/04/15 01:55 707 Source_stat.exp 22/04/15 01:55 1,790 Source_stat.lib 22/04/15 01:55 46,299 Source_stat.obj 9 File(s) 158,920 bytes 2 Dir(s) 24,132,493,312 bytes free A "graphical" comparison between the 2 generated .dlls. Notice that the variant linked with libserial.lib requires libserial.dll:
71,859,765
71,860,252
Why is std::move generating instructions here?
I heard time and again that std::move(t) is more or less only a fancy way of saying static_cast<T&&>(t) and would not generate any instructions. When I was playing around now with std::move on godbolt in order to better understand move semantics I saw that it does (or at least may) generate instructions. In this example #include <iostream> using namespace std; struct S { S() { cout << "default ctor" << endl; } S(S&& s) { i = s.i; s.i = 0; cout << "move ctor" << endl; } int i; }; void foo(S s) { cout << "Foo called with " << s.i << endl; } int main() { S s; foo(static_cast<S&&>(s)); foo(std::move(s)); } the calls to foo lead to the following assembly output ; ... snip ... lea rdi, [rbp - 16] lea rsi, [rbp - 8] call S::S(S&&) [base object constructor] lea rdi, [rbp - 16] call foo(S) lea rdi, [rbp - 8] call std::remove_reference<S&>::type&& std::move<S&>(S&) lea rdi, [rbp - 24] mov rsi, rax call S::S(S&&) [base object constructor] lea rdi, [rbp - 24] call foo(S) ; ... snip ... std::remove_reference<S&>::type&& std::move<S&>(S&): # @std::remove_reference<S&>::type&& std::move<S&>(S&) push rbp mov rbp, rsp mov qword ptr [rbp - 8], rdi mov rax, qword ptr [rbp - 8] pop rbp ret Can someone please explain this to me? I can't much sense of what this std::remove_reference<S&>::type&& std::move<S&>(S&) function is supposed to do and why there is this apparent contraction to what's commonly told.
You are compiling without optimisations. So you see exactly what is written without any attempt to simplify or inline functions. Generated code is roughly eqivalent to what type&& foo(type& x) { return x; } would generate, which is what move does. Studying assembly generated without optimisations turned on is exercise in futility.
71,859,923
71,863,555
C# equivalent of C++ deferred async execution?
I'm relatively new to C# and I'm trying to replicate an asynchronous call that has already been written in C++. This has been a little difficult because while I can easily understand the async/await keywords in C#, I'm stuck on the concept of deferred launch in that language. Here is the original code: bool runMethod(const cv::Mat& param1, float& param2, std::pair<float, float>& param3, std::pair<int, int>& param4) { auto async_lazy{ std::async(std::launch::deferred, [&param1, &param2, &param3, &param4] { const MyClass ret{ MyClass::getInstance()->Method(param1}; if (ret.status) { //Do work... } return ret.status; }) }; return async_lazy.get(); } It may be relevant to add that the "Method" method being called is not async itself. I also took a look at the first example on this page, that says a Task<(T)> by itself is async. There also seems to be no use of the await keyword: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1?view=net-6.0 Would that example reproduce the functionality of the above code?
If my quick google search was correct then launch::deferred means lazy evaluation on the calling thread. In that case, using a task might not be a good idea, they are not meant for lazy evaluation because: Awaiting them or taking their result does not start them if they were not started already (and starting them while they are already running throws an exception) You can't run them on the calling thread, they represent an asynchronous operation (such as IO) or work running on a ThreadPool thread Even if you could run them on the calling thread if they were not started yet, they are typically created using Task.Run() or Task.Factory.StartNew() which starts them right away Perhaps you could use System.Lazy<T> instead. It seems to do what you need, including several thread safety options.
71,859,992
71,884,979
What is causing this memory access violation error (0xC0000005) when using Eigen with "-march=native"?
I am rewriting some c++ code (originally written in Matlab as a MEX function) in codeblocks so that I can use debugging and profiling tools designed for c++. The code I am rewriting uses Eigen and SIMD intrinsic instructions, so I need to compile with the -march=native flag. I was getting a memory access violation error when running my main project. Here is a slimmed down version of the code that causes the issue: #include <iostream> #include <fstream> #include <string> #include <sys/stat.h> #include <immintrin.h> #include <Eigen/Dense> #include "Parameters.h" using namespace std; int main() { Parameters p; p.na = 16; p.TXangle = Eigen::VectorXd::LinSpaced(p.na,0,p.na-1); cout << p.TXangle << endl; cout << "Hello world!" << endl; return 0; } where Parameters is a custom class defined with the following two files: Parameters.h #ifndef PARAMETERS_H_INCLUDED #define PARAMETERS_H_INCLUDED class Parameters { public: int na; Eigen::VectorXd TXangle; Parameters(); }; #endif // PARAMETERS_H_INCLUDED Parameters.cpp #include <string> #include <Eigen/Dense> #include "Parameters.h" Parameters::Parameters() { //ctor } The line that's breaking is when p.TXangle is initialized. At that point, the program throws the (0xC0000005) error. If I don't compile with '-march=native' then the error doesn't happen and the program runs fine. When building with '-march=native' I also get several alignment warnings. My computer supports upto AVX2 instructions and I'm compiling with MinGW GCC (not sure how to check the version of gcc on codeblocks). gcc version is 8.1.0 Update: Is this the value @Sedenion was asking about in the comments? This is the exact line the debugger stops at: **Update: ** Based on the discussion in the comments, the disassembler shows that the code is at this assembly instruction when it fails: I'm struggling to interpret this, reading assembly is still a bit new to me. Here are the registers at that same point:
I managed to reproduce this problem using Eigen 3.4.0 and mingw (gcc 8.1.0 with -mavx -m64 -std=c++17 -g) on Windows using AVX (-mavx, also enabled by -march=native for the OP). As already suspected by people in the comments, it is certainly the issue that mingw-gcc fails to align stack variables correctly to 32 bytes, which is required by AVX (compare the bug issue for gcc, also see e.g. this post). The crash is not related to the use of VectorXd (which should not suffer from it since it uses dynamic memory allocations). Rather, the Eigen::VectorXd::LinSpaced() call is the issue. In Eigen, this eventually calls the following function involving AVX instructions in PacketMath.h: template<> EIGEN_STRONG_INLINE Packet4d plset<Packet4d>(const double& a) { return _mm256_add_pd(_mm256_set1_pd(a), _mm256_set_pd(3.0,2.0,1.0,0.0)); } In this call, temporary stack variables are involved which are not 32 byte aligned by mingw. At one point, an aligned mov vmovapd is attempted to such a non-aligned address: mov rax,QWORD PTR [rbp+0x10] vmovapd YMMWORD PTR [rax],ymm0 For example, in one run, I got rax=0x67f890 which is only 16 byte but not 32 byte aligned. A minimal reproducible example that captures the behavior is the following (https://godbolt.org/z/qbE6z1nb8, note that mingw is not supported on godbolt, so the problem does not appear there): #include <iostream> #include <immintrin.h> __m256d Set(const double&) { __m256d temp = _mm256_setzero_pd(); // Crashes on mingw return temp; } int main() { Set(2); std::cerr << "End" << std::endl; } The unused parameter to Set() is just there to get an offset on the stack to trigger the issue. It crashes using mingw-gcc (with -mavx -m64) but runs fine when compiled with clang or MSVC on Windows. It also runs fine on all Linux compilers I have tried. So, in short, your code is correct and the crash occurs in Eigen. There is no "magic switch" for gcc to fix this. Hence, I guess you have 3 options: Wait for the mingw problem to get fixed. According to the posts, it still persists in gcc 11.2.0. But considering the long history, I doubt it will get fixed soon. Do not compile with AVX or higher (or -march=native) and stick to <=SSE4.2 instead. Of course, this might impact performance. I'd advise to profile to be sure if this is the case for you. Use another compiler such as clang or MSVC.
71,860,358
71,872,418
C++ function not exported by .so seemingly because of pybind11 parameters
I am currently trying to define a shared library that I aim to use from a Python C++ extension as well as from vanilla C++ applications. I managed to build the shared library, and tried to link a simple C++ application against it to test its functionalities, but one of the functions of the shared library is treated as an undefined reference by the linker. After checking with nm --demangle --dynamic --defined-only --extern-only libmylib.so, I realized the function is not being exported by the shared library, but I have no idea why. The function's signature is as follows: void bootstrap_mylib(std::vector<std::string> python_path, std::vector<std::string> python_scripts, std::string interface_module, std::function<void (pybind11::module_, pybind11::object)> interface_module_initializer); Everything goes well if I comment out the last parameter, so the problem seems to be coming from the way I declare the dependencies with pybind11 somehow. Here are the relevant parts of my CMakeLists.txt: set(CMAKE_CXX_COMPILER /usr/bin/g++) project(monilog LANGUAGES CXX VERSION 0.0.1) set(PYBIND11_PYTHON_VERSION 3.8) find_package(pybind11 REQUIRED) include_directories(${PYTHON_INCLUDE_DIRS}) add_library(mylib SHARED MyLib.cc MyLib.h) set_property(TARGET mylib PROPERTY CXX_STANDARD 17) target_link_libraries(mylib ${PYTHON_LIBRARIES}) set_target_properties(mylib PROPERTIES VERSION ${PROJECT_VERSION}) set_target_properties(mylib PROPERTIES SOVERSION 1) set_target_properties(mylib PROPERTIES PUBLIC_HEADER MyLib.h) Any idea of what I might be doing wrong? Edit: minimal working example Here is a minimal example of my problem, consisting of the following files: example.h #include <pybind11/stl.h> namespace Example { void simple_func(std::string some_string); void pybind11_func(pybind11::function some_func); } example.cc #include "example.h" namespace Example { void simple_func(std::string some_string) { std::cout << "Simple function" << '\n'; } void pybind11_func(pybind11::function some_func) { std::cout << "Pybind11 function" << '\n'; } } CMakeLists.txt cmake_minimum_required(VERSION 3.10) cmake_policy(SET CMP0074 NEW) # SET VARIABLES set(CMAKE_CXX_COMPILER /usr/bin/g++) set(CMAKE_CXX_STANDARD 17) project(example CXX) set(PYBIND11_PYTHON_VERSION 3.8) find_package(pybind11 REQUIRED) # include_directories(${PYTHON_INCLUDE_DIRS}) include_directories(${pybind11_INCLUDE_DIRS}) add_library(example SHARED example.cc example.h) target_link_libraries(example ${PYTHON_LIBRARIES}) When I build the project, if I then search for func in the exposed symbols, I get the following result: > nm -D libexample.so | grep "func" 00000000000039d9 T _ZN7Example11simple_funcENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE pybind11_func is thus not exported, while simple_func is correctly exported.
Namespace pybind11 has hidden visibility. /usr/include/pybind11/detail/common.h:# define PYBIND11_NAMESPACE pybind11 __attribute__((visibility("hidden"))) so all functions that have anything to do with that namespace (like having an argument type from it) are also hidden. You can override this by explicitly setting visibility to default: __attribute__((visibility("default"))) void bootstrap_mylib( ... )
71,860,616
71,860,871
C++ method resolution by name
I am wondering if there is a way in C++ to write a function that will resolve object methods based on the method name alone (specific examples below). Run time or compile time resolution (such as templates) would both be acceptable. I have read a little bit about template metaprogramming, but I was hoping I might get some info as to whether that is even the appropriate direction for my problem before delving to deep into that. Essentially, I am trying to write a function that will call non-static methods of a passed in object, such as this psuedocode: exampleFunction(Object myObject, ObjectMethod myObjectMethod) { // do some stuff here myObject.myObjectMethod(arguments); // do some more stuff here } In this case, I cannot hard-code a method into exampleFunction and simply have every object that I call it with have that method name. I must have the flexibility to call exampleFunction with a variety of methods, and have each of those methods properly resolve. Further, I must be able to resolve methods, and those methods must be non-static. In my case, I must be able to modify internal, private object members on the method call. Without going into the details, these constraints are an artifact of the system I am working on that I cannot change. As I previously stated, both compile time and run time solutions are acceptable. So something like this with templates would work perfectly well in my case as well: template <ObjectMethodName methodName> exampleFunction(Object myObject) { // do some stuff here myObject.methodName(arguments); // do some more stuff here } Any thoughts on whether this is possible, as well as information on possible implementation would be appreciated.
You can make exampleFunction a function template that has the first parameter of type of the object, the second parameter can be a reference to a pointer to a member function and the third parameter is a function parameter pack that denotes the arguments to be passed when calling the member function. #include <iostream> class Actions { public: Actions(){} void doSmthg(){ std::cout<<"do something called"<<std::endl; } void multipleArgs(int, int) { std::cout<<"multiple int args called"<<std::endl; } }; class Entity { public: void func(double) { std::cout<<"func called"<<std::endl; } }; template<typename T, typename Callable, typename... Args> void exampleFunction(T obj, const Callable& callable, const Args&... args){ std::cout<<"exampleFunction called"<<std::endl; //call the function on the passed object (obj.*callable)(args...); } int main() { Actions action; exampleFunction(action, &Actions::doSmthg); //calls doSmthg member function with 0 arguments exampleFunction(action, &Actions::multipleArgs, 5,7);//calls multipleArgs member function with 2 int arguments Entity e; exampleFunction(e, &Entity::func,4.4); //calls func member function } Demo The output of the above program is: exampleFunction called do something called exampleFunction called multiple int args called exampleFunction called func called
71,860,748
71,860,865
Logical operators don't output correct results
Here is the code that I'm struggling with #include <iostream> #include <string> using namespace std; int main() { int a{ 6 }, b{ 9 }; cout << !(a < 5) && !(b >= 7); } Every time I run this code it outputs 1. Why doesn't it output 0?
You've been tripped up by the semantic overloading we give the << operator in C++. This operator comes from C, where it is used exclusively for bit-shifting integers. Because of that, it has a lower precedence than the && operator. C++'s use of the << operator for stream insertion doesn't change that. The << will be evaluated before the &&. Thus cout << !(a < 5) && !(b >= 7); first inserts !(a<5) (true, since a==6) into the stream, printing a 1. Then it evaluates the return value of that (a reference to cout), converts it to boolean, then evaluates the && (essentally (!cout.fail() && !(b>=7))), discarding the result. You need more parentheses: cout << (!(a < 5) && !(b >= 7)); However, cout << (a>=5 && b < 7); would be clearer.
71,861,504
71,861,597
What happens when a paddr_t is passed to a linked list that is expecting unsigned on a 64bit system?
After looking harder at the code, I figured out the answer to my question. I was mistaken in thinking the initial declaration of linked list meant all future types had to be the same The code I am looking at is for linked list insertion. The linked list is used to store logical addresses. The linked list is defined as unsigned 32 bit, but the addresses being inserted are defined as void*. A logical address is cast to paddr_t and is then inserted. paddr_t was used to be reverse compatible with 32bit or 64 bit systems, since the void* size changes. When the paddr_t is passed to the insert function, will the insert function parameter be promoted to paddr_t? Will the linked list member be promoted as well once the insertion is complete? Abbreviated example of the code LinkedList <unsigned> foo; unsigned bar = 1001; void* Laddr = &bar; foo.insert((paddr_t)Laddr);
Assuming a common-sense definition of LinkedList: You don't pass paddr_t to the insert function. You pass unsigned to the insert function. If you try to pass paddr_t, the compiler will add an (unsigned) cast for you, and may or may not emit a warning. If paddr_t and unsigned are the same type, it's unlikely that you'll get a warning, and extremely likely that it will work fine. If paddr_t is bigger than unsigned, and you have a paddr_t that doesn't fit in an unsigned, then the extra bits will be removed to make it fit in unsigned, and that number will be stored in the list, and whatever code get the number back out of the list and converts it back to paddr_t will not work properly because it gets the wrong number.
71,862,558
71,862,688
UI blocks while the program is running in QT c++
I have an application in QT with ui. And also I have heavy calculations. When calculations starts, my program stops responding while calculations are running. I wanted to do this via multithreading, but I cannot correctly implement this. I tried to do it with default lib thread: void HeavyCalculations() { // some heavy calculations } void MainWindow::on_pushButton_3_clicked() { // context is some object in whose context the finished signal should be called, so most likely your MainWindow auto futureWatcher = new QFutureWatcher<void>(this); QObject::connect(futureWatcher, &QFutureWatcher<void>::finished, this, compulationFinished); QObject::connect(futureWatcher, &QFutureWatcher<void>::finished, futureWatcher, &QFutureWatcher<void>::deleteLater); auto future = QtConcurrent::run( PackBytes ); futureWatcher->setFuture(future); } but, where to write th.join()? If I put this in the next line, it won't make sense. So, do you have any suggestions? UPD mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void on_pushButton_clicked(); void on_pushButton_3_clicked(); void compulationFinished(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
See the Multithreading Technologies article in Qt - the "simplest" solution is probably to use QtConcurrent for running the computation, and QFutureWatcher for getting notified about when the computation is finished. So. something along those lines: void MainWindow::on_pushButton_3_clicked() { // context is some object in whose context the finished signal should be called, so most likely your MainWindow auto futureWatcher = new QFutureWatcher<void>(this); QObject::connect(futureWatcher, &QFutureWatcher<void>::finished, this, &MainWindow::computationFinished); QObject::connect(futureWatcher, &QFutureWatcher<void>::finished, futureWatcher, &QFutureWatcher<void>::deleteLater); auto future = QtConcurrent::run( HeavyCalculations ); futureWatcher->setFuture(future); } void MainWindow::computationFinished() { // tell the user computation is finished or something } With the above implementation, you don't need your own QThread object, and therefore also don't need to call join on it. Still, you are notified when the thread is finished (the function computationFinished is called in the above example), so you can for example show the result of your computation to the user. Side note: of course you need to add void computationFinished(); to your class declaration (unless you need it somewhere else, in the private slots: section).
71,863,108
71,863,149
What happen when we assign a reference to a variable?
void func(){ int a = 1; int b = a; // copy assignemnt int &c = a; // nothing? int d = c; // nothing? } For example, when we assign reference c to d, is there anything triggered (move, copy, etc.)? What if d is an instance member? Is it safe to store a local variable reference into it?
when we assign reference c to d, is there anything triggered (move, copy, etc.)? Your terminology's getting me confused! If you're talking about d and c, I assume you're referring to int d = c; I'd describe that as "assigning whatever c refers to to d". "Assign reference c to d" sounds too much like int& c = d;. Your code has: int &c = a; // nothing? int d = c; // nothing? In the first line, nothing happens that you need to care about... c can be thought of as a nickname or alias for a. (At a hidden implementation level, it may or may not help to image c being an automatically-dereferenced pointer variable, and your int &c = a; being similar to int* p_c = &a; - it doesn't copy or move any int values around, nor change a in any way.) In the second line, the variable d is assigned a copy of the value from a. What if d is an instance member? Is it safe to store a local variable reference into it? You're thinking of this the wrong way. When you assign to a member reference, you're assigning to the referenced object, and not the reference itself. The referenced object will be another int somewhere, and assignment from one int to another works as usual.
71,863,760
71,863,840
How to access data in a struct? C++
Just quick one, how should I go about printing a value from a struct? the 'winningnums' contains a string from another function (edited down for minimal example) I've tried the below but the program doesnt output anything at all, is my syntax incorrect? struct past_results { std::string date; std::string winningnums; }; int main(){ past_results results; std::cout << results.winningnums; return 0; } EDIT: just to give some more insight, here's the function that populates my struct members. Is it something here im doing wrong? //function to read csv void csv_reader(){ std::string line; past_results results; past_results res[104]; int linenum = 0; //open csv file for reading std::ifstream file("Hi S.O!/path/to/csv", std::ios::in); if(file.is_open()) { while (getline(file, line)) { std::istringstream linestream(line); std::string item, item1; //gets up to first comma getline(linestream, item, ','); results.date = item; //convert to a string stream and put into winningnums getline(linestream, item1); results.winningnums = item1; //add data to struct res[linenum] = results; linenum++; } } //display data from struct for(int i = 0; i < linenum; i++) { std::cout << "Date: " << res[i].date << " \\\\ Winning numbers: " << res[i].winningnums << std::endl; } }
is my syntax incorrect? No, it's just fine and if you add the inclusion of the necessary header files #include <iostream> #include <string> then your whole program is ok and will print the value of the default constructed std::string winningnums in the results instance of past_results. A default constructed std::string is empty, so your program will not produce any output. Your edited question shows another problem. You never call csv_reader() and even if you did, the result would not be visible in main() since all the variables in csv_reader() are local. Given a file with the content: today,123 tomorrow,456 and if you call csv_reader() from main(), it would produce the output: Date: today \\ Winning numbers: 123 Date: tomorrow \\ Winning numbers: 456 but as I mentioned, this would not be available in main(). Here's an example of how you could read from the file and make the result available in main(). I've used a std::vector to store all the past_results in. It's very practical since it grows dynamically, so you don't have to declare a fixed size array. #include <fstream> #include <iostream> #include <sstream> // istringstream #include <string> // string #include <utility> // move #include <vector> // vector struct past_results { std::string date; std::string winningnums; }; // added operator to read one `past_results` from any istream std::istream& operator>>(std::istream& is, past_results& pr) { std::string line; if(std::getline(is, line)) { std::istringstream linestream(line); if(!(std::getline(linestream, pr.date, ',') && std::getline(linestream, pr.winningnums))) { // if reading both fields failed, set the failbit on the stream is.setstate(std::ios::failbit); } } return is; } std::vector<past_results> csv_reader() { // not `void` but returns the result std::vector<past_results> result; // to store all past_results read in // open csv file for reading std::ifstream file("csv"); // std::ios::in is default for an ifstream if(file) { // loop and read records from the file until that fails: past_results tmp; while(file >> tmp) { // this uses the `operator>>` we added above // and save them in the `result` vector: result.push_back(std::move(tmp)); } } return result; // return the vector with all the records in } int main() { // get the result from the function: std::vector<past_results> results = csv_reader(); // display data from all the structs for(past_results& pr : results) { std::cout << "Date: " << pr.date << " \\\\ Winning numbers: " << pr.winningnums << '\n'; } }
71,863,881
71,865,452
using -march switch for gcc does not make a difference in terms of run-time speed
I built a small program (~1000 LOC) using GCC 11.1 and ran it for many iterations both with and without enabling -march=native but overall there was no difference in terms of program execution time (measured in milliseconds). But why? Because it's single-threaded? Or is my stone age hardware (1st gen i5, Westmere microarchitecture with no AVX stuff) not capable enough? A few lines from my Makefile: CXX = g++ CXXFLAGS = -c -std=c++20 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -O3 -march=native -flto LDFLAGS = -O3 -flto Here (Compiler Explorer) is a free function from the program for which GCC does not generate SSE instructions: [[ nodiscard ]] size_t tokenize_fast( const std::string_view inputStr, const std::span< std::string_view > foundTokens_OUT, const size_t expectedTokenCount ) noexcept { size_t foundTokensCount { }; if ( inputStr.empty( ) ) [[ unlikely ]] { return foundTokensCount = 0; } static constexpr std::string_view delimiter { " \t" }; size_t start { inputStr.find_first_not_of( delimiter ) }; size_t end { }; for ( size_t idx { }; start != std::string_view::npos && foundTokensCount < expectedTokenCount; ++idx ) { end = inputStr.find_first_of( delimiter, start ); foundTokens_OUT[ idx ] = inputStr.substr( start, end - start ); ++foundTokensCount; start = inputStr.find_first_not_of( delimiter, end ); } if ( start != std::string_view::npos ) { return std::numeric_limits<size_t>::max( ); } return foundTokensCount; } I want to know why? Maybe because it's not possible to vectorize such code? Also, another thing I want to mention is that the size of the final executable did not change at all and I even tried -march=westmere and -march=alderlake to see if makes any difference in size but GCC generated it with the same size.
I think you should be specifying -march=native as part of LDFLAGS as well, so -flto is targeting the same machine. But it seems your code-gen is respecting your specified arch since you say -march=alderlake make code that crashed with SIGILL, probably on an AVX encoding of a vector instruction. It's quite possible that -mtune=generic makes the same tuning decisions as -march=native, and that there's nothing that benefits from anything more than SSE2. Your CPU supports SSE4.2 and popcnt, but baseline for x86-64 is already SSE2, same vector width just missing some instructions, especially for dword and qword element sizes (like packed min/max). GCC/clang can't auto-vectorize search loops (only loops where the trip-count is known at runtime before the first iteration), so inputStr.find_first_of either compiles to a one-byte-at-a-time search, or calls memchr which only benefits from SSE2 anyway, but can dynamic dispatch based on CPU features since it's in a shared library. (Glibc overloads the dynamic linking process with a "resolver" function that decides which implementation of memchr is best on the current machine, either SSE2 or AVX2. The both versions are hand-written asm, for example the SSE2 version's source. A few functions like strstr have SSE4.2 versions that you CPU can take advantage of, but this choice doesn't depend on -march compile-time settings, purely run-time dynamic linker + glibc.) If you want to see where your program is spending most of its time, use perf record ./a.out / perf report -Mintel (the default is AT&T syntax disassembly; I prefer Intel). If it's in library functions, different tuning options and new instructions available probably aren't helping your main code. If it's in your program proper, not libs, then apparently the baseline instruction-set for x86-64 and the "generic" tuning options are fine, or GCC doesn't know how to get any use out of SSSE3 / SSE4.x for your code. I didn't look much at what your code is doing to see what manual vectorization might be possible.
71,864,115
71,865,495
Why do I get a segmentation fault when using "dialog_checklist" from Linux's "dialog.h"?
I wanted to use the dialog.h library from the dialog Linux package but when I try to make a radiolist (checklist with flag parameter set to 1) it gives me a segmentation fault. I assume it has to do with the list of strings (char**) but I have been unable to find a fix for it. In this code on line 10 the error occurs: #include <dialog.h> int main() { int distro; char dist1[] = "Ubuntu"; char dist2[] = "Gentoo"; char *distros[2] = {dist1,dist2}; init_dialog(stdin, stdout); // start dialog distro = dialog_checklist("Select Distro","Select One",0,0,0,2,distros,1); end_dialog(); // end dialog } Incase anyone needs it: man page for dialog.h
It appears I read the documentation wrong, the list was supposed to contain {tag, item, status} for each item.
71,864,982
71,865,664
When should I be using if constexpr as apposed to a regular if in a constexpr template function?
I've been trying to write a metafuncion to evaluate powers at compile time. I have managed to do it with template metaprogramming, implemented as such: template<int A, int B> struct pow { static constexpr int value = (B % 2 == 0) ? pow<A, B / 2>::value * pow<A, B / 2>::value : A * pow<A, B - 1>::value; }; template<int A> struct pow<A, 1> { static constexpr int value = A; }; But, for some reason, why I try to use template functions, this doesn't compile, as it exceeds maximum recursion depth for function definition: template<int a, int b> constexpr int template_power() { return (b == 0) ? 1 : ((b % 2 == 0) ? template_power<a, b / 2>() * template_power<a, b / 2>() : a * template_power<a, b - 1>()); } What this tells me is that somehow, the conditional statements don't get properly evaluated at compile time, but I don't see any difference between this and the previous implementation. On the other hand, this constexpr function does compile: int constexpr power(int a, int b) { return (b == 0) ? 1 : ((b % 2 == 0) ? power(a, b / 2) * power(a, b / 2) : a * power(a, b - 1)); And, furthermore, if I refactor my template function using if constexpr, it does compile as intended. template<int a, int b> int constexpr template_power() { if constexpr(b == 0) return 1; else if constexpr(b % 2 == 0) return template_power<a,b/2>() * template_power<a, b/2>(); else return a * template_power<a, b - 1>(); } How do I make sense of all of this? My guess is that for the function template, the conditional statement evaluates all the branches before deciding what to choose, which causes it to generate unaccounted for functions (such as when b is negative). If that is the case, why do the conditional statements get properly evaluated for the template struct and the constexpr function, but not the template function? The verbatim error message is this: [path]/main.cpp: In instantiation of 'constexpr int template_power() [with int a = 2; int b = -896]': [path]/main.cpp:42:45: recursively required from 'constexpr int template_power() [with int a = 2; int b = -1]' [path]/main.cpp:41:41: recursively required from 'constexpr int template_power() [with int a = 2; int b = 2]' [path]/main.cpp:41:41: required from 'constexpr int template_power() [with int a = 2; int b = 5]' [path]/main.cpp:47:43: required from here [path]/main.cpp:41:41: fatal error: template instantiation depth exceeds maximum of 900 (use '-ftemplate-depth=' to increase the maximum) 41 | template_power<a, b / 2>() * template_power<a, b / 2>() :
In your first example, since the ternary operator is evaluated at runtime (just like a regular if statement), it cannot stop the instantiation of the template, and since your template has no specialization for the exit, all branches will be instantiated, which makes it recursive infinitely. In your second example, since there is no template involved, there is no instantiation of the template and it compiles. In your third example, since if constexpr only instantiates the template when the expression evaluates to true, and the other branches will be discarded, it compiles fine as well.
71,865,108
71,866,103
How would I seed the PCG RNG with a chosen, set seed?
For testing purposes I need to seed PCG's C++ implementation (the 64 bit output one) with a set value. When I look at the examples I only see it seeding using entropy. I've used pcg64 rng(42); and it's worked, rng() generating the same numbers every time, but PCG64 uses a 256-bit seed and this way seems to generate the same numbers for each value above the 64 bit integer limit. What's the best way to seed it with known values?
As I read source code, pcg64 is an instantination of engine template class which accepts pcg128_t seed value in constructor. So it is only 128 bit value, not 256 bit. There are two ways how you can pass 128 bit seed to constructor. First is if you already have pre-defined two 64-bit values, then you can use PCG_128BIT_CONSTANT(hi, lo) macro for building 128 bit value, and write code: pcg64 rng{PCG_128BIT_CONSTANT(0xC7C8709C9626D159ULL, 0x675BB824D76E9146ULL)}; Second way is by using std::mt19937_64 random generator and maybe std::random_device (for initializing random generator): #include <random> .... std::mt19937_64 seed{0xC7C8709C9626D159ULL}; // or // std::mt19937_64 seed{std::random_device()}; pcg64 rng{PCG_128BIT_CONSTANT(seed(), seed())}; You can also use std::seed_seq for same purpose as std::mt19937_64 was used above: #include <random> #include <array> #include <cstdint> .... std::seed_seq seed{1, 2, 3, 4, 5}; std::array<uint32_t, 4> seeds{}; seed.generate(seeds.begin(), seeds.end()); pcg64 rng{PCG_128BIT_CONSTANT(((uint64_t(seeds[0]) << 32) | seeds[1]), ((uint64_t(seeds[2]) << 32) | seeds[3]))};
71,865,304
71,865,594
Heap corruption detected, while deleting a dynamic 2d char array
I have written a class with char** class field(which is dynamic 2d array) named visa(basically i want there to be countries which a person has visited) and countriesVisited(in fact size of the array). I intentionally didn't use strings. I've added a class method, which adds countries to the mentioned array, but when i try to delete the array elements i get HEAP CORRUPTION detected: after Normal block (#158): void ForeignPassport::addCountry(const char* country) { char** tmp = new char* [countriesVisited + 1]; for (int i = 0; i < countriesVisited+1; i++) { tmp[i] = new char[strlen(country)]; } for (int i = 0; i < countriesVisited; i++) { int f = 0; while (visa[i][f-1] != '\0') { tmp[i][f] = visa[i][f]; f++; } } for (int i = 0; i <= strlen(country); i++) { if (i == strlen(country)) { tmp[countriesVisited][i] = '\0'; break; } tmp[countriesVisited][i] = country[i]; } countriesVisited++; for (int i = 0; i < countriesVisited-1; i++) { delete[]visa[i]; } visa = tmp ; }
tmp[i] = new char[strlen(country)]; here you are allocating memory in amounts of strlen(country) but in this loop: for (int i = 0; i <= strlen(country); i++) { if (i == strlen(country)) { tmp[countriesVisited][i] = '\0'; break; } tmp[countriesVisited][i] = country[i]; } here you are accessing to the memory which is not allocated and this not allowed, so change the condition to i < strlen(country)
71,865,608
71,867,070
Why is my QGraphicsLine in the wrong place
I want to draw a line to connect two circles (QGraphicsEllipseItem), but I find that I don't get the desired result with this way of writing. //they have been initialized to the correct place QGraphicsEllipseItem* nodeu; QGraphicsEllipseItem* nodev; this->addLine(nodeu->x(), nodeu->y(), nodev->x(), nodev->y()); The result of executing these codes is that only two circles appear, but no lines appear. like this My rough inference is the problem of coordinate transformation, but I just can't solve it. thank you!
you should first add one QGraphicsView in your UI or : QGraphicsView *graphicsView; QGridLayout *gridLayout; gridLayout = new QGridLayout(centralwidget); gridLayout->setSpacing(0); gridLayout->setObjectName(QString::fromUtf8("gridLayout")); graphicsView = new QGraphicsView(centralwidget); graphicsView->setObjectName(QString::fromUtf8("graphicsView")); gridLayout->addWidget(graphicsView, 0, 0, 1, 1); then : QGraphicsScene *_scene = new QGraphicsScene(this); ui->graphicsView->setScene(_scene); ui->graphicsView->setRenderHints(QPainter::Antialiasing); QGraphicsEllipseItem *nodeu = new QGraphicsEllipseItem; nodeu->setRect(20, 10, 20, 20); _scene->addItem(nodeu); QGraphicsEllipseItem *nodev = new QGraphicsEllipseItem; nodev->setRect(80, 60, 20, 20); _scene->addItem(nodev); QGraphicsLineItem *_lineItem = new QGraphicsLineItem; _lineItem->setLine(nodeu->rect().x() + nodeu->rect().width() / 2.0, nodeu->rect().y() + nodeu->rect().height() / 2.0, nodev->rect().x() + nodev->rect().width() / 2.0, nodev->rect().y() + nodev->rect().height() / 2.0); _scene->addItem(_lineItem); this is the output:
71,865,918
71,866,714
Why isn't rvalue copy constructor used for assignment from temporary?
#include<iostream> #include<vector> #include<string> using namespace std; class test { public: test(int y) { printf(" test(int y)\n"); } test() { printf(" test()\n"); } test(test&&c) noexcept { printf(" test(test&&c) noexcept\n"); } test(const test&z) { printf(" test(const test&z)\n"); } test& operator=( test&&e) { printf(" test& operator=( test&&e)\n"); return *this; } }; int main() { test o ; o = 4; return 0; } The Output : " test() " " test(int y) " " test& operator=( test&&e ) " I thought that this line in the code o = 4 is creating an rvalue of object of the class ( test ) and passing it to the overloaded operator ( operator = ) But when i changed test& operator=( test&&e ) into test& operator=( test e ) and run the code again : #include<iostream> #include<vector> #include<string> using namespace std; class test { public: test(int y) { printf(" test(int y)\n"); } test() { printf(" test()\n"); } test(test&& c) noexcept { printf(" test(test&&c) noexcept\n"); } test(const test& z) { printf(" test(const test&z)\n"); } test& operator=(test e) { printf(" test& operator=( test e)\n"); return *this; } }; int main() { test o; o = 4; return 0; } The Output : " test() " " test(int y) " " test& operator=( test e ) " While I expected this Output after the change : " test() " " test(int y) " " test(test&&c) noexcept " " test& operator=( test e ) " Because when i changed test& operator=( test&&e ) into test& operator=( test e ) the overloaded operator ( operator = ) now takes an object of the class test as parameter ( pass by value ) and the value that is passed to it is an rvalue so I expected that the constructor test(test&&c) noexcept will be called So why the constructor test(test&&c) noexcept is not called? Explanation why I have this expectation: because when you write this code and run it : #include<iostream> #include<vector> #include<string> using namespace std; class test { public: test(int y) { printf(" test(int y)\n"); } test() { printf(" test()\n"); } test(test&& c) noexcept { printf(" test(test&&c) noexcept\n"); } test(const test& z) { printf(" test(const test&z)\n"); } test& operator=(test e) { printf(" test& operator=( test e)\n"); return *this; } }; int main() { test o; test x; o = move(x); // this function ( move () ) returns an rvalue of its argument return 0; } The Output : " test() " " test() " " test(test&&c) noexcept " " test& operator=( test e ) " edit : this code #include<iostream> #include<vector> #include<string> using namespace std; class test { public: test(int y) { printf(" test(int y)\n"); } test() { printf(" test()\n"); } test(test&& c) noexcept { printf(" test(test&&c) noexcept\n"); } test(const test& z) { printf(" test(const test&z)\n"); } test& operator=(test e) { printf(" test& operator=( test e)\n"); return *this; } }; int main() { test o; test x; o = x; return 0; } The Output : " test() " " test() " " test(const test&z) " " test& operator=( test e ) "
So why the constructor test(test&&c) noexcept is not called? This is due to non-mandatory copy elison prior to C++17.Under certain circumstances, the compilers are permitted, but not required to omit the copy and move (since C++11) construction of class objects. You can verify this by providing the flag -fno-elide-constructors in your 2nd example. And you'll get your expected output. Demo. class test { public: test(int y) { printf(" test(int y)\n"); } test() { printf(" test()\n"); } test(test&& c) noexcept { printf(" test(test&&c) noexcept\n"); } test(const test& z) { printf(" test(const test&z)\n"); } test& operator=(test e) { printf(" test& operator=( test e)\n"); return *this; } }; int main() { test o; o = 4; return 0; } Output with -fno-elide-constructors flag: test() test(int y) test(test&&c) noexcept test& operator=( test e) Working demo. And if you don't provide this flag, then compilers are allowed to elide the copy/move construction in this situation and hence you were getting the output you mentioned. C++17 Note that from C++17 onwards, the flag -fno-elide-constructors won't have any effect on the output becasue of the mandatory copy elison.
71,866,011
71,866,159
Replace hour of chrono::time_point?
How can I change just the hour of an existing std::chrono::system_clock::time_point? For example, say I wanted to implement this function: void set_hour(std::chrono::system_clock::time_point& tp, int hour) { // Do something here to set the hour } std::chrono::system_clock::time_point midnight_jan_1_2022{std::chrono::seconds{1640995200}}; set_hour(midnight_jan_1_2022, 11); // midnight_jan_1_2022 is now 11am on Jan 1 2022 ....
The answer depends on exactly what you mean. The simplest interpretation is that you want to take whatever date tp points to (say yyyy-mm-dd hh:MM:ss.fff...), and create: yyyy-mm-dd hour:00:00.000.... Another possible interpretation is that yyyy-mm-dd hh:MM:ss.fff... is transformed into yyyy-mm-dd hour:MM:ss.fff.... In either event C++20 makes this easy, and if you don't yet have access to C++20 <chrono>, then there exists a free, open-source header-only library that emulates C++20 <chrono> and works with C++11/14/17. If you want to zero the minute, second and subsecond fields as described in the first interpretation that is: void set_hour(std::chrono::system_clock::time_point& tp, int hour) { using namespace std::chrono; auto day = floor<days>(tp); tp = day + hours{hour}; } I.e. you simply floor the time_point to days-precision and then add the desired hours. The second interpretation is slightly more complicated: void set_hour(std::chrono::system_clock::time_point& tp, int hour) { using namespace std::chrono; auto day = floor<days>(tp); hh_mm_ss hms{tp - day}; tp = day + hours{hour} + hms.minutes() + hms.seconds() + hms.subseconds(); } Here you have to discover and recover the {minutes, seconds, subseconds} fields to re-apply them to the desired date (along with the desired hour). hh_mm_ss is a C++20 {hours, minutes, seconds, subseconds} data structure that automates the conversion from a duration into a field structure so that you can more easily replace the hours field. Both of these solutions will give the same answer for your example input: 2022-01-01 11:00:00.000000 since the input has zeroed minutes, seconds and subseconds fields already.
71,866,214
71,866,742
How to use multiple conditions in enable_if?
I have the following code: #include <iostream> #include<type_traits> using namespace std; enum class a : uint16_t { x, y }; template<typename T> using isUint16ScopedEnum = std::integral_constant< bool, std::is_enum_v<T> && std::is_same_v<std::underlying_type_t<T>, uint16_t> && !std::is_convertible_v<T, uint16_t>>; template<typename T, std::enable_if_t<is_same_v<T, uint16_t>, void**> = nullptr> void f(T t) { cout << "works\n"; } template<typename T, std::enable_if_t<isUint16ScopedEnum<T>::value, void**> = nullptr> void g(T t) { cout << "also works\n"; } template<typename T, std::enable_if_t<isUint16ScopedEnum<T>::value || is_same_v<T, uint16_t>, void**> = nullptr> void h(T t) { cout << "Works with enum, Fails with uint\n"; } int main() { a A = a::x; f((uint16_t)1); g(A); h(A); //h((uint16_t)1); } The commented line in main doesn't work and I can't figure out why. If I pass an uint16_t to h, shouldn't the second condition enable the template? The compiler keeps complaining that it is not an enum... Why is it failing to instantiate h(uint16_t)?
(uint16_t)1 is of type uint16_t and not an enum type, so there is no member type for underlying_type, which causes underlying_type_t to be ill-formed and aborts compilation. You can wrap is_enum_v<T> && is_same_v<underlying_type_t<T>, ...> into a separate trait and use partial specialization to apply underlying_type_t to T only when T is enum type, e.g. template<typename E, class T, bool = std::is_enum_v<E>> struct underlying_type_same_as; template<typename E, class T> struct underlying_type_same_as<E, T, false> : std::false_type { }; template<typename E, class T> struct underlying_type_same_as<E, T, true> : std::is_same<std::underlying_type_t<E>, T> { }; Then isUint16ScopedEnum can be rewritten as template<typename T> using isUint16ScopedEnum = std::bool_constant< underlying_type_same_as<T, uint16_t>::value && !std::is_convertible_v<T, uint16_t>>; Demo
71,866,374
71,866,591
Different behavior when accessing a base class when it's a template
When I write A::B::C, with A being a class, and B being its base class, I assume I'm accessing C which is defined in that base B. This wouldn't work when B isn't actually a base of A. However, the same apparently isn't true when B is a template, e.g. A::B<123>::C still gives me B<123>::C, and it doesn't seem to matter whether B<123> is actually a base of A or not. I'm at a loss why there could be a difference. Does it not interpret A::B<123> as accessing base class B<123> of class A? Why not? Can it be rewritten somehow so it does interpret it like accessing a base class? Here's a snippet explaining what's done in detail, with comments explaining every step: // Here we show that we can't access a non-existent base of A namespace WorksAsExpectedWithoutTemplates { struct B { using C = void; }; struct D { using C = void; }; struct A: B { }; // Compiles as expected, B is a base of A, so Foo is B::C, aka void using Foo = A::B::C; // Doesn't compile, as expected, because D isn't a base of A, even though D::C // exists using Bar = A::D::C; // WE DON'T EXPECT THIS TO COMPILE, WHICH IS FINE } // Now we try the same thing with templates, and it doesn't behave the same way. // Why? namespace ActsDifferentlyWithTemplates { template< int > struct B { using C = void; }; struct A: B< 42 > { }; // Compiles as expected, B< 42 > is a base of A, so Foo is B< 42 >::C, aka void using Foo = A::B< 42 >::C; // Compiles, Bar is B< 123 >::C, even though B< 123 > is not a base of A. Why // does this behave differently than in the non-template case above? Can this be // rewritten differently so that this wouldn't compile, same as in // WorksAsExpectedWithoutTemplates, since B< 123 > isn't a base of A? using Bar = A::B< 123 >::C; // WHY DOES THIS COMPILE? B< 123 > isn't a base of A }
template< int > struct B has an injected-class-name B that acts as a template name if it immediately precedes a <. The class struct A inherits this. So, A::B< 123 >::C is the same as B< 123 >::C, not the base class B< 42 >. For example: template<int X> struct B { using C = char[X]; }; struct A : B<42> {}; using Foo = A::B<42>::C; using Bar = A::B<123>::C; using Baz = A::B::C; // (injected-class-name without template) static_assert(sizeof(Foo) == 42); static_assert(sizeof(Bar) == 123); // This is a different type static_assert(sizeof(Baz) == 42); None of these cases actually are "accessing a base class". They are all inheriting the injected-class-name from the base class like any other member type alias / member template.
71,867,090
71,926,738
C++ pass function pointer in function template
I'm trying to pass a function pointer in a template, to then use it in asm code: template <auto T> _declspec(naked) void Test() { __asm { lea eax, T jmp [eax] } } int main() { Test<MessageBoxA>(); Test<Sleep>(); } I know the naked function will crash when executed but I've simplified the code to show only what I'm trying to achieve. The problem with this code is that once compiled, if you look at the assembly code in a disassembler, it will look like this: lea eax, 0 jmp [eax] It is storing 0 in eax. Instead, it should store the MessageBoxA address (and Sleep in another function) in eax. I don't know if I'm doing something wrong or the compiler is failing.
I'm not an assembly expert, but creating a static constexpr void* set to the non-type template parameter value seems to do the trick: template <auto T> __declspec(naked) void Test() { static constexpr void* fptr = T; __asm { lea eax, fptr jmp [eax] } } const void sleep() { } int main() { Test<(&sleep)>(); return 0; } generates lea eax, OFFSET void * `void Test<&void sleep(void)>(void)'::`2'::fptr jmp SHORT DWORD PTR [eax] The example can be played with on compiler explorer: https://godbolt.org/z/f1d7daa49
71,867,686
71,867,796
type-casting abstract class type to struct type with a integer member
I am studing Blender's GHOST code and found the following statement in GHOST_CreateSystem C-API function GHOST_ISystem::createSystem(); GHOST_ISystem *system = GHOST_ISystem::getSystem(); return (GHOST_SystemHandle)system; GHOST_ISystem is an abstract class for a specific operating system such as win32, linux. GHOST_SystemHandle is defined as structure type as follows: typedef struct GHOST_SystemHandle__ { int unused; } * GHOST_SystemHandle I am not familiar with this kind of practice type-casting a pointer to class into a pointer to struct type with an integer member. It would be appreciated to enlighten me the background about it.
Abstract class CANNOT be instantiated, to wit it cannot be converted. What happens here is a conversion of pointer values. The calls GHOST_ISystem::createSystem(); and GHOST_ISystem::getSystem(); are calls to static functions. The latter returns a pointer to GHOST_ISystem. Pointer is a separate compound type and pointer to any declared type may materialized. A pointer to an abstract class-type can hold value of pointer to any derived type. GHOST_ISystem* is its static type while its dynamic type can vary. The C-style cast syntax (GHOST_SystemHandle)system; is considered faux pas in C++ as it is too permitting, unsafe conversion. In this particular case it is treated as reinterpret_cast to a pointer GHOST_SystemHandle__ *. The content of pointer system is bytewise copied to an instance of GHOST_SystemHandle, which is also a pointer. This would be hinged on assumption that all pointers in implementation have similar content and same size and that access by dereferencing the result would be legal. Likely, the underlying reason was that derived types would have an integer field or an subobject with same alignment. Strictly speaking, result is unspecified. Memory model of original class and GHOST_SystemHandle__ should match. This assumes too many things: The abstract base class-type have no non-static member variable or it contains an equivalent member variable. The implementation is conforming to late-enough standard to ensure that base type subobject got zero size, if it doesn't have non-static member variables. The alignment requirement of derived type in question is same as alignment requirement of GHOST_SystemHandle__. It it's not, result of *system->unused is undefined. There is a number of ways it could be avoided in C++ and none was used, which suggests that code was converted from C without much of refactoring done while keeping interface type formats same for compatibility.
71,867,733
71,868,129
Why am I unable to read 2D array using vectors?
The code is : #include<iostream> #include<vector> using namespace std; int main() { vector<vector<int>> arr; int i, j; for (i = 0; i < 5; i++) { for (j = 0; j < 5; j++) { cin >> arr[i][j]; } } return 0; } Compilation is successful. But, when I tried to run the code in Visual Studio (2013) I got runtime error "vector subscript out of range". Why am I getting this run time error ? Is this the correct way to read 2D array input from user ?
Because the vector arr is empty in your code. #include<iostream> #include<vector> using namespace std; int main() { vector<vector<int>> arr; cout << arr.size() << endl; // output: 0 cout << arr.empty() << endl; // output: 1 , it means arr is empty // First way vector<vector<int>> arr1(5, vector<int>(5)); int i, j; // Second way arr.resize(5); for (i = 0; i < 5; i++) { for (j = 0; j < 5; j++) { int temp; cin >> temp; arr[i].emplace_back(temp); } } return 0; }
71,867,746
71,868,081
My if statements inside my while loop keep repeating forever when they are not suppose to be. It should go back to the while loop after the if stateme
So im working on a project for school and i just cant get this to work. everything else seems to run but when i input the users choice for q, s, z10, z25,z5,z1 it loops indefinetly. i cant figure out why it keeps running the function over and over. im not quite sure if im just typing something wrong or what but this is the only thing im really stuck on currently. Here is the code #include<iostream> #include<string> using namespace std; struct Inventory { int Pack_25oz; int Pack_10oz; int Pack_5oz; int Pack_1oz; }; void show_Menu(); void initialize (Inventory& I); void add_25OZ (Inventory& I, int P25); void add_10OZ (Inventory& I, int P10); void add_5OZ (Inventory& I, int P5); void add_1OZ (Inventory& I, int P1); void Place_Order(Inventory& I, int amount); void show (Inventory& I); int main(){ Inventory I; string choice; int nop= 0; initialize(I); show_Menu(); cout << "Dear User! please make a choice from above menu : " << endl; getline(cin,choice); while(choice!="q" or choice != "Q"){ if(choice == "s"|| choice == "S"){ show(I); } else if(choice == "z25" || choice == "Z25"){ cout << "Enter the number of packages : \n"; cin >> nop; add_25OZ(I, nop); } else if(choice == "z10" || choice == "Z10"){ cout << "Enter the number of packages : \n"; cin >> nop; add_10OZ(I, nop); } else if(choice == "z5"||choice == "Z5"){ cout << "Enter the number of packages : \n"; cin >> nop; add_5OZ(I, nop); } else if(choice == "z1"|| choice == "Z1"){ // choice equal to "z1" or "Z1" cout << "Enter the number of packages : \n" ; // prompt for number of packages cin >> nop ; // accept user input add_1OZ( I, nop);// call add_1OZ function } else if(choice == "o"||choice == "O") { cout << "Enter the number of ounces : ";// prompt for number of ounces int noun; // noun stands for number of ounces cin >> noun;// accept user input Place_Order( I, noun); } else if (choice == "q" || choice == "Q"){ // Output final message that the program has ended cout << "The program has ended."; break; } else cout << "invalid comand" << endl; }; return 0; } void show_Menu(){ cout << "S - Show Inventory" << endl; cout << "Z25 - Add 25 oz packages"<< endl; cout << "Z10 - Add 10 oz packages"<< endl; cout << "Z5 - Add 5 oz packages"<< endl; cout << "Z1 - Add 1 oz packages "<< endl; cout << "O - Place order"<< endl; cout << "Q - End"<< endl; } void show (Inventory& I) { cout << "The Inventory comprises of the following:\n 1. Pack_25oz : " << I.Pack_25oz << "\n 2. Pack_10oz : " << I.Pack_10oz << "\n 3. Pack_5oz : " << I.Pack_5oz << "\n 4. Pack_1oz : " << I.Pack_1oz <<endl ; } void initialize (Inventory& I) { int var = 0 ; I.Pack_25oz = var; I.Pack_10oz = var; I.Pack_5oz = var; I.Pack_1oz = var; } void add_25OZ (Inventory& I, int P25) { I.Pack_25oz += P25; } void add_10OZ (Inventory& I, int P10) { I.Pack_10oz += P10; } void add_5OZ (Inventory& I, int P5) { I.Pack_5oz += P5; } void add_1OZ (Inventory& I, int P1) { I.Pack_1oz += P1; } void Place_Order(Inventory& I, int amount) { int subtract; subtract = amount / 25; if (I.Pack_25oz <= 0) { cout << "Not enough packs" << endl; } else { I.Pack_25oz -= subtract; } amount = amount % 25; subtract = amount / 10; if (I.Pack_10oz <= 0) { cout << "Not enough packs" << endl; } else { I.Pack_10oz -= subtract; } amount = amount % 10; subtract = amount / 5; if (I.Pack_5oz <= 0) { cout << "Not enough packs" << endl; } else { I.Pack_5oz -= subtract; } amount = amount % 5; subtract = amount / 1; if (I.Pack_1oz <= 0) { cout << "Not enough packs" << endl; } else { I.Pack_1oz -= subtract; cout << "Order Fufilled" << endl; } }
It seems you call getline outside of the loop. so choice is never updated.
71,867,795
71,869,861
Specialised template *not* asserting despite compile time constant static_assert
For a few days I've been using and testing my application without any trouble using the following code: class dataHandler { public: template<class T> T GetData(bool truncate = false) { static_assert(false, "Unhandled output type"); } template<T> int GetData<int>(bool truncate) { // Normal stuff that compiles } } This (As I expected at the time) works fine as long as no implicit instantiation of GetData's default is performed. However, today after adding a new failing specialisation for void* specifically (I wanted a different error) I discovered it wouldn't compile due to the assertion, even though the `void* spec was never called or mentioned in code. I started a new C++ test project (with the same C++ version, MSVC version, and VS2022 version) and found this also doesn't compile for the same reason: template<class T> T Spec() { static_assert(false, "default"); } template<> int Spec<int>() { return 1; } I was unable to replicate the original 'success' in anything I tried within the test project, and the failing GetData<void*> assert in the initial project seems to indicate that it's not a project config / difference in toolset issue. After some searching I discovered that it failing was the intended (or otherwise expected) behaviour, as well as a workaround for it. However I find myself wondering why the initial case of static_assert(false) didn't also fail to compile. Is this some niche exception, or is this an issue with MSVC's consistency?
However I find myself wondering why the initial case of static_assert(false) didn't also fail to compile. Is this some niche exception, or is this an issue with MSVC's consistency? It's certainly not an inconsistency. The key part here is "Standard conformance mode", controllable with the compiler option /permissive-. See the documentation of this compiler option. The reason that MSVC from before VS2017 used to accept your static_assert(false, ...), is because it postponed parsing the contents of a function template until template instantiation. That is just how the parser used to work, and also why features like two-phase name lookup could never be properly implemented. I'll refer you to this blog post for more background on this. You can easily try it for yourself. Even if the function contains ill-formed code that shouldn't even parse correctly, the compiler doesn't complain as long as the template isn't being instantiated: template<class T> void foo() { Normally this should not (never actually (compile)) but it does anyway } It appears to do some basic paranthesis matching and that is it. The token stream is recorded and parsed when foo is instantiated (usually when called). In order to fix two-phase lookup (and other conformance issues), they had to fix the compiler and parse the code whenever a function template is encountered, rather than being instantiated. But now they have a problem, because a lot of old code might be reliant on the old compiler behavior that suddenly doesn't compile anymore. So they introduced the /permissive- option for users to opt-in into standard conformance mode. And gradually the default was changed for new projects or certain compiler options, as can be read in the documentation: The /permissive- option is implicitly set by the /std:c++latest option starting in Visual Studio 2019 version 16.8, and in version 16.11 by the /std:c++20 option. /permissive- is required for C++20 Modules support. Perhaps your code doesn't need modules support but requires other features enabled under /std:c++20 or /std:c++latest. You can explicitly enable Microsoft extension support by using the /permissive option without the trailing dash. The /permissive option must come after any option that sets /permissive- implicitly. By default, the /permissive- option is set in new projects created by Visual Studio 2017 version 15.5 and later versions. It's not set by default in earlier versions. When the option is set, the compiler generates diagnostic errors or warnings when non-standard language constructs are detected in your code. These constructs include some common bugs in pre-C++11 code. Which brings us to the answer to your question. You weren't seeing it in your original code because you were compiling without /permissive-. In your test project, created in VS2022, /permissive- mode was set by default so it failed to compile. It also fails to compile in an explicit specialization (your void* case) because at that point the template arguments are known and the function is instantiated. There are a couple of ways to properly fix your code. One is by explicitely deleting the main template and any specialiation you don't want to have. template<class T> void foo() = delete; template<> void foo<void*>() = delete; template<> void foo<int>() { // ... } This will make any use of the explicitely deleted variants ill-formed, without having the option to include an error message. Of course the void* case is a bit redundant in this example. If you want to stick to static_assert, you must make the condition for the assert dependent on the template arguments. If you are compiling with C++17, you could do: template<class...> constexpr bool always_false = false; template<class T> void foo() { static_assert(always_false<T>, "your error here"); } If using C++14 or earlier, you could wrap the always_false into a struct template: #include <type_traits> template<class...> struct always_false : false_type { }; template<class T> void foo() { static_assert(always_false<T>::value, "your error here"); }
71,867,891
71,869,207
C++/WinRT DeviceInformation No default Constructor exists error
Hello i'm trying to port the following code from a c# program. public class DeviceListEntry { private DeviceInformation device; private String deviceSelector; public String InstanceId { get { return device.Properties[DeviceProperties.DeviceInstanceId] as String; } } public DeviceInformation DeviceInformation { get { return device; } } public String DeviceSelector { get { return deviceSelector; } } /// <summary> /// The class is mainly used as a DeviceInformation wrapper so that the UI can bind to a list of these. /// </summary> /// <param name="deviceInformation"></param> /// <param name="deviceSelector">The AQS used to find this device</param> public DeviceListEntry(Windows.Devices.Enumeration.DeviceInformation deviceInformation, String deviceSelector) { device = deviceInformation; this.deviceSelector = deviceSelector; } } } Essentially if I attempt to port the DeviceListEntry Constructor with the deviceInformation object it errors me saying there is no default Constructor for the DeviceInformation Class. however if I remove the corresponding code for the device object the DevuceListEntry constructor doesn't return any errors. Here's what I have: #include "pch.h" #include "DeviceListEntry.h" #include "Constants.h" using namespace winrt::Windows::Devices::Enumeration; using namespace winrt::Windows::Foundation::Collections; namespace SerialArduino { const winrt::hstring DeviceProperties::DeviceInstanceID = {L"System.Devices.DeviceInstanceId"}; // having a DeviceInformation object as parameter as well as object causes no default constructor error DeviceListEntry::DeviceListEntry(winrt::Windows::Devices::Enumeration::DeviceInformation deviceInformation, winrt::hstring deviceSelector) { device = deviceInformation; this->deviceSelector = deviceSelector; } winrt::hstring DeviceListEntry::InstanceId() { return winrt::unbox_value<winrt::hstring>(device.Properties().Lookup(DeviceProperties::DeviceInstanceID)); } winrt::Windows::Devices::Enumeration::DeviceInformation DeviceListEntry::DeviceInformation() { return device; } winrt::hstring DeviceListEntry::DeviceSelector() { return deviceSelector; } } Error: Error (active) E0291 no default constructor exists for class Error C2512 'winrt::Windows::Devices::Enumeration::DeviceInformation': no appropriate default constructor available SerialArduino Any help would be greatly appreciated as I'm completely lost on what I'm doing wrong. Thanks in advance
Assuming your DeviceListEntry declaration looks like: namespace SerialArduino { class DeviceListEntry { public: //... private: winrt::Windows::Devices::Enumeration::DeviceInformation device; winrt::hstring deviceSelector; }; } Try implementing your constructor like this: // having a DeviceInformation object as parameter as well as object causes no default constructor error DeviceListEntry::DeviceListEntry(winrt::Windows::Devices::Enumeration::DeviceInformation deviceInformation, winrt::hstring deviceSelector_) : device(deviceInformation), deviceSelector(deviceSelector_) { } This way, device will be copy-initialized from deviceInformation. Otherwise, the compiler will try to default-construct device and then copy-assign deviceInformation to it.
71,868,106
71,868,566
How to make getting a pixel value independent of the cv::Mat type?
I am writing a method that uses OpenCV (C++). For example void foo(const cv::Mat &image); Inside, I need to take the pixel value of the cv::Mat by row and column. If the type of image the method works with is CV_32FC3, I need to use image.at<cv::Vec3f>(row, col); If the type is CV_32SC2, I need to use image.at<cv::Vec2i>(row, col); If the type is CV_8UC1, I need to use image.at<uchar>(row, col); etc. I would like the method to be universal, that is, it works with an image with any number of channels and depth. Can anything be done to fulfill this requirement (any template logic)? Perhaps the solution is quite obvious, but I did not find it. Thank you!
Drop the use of cv::Mat - where you have to call type() method (at runtime) to get the type of values stored by mat, and instead that just start using templated version of mat class: it is cv::Mat_<Type> and write more generic code. Then you could write only one function template to read mat pixels: template<class T> T access(cv::Mat_<T> const& img, int r, int c) { return img(r,c); } More about cv::Mat_ here.
71,868,477
71,868,598
Is there a concept in the standard library that tests for usability in ranged for loops
There are a number of different ways, that make a type/class usable in a ranged for loop. An overview is for example given on cppreference: range-expression is evaluated to determine the sequence or range to iterate. Each element of the sequence, in turn, is dereferenced and is used to initialize the variable with the type and name given in range-declaration. begin_expr and end_expr are defined as follows: If range-expression is an expression of array type, then begin_expr is __range and end_expr is (__range + __bound), where __bound is the number of elements in the array (if the array has unknown size or is of an incomplete type, the program is ill-formed) If range-expression is an expression of a class type C that has both a member named begin and a member named end (regardless of the type or accessibility of such member), then begin_expr is __range.begin() and end_expr is __range.end() Otherwise, begin_expr is begin(__range) and end_expr is end(__range), which are found via argument-dependent lookup (non-ADL lookup is not performed). If I want to use a ranged for loop say in a function template, I want to constrain the type to be usable in a ranged for loop, to trigger a compiler error with a nice "constraint not satisfied" message. Consider the following example: template<typename T> requires requires (T arg) { // what to write here ?? } void f(T arg) { for ( auto e : arg ) { } } Obviously for a generic function I want to support all of the above listed ways, that a type can use to make itself ranged for compatible. This brings me to my questions: Is there a better way than manually combining all the different ways into a custom concept, is there some standard library concept that I can use for that? In the concepts library, there is no such thing. And if there is really no such thing, is there a reason for that? If there is no library/builtin concept for that, how am I supposed to implement such thing. What really puzzles me, is how to test for members begin and end regardless of the type or accessibility of such member (second bullet in the qouted list). A requires clause that tests for example for the existence of a begin() member fails if begin() is private, but the ranged for loop would be able to use the type regardless of that. Note I am aware of the following two questions: What concept allows a container to be usable in a range-based for loop? How to make my custom type to work with "range-based for loops"? but neither of them really answers my question.
It seems like what you need is std::ranges::range which requires the expressions ranges::begin(t) and ranges::end(t) to be well-formed. Where ranges::begin is defined in [range.access.begin]: The name ranges​::​begin denotes a customization point object. Given a subexpression E with type T, let t be an lvalue that denotes the reified object for E. Then: If E is an rvalue and enable_­borrowed_­range<remove_­cv_­t<T>> is false, ranges​::​begin(E) is ill-formed. Otherwise, if T is an array type and remove_­all_­extents_­t<T> is an incomplete type, ranges​::​begin(E) is ill-formed with no diagnostic required. Otherwise, if T is an array type, ranges​::​begin(E) is expression-equivalent to t + 0. Otherwise, if auto(t.begin()) is a valid expression whose type models input_­or_­output_­iterator, ranges​::​begin(E) is expression-equivalent to auto(t.begin()). Otherwise, if T is a class or enumeration type and auto(begin(t)) is a valid expression whose type models input_­or_­output_­iterator with overload resolution performed in a context in which unqualified lookup for begin finds only the declarations void begin(auto&) = delete; void begin(const auto&) = delete; then ranges​::​begin(E) is expression-equivalent to auto(begin(t)) with overload resolution performed in the above context. Otherwise, ranges​::​begin(E) is ill-formed. That is to say, it will not only perform specific operations on the array type but also decide whether to invoke member function range.begin() or free function begin(range) based on the validity of the expression, this already covers the behavior described by the so-called range-expression. And ranges::end follows similar rules. So I think you can simply do template<std::ranges::range T> void f(T arg) { for (auto&& e : arg) { // guaranteed to work } } It should be noted that ranges::begin requires that the returned type must model input_or_output_iterator, and ranges::end also requires that the returned type must model sentinel_for type returned by ranges::begin, so that T is enough to be a range. The range-expression does not have such constraints, it only checks the validity of the expression, so a minimal type that can use a range-based for loop could be struct I { int operator*(); I& operator++(); bool operator!=(const I&) const; }; struct R { I begin(); I end(); }; for (auto x : R{}) { } // well-formed But I don't think you're interested in such a case since I is not sufficient to constitute a valid iterator.
71,868,673
71,868,713
Creating a std::string from std::string_view
Given a string_view sv and a string s(sv), does s use the same char array internally as sv? Is it safe to say that when s is destroyed, sv is still valid?
Creating a std::string object always copies (or moves, if it can) the string, and handles its own memory internally. For your example, the strings handled by sv and s are totally different and separate.
71,869,011
71,869,059
std::map.operator[] not working with global maps
Can someone tell me how I can make use of std::map.operator[] to get the value of a const std::map ? For example: file.h #ifndef _FILE_H #define _FILE_H #include <map> #include <string> const std::map<std::string,std::string> STRINGS= { {"COMPANY","MyCo"} ,{"YEAR","2022"} }; #endif file.cpp #include "cpp_playground.h" #include <iostream> int main (void){ std::cout<< "Code by "<< STRINGS["COMPANY"] << " " << STRINGS["YEAR"] << std::endl; } With Visual Studio 2015 I get this error, but I can't interpret it Severity Code Description Project File Line Suppression State Error C2678 binary '[': no operator found which takes a left-hand operand of type 'const std::map<std::string,std::string,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>' (or there is no acceptable conversion) cpp_playground d:\user\documents\visual studio 2015\projects\cpp_playground\cpp_playground.cpp 10
The operator[] in std::map is defined to return a reference to the object with the given key - or create it, if it doesn't exist, which modifies the map, that's why it's not a const method. There is no const version of that operator, that's why you get the shown error. Use std::map's at(...) function for access-only. Note that it throws a std::out_of_range exception if the given key is not contained in the map; in C++20 or later you can use contains() to check whether the given key exists.
71,869,458
71,911,504
Drake cmake Could NOT find Gurobi
I use ubuntu 20.04 and I trying install Drake software. I have got error while making with cmake cmake -DWITH_GUROBI=ON -DWITH_MOSEK=ON ../drake: CMake Error at cmake/modules/FindGurobi.cmake:13 (file): file STRINGS file "/home/dmitriy/git/drake/Gurobi_INCLUDE_DIR-NOTFOUND/gurobi_c.h" cannot be read. Call Stack (most recent call first): CMakeLists.txt:450 (find_package) CMake Error at /usr/share/cmake-3.16/Modules/FindPackageHandleStandardArgs.cmake:146 (message): Could NOT find Gurobi: Found unsuitable version ".;.", but required is exact version "9.5.1" (found Gurobi_INCLUDE_DIR-NOTFOUND) Call Stack (most recent call first): /usr/share/cmake-3.16/Modules/FindPackageHandleStandardArgs.cmake:391 (_FPHSA_FAILURE_MESSAGE) cmake/modules/FindGurobi.cmake:52 (find_package_handle_standard_args) CMakeLists.txt:450 (find_package) -- Configuring incomplete, errors occurred! See also "/home/dmitriy/git/drake-build/CMakeFiles/CMakeOutput.log".
I installed Gurobi and error dosappeared.
71,869,663
71,869,961
Visual Studio C++ Project for Linux, how to run .out file?
Im using Visual Studio 2022 and have created a C++ project for linux. I followed this article: https://learn.microsoft.com/en-us/cpp/linux/connect-to-your-remote-linux-computer?view=msvc-170 And got a running OpenGL-application in Linux via Remote Debugging in Visual Studio. I see a .out-file in Linux but I can not run it. So, how do I compile an executable file, so I can run it on Linux Mint? I am using Linux Mint.
As you are using linux, you can use cpp or g++ for compiling your code. Linux usually have the g++. Run it by g++ filename.cpp and you will get a ELF file named a.out, you can execute this by the command ./a.out. If you couldn't run or your code check for the modes on file with ls -la command and if you can't find the letter -x in your files mode then use the command chmod +x filename .Hope this solves the problem.
71,869,715
71,869,870
Linking CPR C++ library with OMNET++
I have succesfully installed OMNET++ and now I want to link OMNET with a REST API library called CPR. Usually, in Eclipse (Which OMNET++ is based on) I would do the linking something like project properties->C/C++ build->Settings->GCC C++ Linker->Libraries->[-l section]. Now in OMNET I have tried linking it by going to Project -> Properties -> Makemake -> Options -> Additional Libraries to link with (-l option) and include: cpr. But it returns an error: ld.lld error: unable to find library -lcpr Thanks a lot for your help.
The cpr library should be on your library path (i.e. usually on /usr/lib). Otherwise you must specify also the -L option to specify the directory where that given library is.
71,870,664
71,870,821
Printing vector of struct - data not being saved? c++
I have a program that randomly generates an array, and then compares the numbers to the numbers in a csv file. The file is read via getline, where it is then inserted into my struct called 'past_results'. I then try and insert the struct data into a vector in my main function, but this doesnt seem to work. No data is printed at all. the initial printing of the data works fine and is correctly formatted, but when I send to my vector it wont print from that. I'm working with a file containing a mix of ints and strings so I was wondering if my data type management was the issue. #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <string> //struct to store data from file struct past_results { std::string date; std::string winningnums; }; //fills array of size 6 with random numbers between 1-50 void num_gen(int arr[]) { for (int i = 0; i < 6; i++) { int num = rand() % 51; arr[i] = num; } } //function to read csv void csv_reader(){ std::string line; past_results results; past_results res[104]; int linenum = 0; //open csv file for reading std::ifstream file("path/to/csv/file", std::ios::in); if(file.is_open()) { while (getline(file, line)) { std::istringstream linestream(line); std::string item, item1; //gets up to first comma getline(linestream, item, ','); results.date = item; //convert to a string stream and put into winningnums getline(linestream, item1); results.winningnums = item1; //add data to struct res[linenum] = results; linenum++; } } //display data from struct for(int i = 0; i < linenum; i++) { std::cout << "Date: " << res[i].date << " \\\\ Winning numbers: " << res[i].winningnums << std::endl; } } int main(){ //random num gen variables srand(time(NULL)); int size = 6; int numbers[size]; //fetch and print generated array of nums num_gen(numbers); //formatting for terminal output of random nums std::cout<< std::endl; std::cout << "Numbers generated: "; for (auto i: numbers) std::cout<< i << " "; std::cout<< std::endl; std::cout<< std::endl; //call csv_reader function csv_reader(); //create vector and insert struct data to it std::vector<past_results> results; results.push_back(past_results()); //printing vector of struct for (int i = 0; i > results.size(); i++){ std:: cout << "Winning nums from struct: " << results[i].winningnums; } return 0; } CSV format example: , Date, 1, 2, 3, 4, 5, 6, 7 0, wednesday, 1, 2, 3, 4, 5, 6, 7 1, thursday, 1, 2, 3, 4, 5, 6, 7 etc...
csv_reader writes to a function local array. Once the function returns all information read from the file is lost. Data is not stored in the class past_result. The data is stored in an instance of type past_result. In main you push a single element to the vector via results.push_back(past_results()); as a default constructed past_result contains empty strings you see no ouput. You should read results into a vector in csv_reader and return that vector: std::vector<past_results> csv_reader(...) { std::vector<past_results> result; past_results entry; // ... results.push_back(entry); // ... return result; }
71,870,798
71,870,981
C++ what happens if an exception occurs inside catch block?
What happens if an exception occurs inside a catch block? try {} catch(...) { stream.close(); // IO exception here } What's the default behaviour?
Nothing special will happen. A new exception object will be initialized by the throw expression inside the call and a search for a matching catch handler will start, which on escaping the function call will continue on the nearest enclosing try block (enclosing the shown try/catch pair). The old exception object will be destroyed during stack unwinding when leaving the old handler, since it wasn't rethrown.
71,871,314
71,871,419
static_cast from 'QgsVectorLayer *' to 'QgsMapLayer *', which are not related by inheritance, is not allowed
Class QgsVectorlayer derives from base class QgsMapLayer which derives from base class QObject. I want to cast a QgsVectorlayer object to a base class. This should easily be possbile but I get an error and don't understand why. The annex to the (probably not unimportant) error message is: ...qgsgeometry.h:46:7: note: 'QgsVectorLayer' is incomplete Line 46 contains only the QgsVectorLayer class definition: class QgsVectorLayer; (see source https://github.com/qgis/QGIS/blob/master/src/core/geometry/qgsgeometry.h#L46) This is my use case: I need to pass the argument variable vectorLayer in my adapted function QgsOgrProvider::extent(QgsVectorLayer* vectorLayer) const to another function as type QgsMapLayer* or QObject* which QgsVectorlayer is derived from. My understanding is that this should automatically be type casted or I could cast it using static_cast<type>(variable) but I get an error and don't understand why. The definition of QgsVectorLayer: class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionContextGenerator, ... {...} (full source: https://github.com/qgis/QGIS/blob/master/src/core/vector/qgsvectorlayer.h) The definition of QgsMapLayer: class CORE_EXPORT QgsMapLayer : public QObject {...} (full source: https://github.com/qgis/QGIS/blob/master/src/core/qgsmaplayer.h) My code that throws errors: QgsOgrProvider::extent(QgsVectorLayer* vectorLayer) const { ... QgsMapLayer * mapLayer=static_cast< QgsMapLayer*>(vectorLayer); // error: static_cast from 'QgsVectorLayer *' to 'QObject *', which are not related by inheritance, is not allowed; qgsgeometry.h:46:7: note: 'QgsVectorLayer' is incomplete QObject * mapObject=static_cast< QObject*>(vectorLayer); // error: static_cast from 'QgsVectorLayer *' to 'QgsMapLayer *', which are not related by inheritance, is not allowed; qgsgeometry.h:46:7: note: 'QgsVectorLayer' is incomplete QObject * mapObject2=new QObject(); // error: assigning to 'QObject *' from incompatible type 'QgsVectorLayer *' mapObject2=vectorLayer; ... }
The definition of the class is missing at the point where the static_cast is used. Just because the definition of the class exists in some header file doesn't mean that the compiler automatically knows it everywhere the class is referenced. Whichever header file defines this class was not #included, so the only thing that the compiler knows is that the class has been declared. Line 46 contains only the QgsVectorLayer class definition: class QgsVectorLayer; The translation unit #included this header file, directly or indirectly. The definition of QgsVectorLayer: class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionContextGenerator, ... {...} And this header file was not #included, directly or indirectly. You'll need to figure out how to correctly #include the required header files.
71,871,601
71,872,289
Why does inet_ntop() return a pointer instead of an int?
inet_ntop() has a signature as follows: const char* inet_ntop(int af, const void* src, char* dst, socklen_t size); Description: This function converts the network address structure src in the af address family into a character string. The resulting string is copied to the buffer pointed to by dst, which must be a non- null pointer. The caller specifies the number of bytes available in this buffer in the argument size. On success, inet_ntop() returns a non-null pointer to dst, or NULL if there was an error. The pattern for socket operations (e.g., getsockopt(), socket(), bind(), listen(), connect(), etc.) is typically to return an int, indicating (0) success, or (-1) error. It seems redundant for inet_ntop() to return a pointer to the very data structure that the caller passed into it -- dst. Obviously, that datum was already known by the caller, since it was required to be passed into the function. There has to be some compelling reason for this to step away from the convention; returning redundant information surely cannot be such. I'm feeling pretty stupid for just not seeing the reason for this. Any insight?
While the reason for these choices should be found in the minutes of the committee discussion, or asked to the people who designed the API, I can take a guess. inet_ntop() is a POSIX function, so it comes from C more than from C++. As you say, the pattern for socket operations is to return an int. But inet_ntop() is more a string function, so I'd compare it with functions from the string.h library. Just consider char *strcpy( char *dest, const char *src ); Why returning the same pointer I passed in? For chaining operations without declaring multiple temporary variables: char s[] = "this is the origial string I want to copy"; char *my_copy = strcpy(malloc(strlen(s) + 1), s); (I know that this is bad practice because we are not checking the return value of malloc, but I don't think that the design was taking this into account). More (really more) guess work is available here.
71,871,708
71,871,944
Get G++ to use a custom calling convention to pass larger structs in registers instead of memory?
Short question: Are there compiler options or functions attributes available in g++ that force the compiler to pass members of structures through registers instead of the stack. Long question: In my application I have a list of function handles that I am basically calling in a loop. Since every function does only a small amount of work, the function call overhead needs to be minimized. I want now to pass the arguments in a struct. This has the advantage, that a change in the arguments needs to be done only in one place not in like 20 places all over the code base. Another advantage is, that some arguments are based on template parameters which add or remove arguments. With the struct this could be overcome. The problem is now, that if the struct has more than two members, g++ pushes the struct on the stack instead of passing the arguments in the registers. This causes the performance to go down by 50%. I produced a small example that demonstrates the problem: #include <iostream> struct A { uint8_t n; size_t& __restrict__ dataPos; char* const __restrict__ data; }; struct B { size_t& __restrict__ dataPos; char* const __restrict__ data; }; __attribute__((noinline)) void funcStructA(A a) { std::cout << "out struct A: n: " << a.n << " dataPos: " << a.dataPos << " data: " << a.data << std::endl; } __attribute__((noinline)) void funcStructB(uint8_t n, B b) { std::cout << "out struct B: n: " << n << " dataPos: " << b.dataPos << " data: " << b.data << std::endl; } __attribute__((noinline)) void funcDirect(uint8_t n, size_t& __restrict__ dataPos, char* const __restrict__ data) { std::cout << "out direct: n: " << n << " dataPos: " << dataPos << " data: " << data << std::endl; } int main(int nargs, char** args) { char data[1000]; size_t pos = 100; funcStructA(A{10, pos, data}); funcStructB(10, B{pos, data}); funcDirect(10, pos, data); return 0; } The assembly code (g++ -std=c++14 -O3, version 11.2.1 20220127 (Red Hat 11.2.1-9)) in main is: 401119: push QWORD PTR [rsp+0x10] 40111d: push QWORD PTR [rsp+0x10] 401121: push QWORD PTR [rsp+0x38] 401125: call 401280 <funcStructA(A)> 40112a: add rsp,0x20 40112e: mov rsi,rbp 401131: mov rdx,r12 401134: mov edi,0xa 401139: call 4013a0 <funcStructB(unsigned char, B)> 40113e: mov rdx,r12 401141: mov rsi,rbp 401144: mov edi,0xa 401149: call 4014c0 <funcDirect(unsigned char, unsigned long&, char*)> In functStructA the structure is pushed to the stack, for funcStructB the members are passed through the registers. I tried to move n around in the struct or pass it by reference, but the behavior is always the same. I read through the attributes available in gnu (https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes, https://gcc.gnu.org/onlinedocs/gcc/x86-Function-Attributes.html#x86-Function-Attributes) but could not find one that matches my problem. I tried cdcl, fastcall, ms_abi but this changed not that much. Passing the structure by reference causes the same problems. clang++ seems to have the same problem. I will run a test in the next days. Any help would be appreciated.
You could pass the uint8_t or one of the pointers as a separate arg to describe what you want to the compiler, or stuff it into one of the existing 64-bit members (see below). Unfortunately no, there aren't compiler options that tweak the C ABI / calling-convention rules to pass structs larger than 16 bytes in registers on x86-64 or other ISAs. The x86-64 System V ABI doesn't do that, and there isn't another calling convention GCC knows about which does. The Windows x64 ABI only passes up to 8-byte objects in registers, not even 16. Also, you can't override the C++ ABI rule that non-trivially-copyable objects (or whatever the exact criterion is) are passed in memory so they always have an address. (e.g. by value on the stack in x86-64 System V.) The only options I know of that modify the calling convention are -mabi=ms or whatever to select an existing calling convention GCC knows about. Or ones that affect whether certain registers are call-preserved or call-clobbered, like -fcall-used-reg (GCC manual) and some ABI-affecting options like -fpack-struct[=n] that aren't specifically about the calling convention. (And no, -fpack-struct wouldn't help. Bringing sizeof(A) down from 24 to 17 doesn't let it fit in 2 regs. In theory with -fwhole-program or maybe -flto, GCC could invent custom calling conventions, but AFAIK it doesn't. It can take advantage of the fact that another function doesn't clobber certain registers, in terms of inter-procedural optimization (IPO) other than inlining, but not changing how args are passed. The normal way to handle calling-convention overhead is to make sure small functions inline (e.g. by compiling with -flto to allow cross-file inlining), but this doesn't work if you're taking function pointers or using virtual functions. It's not number of members, it's total size, so the x32 ABI (with 32-bit pointers/references and size_t) would be able to pass / return that struct packed into two registers. g++ -O3 -mx32. (x86-64 SysV packs aggregates into up-to-2 registers using the same layout it would in memory, so smaller members means more member fit in 16 bytes.) Or if you can settle for having a 32-bit size by value, or 48-bit size, you could pack the uint8_t into the upper byte of a uint64_t, or even use bitfield members. But since you have a level of indirection (a reference member) for size_t& __restrict__ dataPos;, that member is basically another pointer; using uint32_t& there wouldn't help since a pointer is still 64 bits. I assume you need that to be a reference for some reason. You could pack your uint8_t into the upper byte of a pointer. Upcoming HW will have an option to optimize this, ignoring high bits instead of enforcing correct sign-extension from 48-bit or 57-bit. Otherwise you just manually do that with shifts and & with uintptr_t: Using the extra 16 bits in 64-bit pointers Or since it's easier / more efficient to get data in/out of the bottom of a register on x86-64 (e.g. zero-latency movzx r32, r8), shift the pointer left. That means before deref, you just need an arithmetic right shift to redo sign-extension. This is cheaper than mov r64,imm64 to create as 0xff00000000000000 mask, and as a bonus it sign-extends cheaply so it even works in kernel code. In theory a compiler can even write a partial register to merge a new low-8 in after left-shifting, to create this data. (But if writing to memory, overlapping qword and byte stores could be even better, not even needing a shift. If you aren't re-reading soon enough to cause a store-forwarding stall.) (But if you have a CPU with the LAM feature, you can use the high 8 bits and have the CPU ignore those bits.)
71,872,106
71,885,647
Error: ‘int XYZ::data’ is private within this context
I have one question about the following code snippet in c++ : #include <iostream> using namespace std; class ABC; class XYZ { int data; public: void setvalue(int value) { data=value; } friend void add(ABC,XYZ); }; class ABC { int data; public: void setvalue(int value) { data=value; } friend void add(ABC,XYZ); }; void add(XYZ obj1, ABC obj2) { cout << "Sum of data values of XYZ and ABC objects using friend function = " << obj1.data + obj2.data; cout << "\n"; } int main() { XYZ X; ABC A; X.setvalue(5); A.setvalue(50); add(X,A); return 0; } In particular, when I compile, g++ complains with the following log: g++ -Wall -Wextra -Werror friend_function_add_data.cpp -o friend_function_add_data.o friend_function_add_data.cpp: In function ‘void add(XYZ, ABC)’: friend_function_add_data.cpp:33:86: error: ‘int XYZ::data’ is private within this context 33 | ut << "Sum of data values of XYZ and ABC objects using friend function = " << obj1.data + obj2.data; | ^~~~ friend_function_add_data.cpp:9:5: note: declared private here 9 | int data; | ^~~~ friend_function_add_data.cpp:33:98: error: ‘int ABC::data’ is private within this context 33 | data values of XYZ and ABC objects using friend function = " << obj1.data + obj2.data; | ^~~~ friend_function_add_data.cpp:21:5: note: declared private here 21 | int data; | Since it was complaining about data declared as private, I changed the declaration to public by placing data right after the public statement for each class ABC and XYZ . In this way g++ compiles without problems. What I wonder is : is this the only correct way to handle this issue for this example? do you think it is just a mistake by the author himself? This piece of code is taken from Balagurusamy's "OOP programming with C++" (8th edition, page 124) Edit: thanks Anoop for double checking! I realized I inverted the input arguments for each class ABC and XYZ, w.r.t. to the outer add function taking XYZ obj1 and ABC obj2. So it is written correctly on the book
The problem is that while defining the function add, the order of the two parameters named obj1 and obj2 is opposite to what it was in the friend declaration. So to solve this, make sure that the order of the parameters match in the definition and the friend declaration as shown below: class XYZ { public: //other code here friend void add(ABC,XYZ); }; class ABC { public: //other code here friend void add(ABC,XYZ); }; //ORDER OF PARAMETERS CHANGED TO MATCH WITH THE FRIEND DECLARATION void add(ABC obj1, XYZ obj2) { cout << "Sum of data values of XYZ and ABC objects using friend function = " << obj1.data + obj2.data; cout << "\n"; } int main() { XYZ X; ABC A; X.setvalue(5); A.setvalue(50); add(A,X); //ORDER OF ARGUMENTS CHANGED } Demo
71,872,131
71,872,809
iterating over an unordered_set
I need help iterating over an unordered map in C++. I am trying to put the elements of the set into an array so that I can sort the array. for(auto it=s.begin();it!=s.end();it++){ a[i]=*it; i++; }
Your are using many differen terms here. unordered_set unordered_map set array So, it is a little bit unclear what you really want to do. If you have a std::unordered_setand want to put the data into a std::set, then you can simply use its range constructor and write something like std::set<int> ordered(s.begin(),s.end()); The same would work with a std::vector which has also a range constructor. Arrays, either C-style or C++ std::array are more complicated, because you need to know the size of the original data in advance. Because: Arrays have a compile time definde fixed size. For sorting std::maps or std::unordered_maps according to their "value" and not the key, you need to use a std::multiset with a special sorting functor or lambda. If you edit your question and give more details, then I will provide source code to you.
71,872,152
71,872,153
Unable to compile doctest's `CHECK_THROWS_AS` with Visual Studio 2019
Consider the following code using doctest.h C++ unit test library: #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "doctest.h" TEST_CASE("") { CHECK_THROWS_AS(throw 0, int); } The code creates a single test case with an empty name. The test ensures that throw 0 throws an exception of type int. The example compiles and runs successfully on GCC. However, compiling with Visual Studio 2019 yields an error: [REDACTED]>cl /std:c++17 a.cpp Microsoft (R) C/C++ Optimizing Compiler Version 19.29.30142.1 for x64 Copyright (C) Microsoft Corporation. All rights reserved. a.cpp a.cpp(4): error C2062: type 'int' unexpected How do I fix it? At the same time, a simpler example compiles and works as expected: #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "doctest.h" TEST_CASE("") { CHECK(2 * 2 == 4); }
Visual C++ command line compiler does not fully support C++ exceptions by default, see here. Hence, doctest disables them inside (_CPPUNWIND is left undefined by VS), but the error message is somewhat misleading. You should pass the /EHsc compiler flag: [REDACTED]>cl /EHsc /std:c++17 a.cpp Microsoft (R) C/C++ Optimizing Compiler Version 19.29.30142.1 for x64 Copyright (C) Microsoft Corporation. All rights reserved. a.cpp Microsoft (R) Incremental Linker Version 14.29.30142.1 Copyright (C) Microsoft Corporation. All rights reserved. /out:a.exe a.obj As a sidenote, both Visual Studio's default "Empty project" and CMake configurations include this flag by default:
71,872,205
71,872,668
In template: static_assert failed due to requirement in qt c++
I`m making an app on QT c++. And here is a problem. When I try to create Future in QT, I got many errors. Here is a bit of my code: mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void on_pushButton_clicked(); void on_pushButton_3_clicked(); private: Ui::MainWindow *ui; void SomeFunc(QString path, QString name, QString result, bool isProgressBar); }; #endif // MAINWINDOW_H mainwindow.cpp void MainWindow::SomeFunc(QString path, QString name, QString result, bool isProgressBar) { } void MainWindow::on_pushButton_3_clicked() { auto futureWatcher = new QFutureWatcher<void>(this); QObject::connect(futureWatcher, &QFutureWatcher<void>::finished, futureWatcher, &QFutureWatcher<void>::deleteLater); auto future = QtConcurrent::run( &MainWindow::SomeFunc, file_path, file_name, result_name, isProgressBar ); futureWatcher->setFuture(future); } Here is error: In template: static_assert failed due to requirement 'QtPrivate::ArgResolver<void (MainWindow::*)(QString, QString, QString, bool)>::integral_constant<bool, false>::value' "The first argument of passed callable object isn't a QPromise<T> & type. Did you intend to pass a callable which takes a QPromise<T> & type as a first argument? Otherwise it's not possible to invoke the function with passed arguments." qtconcurrentstoredfunctioncall.h:225:5: error occurred here qtconcurrentstoredfunctioncall.h:248:18: in instantiation of template class 'QtConcurrent::PromiseTaskResolver<void (MainWindow::*)(QString, QString, QString, bool), QString, QString, QString, bool>' requested here qtconcurrentstoredfunctioncall.h:253:30: in instantiation of template class 'QtConcurrent::TaskResolverHelper<std::integral_constant<bool, false>, void (MainWindow::*)(QString, QString, QString, bool), QString, QString, QString, bool>' requested here qtconcurrentrun.h:76:12: in instantiation of template class 'QtConcurrent::TaskResolver<void (MainWindow::*)(QString, QString, QString, bool), QString, QString, QString, bool>' requested here qtconcurrentrun.h:93:12: in instantiation of function template specialization 'QtConcurrent::run<void (MainWindow::*)(QString, QString, QString, bool), QString &, QString &, QString &, bool &>' requested here mainwindow.cpp:163:33: in instantiation of function template specialization 'QtConcurrent::run<void (MainWindow::*)(QString, QString, QString, bool), QString &, QString &, QString &, bool &>' requested here Does anyone know how this can be fixed?
auto future = QtConcurrent::run( &MainWindow::SomeFunc, file_path, file_name, result_name, isProgressBar ); An immediate question comes to mind when seeing any line of code involving a pointer to a member function: "Which instance of is the method being called on?" In this case, none, so there's obviously a problem. We need to provide that information somehow. According to the documentation of QtConcurrent::run, there is a dedicated syntax to handle that case, which requires the target object to be passed as the first argument. Concretely, this means that you are effectively calling the wrong function overload. The compiler does its best to make heads or tails of the code being called, but since the wrong code is being interpreted, it ultimately fails on some seemingly unrelated error. In other words, the error you are getting is due to the compiler being confused. Following the documentation, the code should look like this: QtConcurrent::run(this, &MainWindow::SomeFunc, file_path, file_name, result_name, isProgressBar ); However, interpreting that line of code correctly requires either knowing, learning or guessing how the overload resolution of QtConcurrent::run works, which is not great. Lambdas let you do the same thing with (in my opinion) a lot less cognitive load for a future reader: QtConcurrent::run([=]{ SomeFunc(file_path, file_name, result_name, isProgressBar ); });
71,872,351
71,872,460
Why Does My Multidimensional Array Works Globally, but Not Scoped?
I have a multidimensional array meant to represent 1024 * 1024 2-byte values. When I declare it in global scope, my fstream is able to read into it. When I declare it inside the same function that calls file.read, I get 0xC00000FD (stack overflow exception in windows?) The following works, returning 0 when the program is finished The following does not, exiting with 0xC00000FD Eventually, I'd like to have the textureMap1 variable as part of a struct, but in my troubleshooting, I've found out that I can't seem to read into it, if it's not declared globally. I suspect it's something with static initialization, but I'm not familiar enough with C++ to know the nuances. Why does the global declaration run without issue, but as soon as I move it into a scope, whether it be function scope or a struct, I get a stack overflow exception? Edit Link to Single File Header on pastebin.com https://pastebin.com/raw/enLtebEe To use in a project, you'll need a copy of a carnivores2 map file, as well as defining #STB_OCARN2_IMPLEMENTATION in one file, like stb headers.
By default, programs built on Micrsoft Windows using the Microsoft compiler have a default maximum stack size of about 1 MB. The declaration unsigned short textureMap1[1024][1024]; allocates 2 MB on the stack, if you declare it as an automatic variable. That is why the stack overflows in your case. If you instead declare the array as a global variable, then it won't be allocated on the stack, so it won't be a problem. Stack space is a very limited resource, especially on Microsoft Windows (Linux has a larger default stack size of about 8 MB). Therefore, you should generally not allocate more than a few kilobytes on it, unless you know exactly what you are doing. For allocating such large amounts of data, it is usually better to use dynamic memory allocation, such as new or std::make_unique, or use a container such as std::vector.
71,872,381
71,872,848
how to compile multiple cpp files with main methods at once?
For the sake of example i have 10 cpp files with main method. a.cpp b.cpp c.cpp d.cpp e.cpp f.cpp g.cpp h.cpp i.cpp j.cpp All these scripts do different things so they have their own main method. I have been compiling them one by one for example g++ -o a a.cpp My question is is there a way to compile all cpp files and produce 10 different executables with the same name as the source file. For example a.cpp should produce executable a b.cpp should produce executable b There are more than 50 cpp files so it should produce 50 executables. Is there a way of doing this maybe using a loop? I appreciate any guidance. Thanks!
I'll start by stating I don't believe this question's tags are not exactly related to the problem at hand. The compilation one is the closest one but, even though, I consider the question to be more related to specific environment file selection and string manipulation than anything else. Nonetheless there are several ways of doing it. It mostly comes down to the system in which you want to compile these files and the compilation environment, if any. Basic options will involve Makefiles, Shell Scripting, for Linux environments, Batch Files and PowerShell for Windows environments, and so on. Given the way the question was formulated I'll assume you're on a Linux system using Bash. A simple solution for that would involve a few commonly-distributed tools (you can find out more about each of them on their man pages): for echo awk Assuming you're running the commands in the same folder the source files are located, the following line should do the trick for you: for f in *.cpp; do g++ -o $(echo $f | awk -F.cpp '{printf "%s", $1}') $f; done What the line above is doing is: for f in *.cpp - iterates over all files in the current directory that match the provided wildcard. On each iteration the file name is stored at the $f variable echo $f | awk -F.cpp '{printf "%s", $1}' - this snippet removes the .cpp extension from the file name we've got Edit note: the proposed solution was improved by removing the parsing over ls -l's result because of @clcto's reference in this answer's comments.
71,872,624
71,872,702
Comparing a vector and a vector of struct for matching values - c++
I have a vector of 6 numbers, and another vector which is a vector of my struct that contains numeric data from a file. my vectors are as so (vec1 = 6 random nums, vec2 = file numeric data) vec1 1, 2, 3, 4, 5, 6 vec2 4, 5, 2, 7, 34, 76 5, 7, 3, 7, 1, 23 98, 76, 5, 9, 12, 64 I need to compare vec1 to vec2 to see how many matching numbers are contained in vec2, and return the count of each value found from vec1 in vec2. The issue im having is that my vec2 is a vector of a structure, and vec1 is just a regular vector. How do you compare a vec with a vec of a structure? I've tried the below but the '==' operator doesnt like the comparison between a vec and a struct. //struct to store data from file struct past_results { std::string date; std::string winningnums; }; //vectors to store file content, and 6 random numbers std::vector<past_results> resultvec; std::vector<std::string> random_nums for(int i = 0; i < resultvec.size(); i++) if(randomnums.at(i) == resultvec.at(i)) { //output result } error message: operand types are: std::string == past_results How do I explicitly get the values from my struct vector and compare to my normal vector? For clarity, I have cut out a lot of my code as I didn't believe it to be relevant as i just need to know how I would compare both vectors.
In your if statement you are trying to compare an element of randomnums which is of type std::string to an element of resultvec which is of type past_result. In order to compare the actual winningnums value of the struct, change your if-statement to: if(randomnums.at(i) == resultvec.at(i).winningnums) { //output result }
71,872,705
71,873,841
Is swapping a const member undefined behavior? C++17
https://godbolt.org/z/E3ETx8a88 Is this swapping UB? Am I mutating anything? UBSAN does not report anything. #include <utility> struct MyInt { MyInt(int ii): i(ii) {} const int i; MyInt& operator=(MyInt&& rh) { std::swap(const_cast<int&>(i), const_cast<int&>(rh.i)); return *this; } }; int main() { MyInt i0(0); MyInt i2(2); i0 = std::move(i2); return i0.i; }
This seems to be an area of c++ evolution. It's UB in c++17 because of this restriction on replacing const member objects However, in later versions, this restriction is mostly removed.. There remains a restriction on complete const objects. For instance you can't do this if MyInt i0(0); was const MyInt i0(0); Even though c++20 now allows modification of const sub objects, it's best to avoid const_cast and use this to create an assignment ctor. In this case one doesn't need a destructor since it's trivially destructable. Note that one had to use placement new prior to c++20 and that was still UB since const sub objects were not permitted to change previously. constexpr MyInt& operator=(MyInt&& rh) { std::construct_at(&this->i, rh.i); return *this; }
71,873,800
71,873,935
std::unique_copy with overlapping ranges
template< class InputIt, class OutputIt > OutputIt unique_copy( InputIt first, InputIt last, OutputIt d_first ); Is it valid to use std::unique_copy if input range and output range overlap? Consider the following two example cases auto d_last = std::unique_copy(first, last, d_first); d_first <= first <= d_last <= last first <= d_first <= last <= d_last
The preconditions for std::unique_copy are described in [algorithms#alg.unique-8]: template<class InputIterator, class OutputIterator> constexpr OutputIterator unique_copy(InputIterator first, InputIterator last, OutputIterator result); Preconditions: The ranges [first, last) and [result, result+(last-first)) do not overlap. So this is undefined behavior.
71,873,890
72,053,725
How to erase line if entry it doesn't match variable
I am trying to make a program where you have to sign in with a password. If the password is incorrect it is supposed to erase the line so you can try again. Instead it just makes new lines. Any ideas on how to make this work? cout << "--Bank Account Database--\n"; string password = "wfadmin"; string pwentry; int entryCount = 0; while (pwentry != password) { if (entryCount == 0) { string login = "\n\n\nEnter your password: "; cout << login; getline(cin, pwentry); cout << string(login.length(), '\b'); entryCount++; } else { string login = "\nIncorrect. Try again.\n\nEnter your password: "; cout << login; getline(cin, pwentry); cout << string(login.length(), '\b'); } }
It can be done. However, I do not know of a portable way of doing it. The reason for that is that echoing of stdin is a console property, and not part of the C++ standard. There is a library designed to address that problem: ncurses Beyond that, your loop can be simplified quite a bit. (See: ideone) If there is a portable solution, I'm really interested to know. I spent about 5 hours looking around, and this was the best I got.
71,874,667
71,875,003
Overloaded 'operator<<' must be a binary operator (has 3 parameters)
I am trying to implement Heap ADT in C++. I am currently facing a problem in the my overloaded operator<<. I saw many solutions but non worked for me: first solution || Here is the second one Here is the hpp file: #ifndef Heap_hpp #define Heap_hpp #include <stdio.h> #include <vector> #include <string> #include <iostream> using namespace std; typedef int elementType; class Heap{ private: vector<elementType> myVecrtor; int mySize = 1; //The minimum size is 1 since //the first element is a dummy. public: Heap(); //some functions... //My problem is in this function friend ostream& operator<<(ostream &out, Heap &h); void perculateDown(int root); void perculateUp(); }; #endif /* Heap_hpp */ Here is the cpp file: #include "Heap.hpp" using namespace std; Heap::Heap(){ } ostream& Heap::operator<<(ostream &out, Heap &h){//it is giving me the error here out<<"\t\tHeap:"; for(int i = 0; i < mySize; i++){ out<<myVecrtor.at(i);//this is not what i actualy want to display, just a demo } return out; } I need to mention that i tried it not as a friend and it gave me the same error And when initializing the function inside the cpp file like this: ostream& operator<<(ostream &out, Heap &h) the error was gone but i wasn't able to use any member. Any help other than the solutions I have mentioned would be appreciated. Also removing the qualification (Heap::) prevents me from using any member of my class for some reason. error: Use of undeclared identifier 'mySize' image showing the error I tried using h.mySize, it gave me: 'mySize' is a private member of 'Heap' private member error photo
The problem is that you've defined the overloaded operator<< as a member function of class Heap instead of defining it as a non-member function. To solve this you should remove the Heap qualification(Heap::) while defining the overloaded operator<< as shown below: //------v-----------------------------------> removed Heap:: from here std::ostream& operator<<(std::ostream &out, Heap &h){ for(int i = 0; i < h.mySize; i++){ //---------------------^^-------------------->added h. here out<<h.myVecrtor.at(i); //-----------^^------------------------------>added h. here } return out; } Additionally, when implementing the overloaded operator<<, we make the second parameter as an lvalue reference to const since operator<< doesn't change the state of the object. So after modification the code would look something like: class Heap{ //other code as before public: //------------------------------------------vvvvv------------>added const here friend std::ostream& operator<<(std::ostream &out,const Heap &h); }; //------v---------------------------------------------> removed Heap:: from here std::ostream& operator<<(std::ostream &out,const Heap &h){ //-------------------------------^^^^^---------------->added const here for(int i = 0; i < h.mySize; i++){ out<<h.myVecrtor.at(i);//this is not what i actualy want to display, just a demo } return out; } Demo Important Note Note that you should not use using namespace std; inside header files like you've done in your example. You can refer to Why is "using namespace std;" considered bad practice?. Also, note that since operator<< is a non-member function, so we have to use h.mySize and h.myVecrtor.at(i) instead of just using mySize and myVecrtor.at(i).
71,874,730
71,876,340
Qt5 + CMake + QThread: the signal from abstract base class is not connected to the slot in another thread
I implemented a hierarchy of classes to handle sensor interaction in a multithreaded QThread-based manner, as how it is recommended in Qt documentation. Here I have the header file types.h with the abstract base sensor reader class: #include <QtCore> class QAbstractSensorReader: public QObject { Q_OBJECT protected slots: virtual void ReadData() = 0; public slots: virtual void RunPoll() = 0; signals: void acquired(); }; In the file serial.h implementing the actual sensor reader I have the following text: #include "types.h" class QBaseSerialSensorReader: public QAbstractSensorReader { Q_OBJECT private: /*===*/ protected: QTextStream ttyout; QTimer* poll_timer; virtual void ReadData(); public: QBaseSerialSensorReader(const QString device); virtual ~QBaseSerialSensorReader(); virtual void RunPoll(); }; The signal acquired() is emitted in the ReadData() handler when the data packet is assembled completely during the sensor poll. The slot RunPoll() is used to initialize and start a timer. Then I implemented the controller class: #include "serial.h" class QSensor: public QObject { Q_OBJECT private: QThread reader_thread; QBaseSerialSensorReader* reader; public: QSensor() { reader = new QBaseSerialSensorReader(); reader->moveToThread(&reader_thread); connect(&reader_thread, &QThread::finished, reader, &QObject::deleteLater); connect(this, &QSensor::RunReader, reader, &QAbstractSensorReader::RunPoll); connect(reader, &QBaseSerialSensorReader::acquired, this, &QSensor::Packet); reader_thread.start(); } void Start() {emit RunReader();} virtual ~QSensor(); public slots: void Packet(){ttyout << "ACQUIRED!";} signals: void RunReader(); }; Then the application: #include "controller.h" int main(int argc, char** args) { QCoreApplication app(argc, args); QSensor sensor(); sensor.Start(); sleep(10); return 0; } exploits the hierarchy. The CMake file contains the following text: find_package(Qt5 REQUIRED COMPONENTS Core SerialPort) set(CMAKE_AUTOMOC ON) qt5_wrap_cpp(MOC_SOURCES include/types.h include/serial.h include/contoller.h ) set(LIBRARY_SOURCES ${MOC_SOURCES} src/util.cpp src/serial.cpp src/controller.cpp ) add_library(sensor-serial SHARED ${LIBRARY_SOURCES}) target_link_libraries(sensor-serial Qt5::Core Qt5::SerialPort) add_executable(library-init-test tests/library-init-test.cpp ) target_link_libraries(library-init-test Qt5::Core Qt5::SerialPort sensor-serial ) The problem is that the signal QSensor::RunReader is successfully connected to QAbstractSensorReader::RunPoll slot: the virtual function QBaseSerialSensorReader::RunPoll() is called. The timer is also started and the ReadData() function works emitting the acquired signal. But this signal then does not seem to be connected to the QSensor::Packet() slot neither from QAbstractSensorReader nor from QBaseSerialSensorReader namespace. Could you please try to explain what wrong is happening with this code?
You are not entering application event loop. Remove sleep from main function and call QCoreApplication::exec. I.e. replace these lines sleep(10); return 0; with return app.exec();
71,875,107
71,876,428
How to pass a DBus variant to Qt's QDBusInterface::call
I am trying to send the following message to Connman over Qt 5.12's DBus API: dbus-send --system --print-reply --dest=net.connman / net.connman.Manager.SetProperty string:"OfflineMode" variant:boolean:true As seen, the SetProperty method takes a dbus string and a dbus variant. If I look at the signature with qdbus, I get the following: $ qdbus --system net.connman / | grep Manager.SetProperty method void net.connman.Manager.SetProperty(QString name, QDBusVariant value) So that's what I do... iface.call("SetProperty", "OfflineMode", QDBusVariant(!m_flightModeOn)); However, I get the following compile error: error: no matching function for call to ‘QDBusInterface::call(const char [12], const char [12], QDBusVariant)’ QDBusReply<QVariantMap> reply = iface.call("SetProperty", "OfflineMode", QDBusVariant(true)); Here is the complete function: void enableFlightMode() { QDBusInterface iface("net.connman", "/", "net.connman.Manager", QDBusConnection::systemBus()); if (iface.isValid()) { QDBusReply<QVariantMap> reply = iface.call("SetProperty", "OfflineMode", QDBusVariant(true)); } qDebug() << qPrintable(QDBusConnection::systemBus().lastError().message()); } I have tried passing both a bool and a QVariant to ::call, but those result in DBus in a dbus error: Method "SetProperty" with signature "sb" on interface "net.connman.Manager" doesn't exist. This makes sense since the signature is a string and a variant. I guess my question is, according to the Qt DBus API type system docs, QDBusVariant() is supposed to be analogous to the DBus "VARIANT", so I would expect to be able to pass it into this function. Is there another way I can pass a DBus variant through this API?
I have found a workaround using a different part of the API... Utilizing QDBusMessage, this can be done: QDBusMessage message = QDBusMessage::createMethodCall("net.connman", "/", "net.connman.Manager", "SetProperty"); QList<QVariant> arguments; arguments << "OfflineMode" << QVariant::fromValue(QDBusVariant(true)); message.setArguments(arguments); QDBusConnection::systemBus().call(message); qDebug() << qPrintable(QDBusConnection::systemBus().lastError().message()); For anyone doing similar things with Connman, check out cmst. It uses Qt to communicate with Connman over DBus.
71,875,304
71,875,925
Is there an example of specializing std::allocator_traits::construct?
I have the task of porting some code to c++20. Part of it is an templated allocator that handles some of the odd needs or Microsoft COM objects so we can use them in vectors. In part, it allocates/deallocates memory via CoTaskMemAlloc/CoTaskMemFree It also provides specializations of construct and destroy which have gone way in c++20. For Example: // VARIANT inline void CnvCoTaskAlloc<VARIANT>::construct(VARIANT* p, const VARIANT& val){ ::VariantCopy( p, const_cast<VARIANT*>( &val ) ); } inline void CnvCoTaskAlloc<VARIANT>::destroy(VARIANT* p){ ::VariantClear( p ); } I am having a hard time working out how to migrate this code to c++20. If I could find an example of doing something similar that implements construct, I am pretty sure it would be obvious. Thanks in Advance.
The standard has the following to say about specializing standard library templates ([namespace.std]/2): Unless explicitly prohibited, a program may add a template specialization for any standard library class template to namespace std provided that (a) the added declaration depends on at least one program-defined type and (b) the specialization meets the standard library requirements for the original template. The standard specifies the following behaviour for std::allocator_traits<Alloc>::construct ([allocator.traits.members]/5): template<class T, class... Args> static constexpr void construct(Alloc& a, T* p, Args&&... args); Effects: Calls a.construct(p, std::forward<Args>(args)...) if that call is well-formed; otherwise, invokes construct_at(p, std::forward<Args>(args)...). So, if you choose to specialize std::allocator_traits<MyAlloc>::construct, it must do basically the same thing as the primary template: it will call MyAlloc::construct if possible, otherwise construct_at. This suggests that specializing std::allocator_traits is generally not what you want to do. Instead, just like pre-C++20, you just need to make sure that MyAlloc::construct contains the logic that you want. If you want the default, you can even omit MyAlloc::construct entirely, and std::allocator_traits will take care of it.
71,875,477
71,876,095
Updating value of class variables - C++
I'm just beginning to learn how to code and I've come across a problem I can't seem to solve. More specifically the problem occurs in the "borrows" function. In the following program I am somehow unable to update the value of the public class variable "stock" even though I used getters and setters. It seems to be updated correctly on the cout right after but not "saved permanently". My guess is that it's modifying a copy of the variable rather than the variable itself. I have attached my code to the post! Please let me know if I should upload the whole file! Thanks in advance! void Book::borrows() { int searchid; bool isfound=false; cout<<"Please enter the unique ID of the book:\t\t"; cin>>searchid; for(auto i:myBooks){ if (i.id==searchid){ cout<<"This book matches your search:\t"; print(i); if (i.stock==0) { cout<<"Book is out of stock!"<<endl; } else { setStock((i.stock-1)); cout<<"Successfully borrowed!! Now there are only "<<getStock()<<" copies left in stock!"<<endl; } isfound=true; } } if (isfound== false){ cout<<"++++\t\tBook not found++++\t\t"<<endl; } system("pause"); } int Book::getStock() const { return stock; } void Book::setStock(int newstock) { Book::stock = newstock; } Edit 1: Here is my Class structure and my vector: class Book{ public: int id; string title; int stock; void add(); void displayall(); void displayspecific(); void print(Book); void borrows(); void returns(); int getStock() const; void setStock(int stock); }; vector<Book> myBooks;
Your actual problem is that you are operating on a copy of the Book object, not the setters and getters of the members of a book. for(auto i:myBooks){ You need for(auto &i:myBooks){ But as other have pointed out, you need 2 classes, Library and Book.
71,875,808
71,875,933
How to update value in progressBar in another thread in QT c++
I develop a qt program with an interface. I also have a complex calculation that is done on a separate thread from the ui thread. I want to update the progressBar from the thread in which the calculations are done. But I get an error that I cannot change an object that belongs to another thread. Here is my code: void Somefunc() { ui->progressBar->setValue(progress); } void MainWindow::on_pushButton_3_clicked() { auto futureWatcher = new QFutureWatcher<void>(this); QObject::connect(futureWatcher, &QFutureWatcher<void>::finished, futureWatcher, &QFutureWatcher<void>::deleteLater); auto future = QtConcurrent::run( [=]{ SomeFunc(); }); futureWatcher->setFuture(future); } How correctly update the progress bar?
Use a signal/slot combination, specifically the queued connection type (Qt::ConnectionType). So, along those lines: void MainWindow::Somefunc() { emit computationProgress(progress); } void MainWindow::setProgress(int progress) { ui->progressBar->setValue(progress); } void MainWindow::on_pushButton_3_clicked() { auto futureWatcher = new QFutureWatcher<void>(this); connect(futureWatcher, &QFutureWatcher<void>::finished, futureWatcher, &QFutureWatcher<void>::deleteLater); auto future = QtConcurrent::run( [=]{ SomeFunc(); }); futureWatcher->setFuture(future); connect(this, &MainWindow::computationProgress, this, &MainWindow::setProgress, Qt::QueuedConnection); }
71,876,111
71,876,269
When using streams do you need to sync after cudamalloc
When using streams in cuda, is it necessary to perform any synchronization between memory allocations and usage of this memory by a stream (assuming cudaMallocAsync is not available, which it is not for me). example: cudaStream_t stream; cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking); ... Other code int *a; gpuErrchk(cudaMalloc((void **)&a, sizeof(int))); foo<<<1, 1, 0, stream>>>(a); gpuErrchk(cudaStreamSynchronize(stream)); cudafree(a); Is there a chance that when calling foo in such a situation, that the memory allocation is not completed? Would I be forced to do a device synchronize after the allocation to be sure?
There is no chance that the memory allocation will not be completed. You don't need an explicit device synchronization after a memory allocation. When the cudaMalloc call returns, the memory is allocated and usable.
71,876,202
71,889,274
EmguCV: Emplace one Mat onto another?
In C++ if you wanted to emplace one mat into another, the code would simply be: clone_img.emplace(out_mat); Now, I know in C# there is no real equivalent to the "emplace" method. If I was working with other data types in a more standard collection, I can find the answer for what I want to do on Google. Working with a cv::Mat is a bit different though, and I can't find anything about that. There is a Mat.PushBack method, but it doesn't construct the new object in-place within the collection. Or does that not matter? What is the C#/EmguCV equivalent of this emplacement, and what would be the differences under the hood to be aware of?
I found the answer for what I wanted to do, although it may not exactly answer this above question. What I wanted to do was to create an empty Mat, and then call Mat.emplace() to put something else in it. I found out it was as simple as doing: Mat newMat = old_mat;
71,876,207
71,876,366
instance of 'std::out_of_range' error disappear with a change in expression of an integer
i'm into a problem that looks like this : Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Example 1: Input: s = "([])" Output: true Example 2: Input: s = "()[]{}" Output: true Example 3: Input: s = "([)]" Output: false Constraints: 1 <= s.length <= 104 s consists of parentheses only '()[]{}'. the way i solve it is to put it into a for loop,and replace all the substring that look like"()","{}" with a "",an empty string. If there's no character remaining, then it should be true. here's my code: class Solution { public: bool isValid(string s) { if(s.length()%2!=0) return false; else{ int Len=s.length(); int len=Len/2; int pos1=0,pos2=0,pos3=0; for(int i=0;i<len;i++){ pos1=s.find("()"); if(pos1<Len){ s=s.replace(pos1,2,""); } pos2=s.find("{}"); if(pos2<Len){ s=s.replace(pos2,2,""); } pos3=s.find("[]"); if(pos3<Len){ s=s.replace(pos3,2,""); } } return s.length()==0; } } }; If I just run the code above, it'll report the following information: "terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::replace: __pos (which is 18446744073709551615) > this->size() (which is 0)". However, if I change the "pos1/2/3" in every if statement to the corresponding expression like s.find("()") , there will no longer be a problem. Or I change the "Len" integer in every if statement to it's value--s.length(), the problem will disappear, too. I wonder what's the difference between my code and the other two versions. I just can't figure it out cause that seems like just a equivalent transformation to me.
std::string::find returns an unsigned integer type, size_t. If the string isn't found, it returns std::string::npos which is the largest possible value representable in size_t. This value is outside of the range of int and gets converted to the int value -1. This results the condition in e.g. if(pos1<Len){ evaluating to true. The first parameter of std::string::replace is size_t and your int gets converted back to size_t yielding the large index value the program complains about. if you use if(s.find("()") < Len){ though, Len gets converted to size_t which doesn't result in any surprises, since the string length should be representable as int the conversion of the string length from size_t to int and back to size_t doesn't change the value. Don't convert between integral types, without a good reason (or at lest be sure the values are representable in the target type of the conversion). Changing the integral types used to size_t should fix the issue in your program. Note that using auto and comparison to the constant std::string::npos would be a good choice here, since you don't need to bother with the exact types. Furthermore working with std::string::erase is a function that better fits the operation happening here (replacing some substing by nothing). auto const Len = s.length(); ... auto const pos1 = s.find("()"); if(pos1 != std::string::npos){ s.erase(pos1, 2); }
71,876,809
71,877,102
Is it possible to avoid copying a temporary class instance passed to a function that saves a pointer to it?
I have a class Holder with a vector that holds instances of different classes (e.g. Derived) derived from the same abstract base class (Base). I constructed it as a vector of pointers to the base class to support polymorphism. New instances are added to the vector via a method called add. The new classes are constructed inside the parentheses when calling add and are not named (this mechanism is supplied to me and cannot be changed). I do not quite understand what the lifetime of this constructed class is and how can I prevent it from being destructed right after exiting add. It has to be constructed, so is there a way to keep it alive and hold a valid pointer to it? Or will I have to create a copy and let the passed temporary die? I am using C++17, none of my classes allocate memory manually, only STL containers and primitive data types are used. I've been looking at std::move() but I did not find what I needed. Example code: class Base { public: std::vector<int> vec; virtual void foo() = 0; } class Derived : public Base { public: Derived(int a, int b) { vec.push_back(a); vec.push_back(b); } void foo() override; } class Holder { public: std::vector<Base*> ptrs; void add(Base& arg) // What should be the type of arg? (Does not have to be Base&) { ptrs.push_back(&arg); // How should I add a pointer to arg into ptrs so that // arg stays alive after returning from this method? } } int main() { Holder h; h.add(Derived(1, 2)); // this is how add() gets called, I cannot change it ... } EDIT: To clarify, I can change the signature and body of add as well as the data type that vector ptrs uses. I cannot change the way add is called (h.add(Derived(1, 2));).
In main the parameter passed is a temporary destroyed just after the call to add returns. You may store this value, the address, but you must never dereference it. If you want to ensure the the object remains valid for the lifetime of Holder your only option is taking over the ownership of an existing object or making a copy you've got ownership of. Taking ownership of an existing object For this using std::unique_ptr would be preferrable to make the ownership clear. class Holder { ... void add(std::unique_ptr<Base>&& arg) { //preferrably make ptrs a std::vector<std::unique_ptr<Base>> and use ptrs.emplace_back(std::move(arg)) or ptrs.push_back(args.get()); args.release(); // make sure the object gets deleted before or during destruction of the Holder object } }; Making a copy Use the move constructor here to void a copy class Holder { ... template<class T> void add(T&& arg) // What should be the type of arg? { ptrs.push_back(new T(std::forward<T>(arg)); // Note: make sure the object created here gets destroyed } }; EDIT According to the updated answer this is the implementation of Holder I'd go with: class Holder { public: std::vector<std::unique_ptr<Base>> ptrs; // make this private? template<class T> void add(T&& arg) { // better compiler error on incorrect use static_assert(std::is_base_of_v<Base, T>, "parameter passed must be an object of a class derived from Base"); ptrs.reserve(ptrs.size() + 1); // if an std::bad_alloc happens, this gives you a strong exception guarantee ptrs.emplace_back(std::make_unique<T>(std::forward<T>(args))); } }; Note: This only works with a virtual destructor of Base; if this isn't an option, you'll need to save logic for invoking the correct destructor alongside the object. You do not prevent the creation of the temporary Derived object, but at least it's possible to use the implicitly created move constructor of Derived to prevent unnecessary copies of the elements of Base::vec
71,876,832
71,877,896
Qt how to center widget with a maximum width?
How can I horizontally center a widget in Qt, in such a way that it stretches out up to a certain size? I tried the following: QVBoxLayout *layout = new QVBoxLayout(this); QProgressBar *progressBar = new QProgressBar(); progressBar->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); progressBar->setMaximumWidth(1000); layout->addWidget(progressBar, 0, Qt::AlignCenter); However, the progress bar is always smaller than 1000px. How could I make it to stretch to 1000px, but shrink if the parent widget is smaller and center it at the same time?
Can be fixed by replacing QVBoxLayout with QHBoxLayout and replacing layout->addWidget(progressBar, 0, Qt::AlignCenter); with layout->addWidget(progressBar); progressBar->setAlignment(Qt::AlignCenter);, guess these two alignments are different. QHBoxLayout *layout = new QHBoxLayout(this); QProgressBar *progressBar = new QProgressBar(); progressBar->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); progressBar->setMaximumWidth(1000); progressBar->setAlignment(Qt::AlignCenter); layout->addWidget(progressBar);
71,877,509
71,877,734
Constructor cannot be redeclared C++
Tp start, I want to say that I am new to C++. I am trying to declare my constructor 3 times, because i have 3 more derived classes, which work with different variables. But i get this error, so i don't really know what to do then... The task is to create a class with derived classes of different ways of payments and print it out using an array of polymorphic objects. That's why i use derived classes class employee{ private: char type[25]; int hours; int salary_per_hour; int days; int salary_per_day; int sales_per_month; int percent_per_sales; public: employee() { hours = salary_per_hour = days = salary_per_day = sales_per_month = percent_per_sales = 0; strcpy(type, "unknown"); } employee(int h, int d, int sph, char *n) { hours = h; days = d; salary_per_hour = sph; strcpy(type, n); } employee(int d, int spd, char *n) { days = d; salary_per_day = spd; strcpy(type, n); } employee(int b, int spm, int pps, char *n) { //This one doesn't declare sales_per_month = spm; percent_per_sales = pps; strcpy(type, n); } int getHours() { return hours; } int getDays() { return days; } int getSPD() { return salary_per_day; } int getSPH() { return salary_per_hour; } int getSPM() { return sales_per_month; } int getPPS() { return percent_per_sales; } char *getType() { return type; } virtual int salary() { cout << "ERROR | salary() must be overridden.\n"; return 0; }}; class hourly_payment: public employee{ public: hourly_payment(int h, int d, int sph) : employee(h, d, sph, "hourly_payment") { } int salary() { return getHours()*getDays()*getSPH(); } }; class daily_payment: public employee{ public: daily_payment(int d, int spd) : employee(d, spd, "hourly_payment") { } int salary() { return getDays()*getSPD(); } }; class percent_per_sales_payment: public employee{ public: percent_per_sales_payment(int b, int spm, int pps) : employee(b, spm, pps, "percent_per_sales_payment") { } int salary() { return getSPM()*getPPS(); } };
That's because your constructor was redefined. The compiler doesn't care about variable names, all he sees in your case is data type. employee(int, int, int, char *) Which is the same in both cases employee(int b, int spm, int pps, char *n) { //This one doesn't declare sales_per_month = spm; percent_per_sales = pps; strcpy(type, n); } and employee(int h, int d, int sph, char *n) { hours = h; days = d; salary_per_hour = sph; strcpy(type, n); } Both of them has the same prototype employee(int, int, int, char *) The easiest solution in your case is to change the order of the parameters. You can do for example: employee(char *n, int h, int d, int sph) { hours = h; days = d; salary_per_hour = sph; strcpy(type, n); } In this case you have a new prototype that doesn't match any other. employee(char *, int, int, int) Another way of dealing with this if you have the same type of variables in your constructor is by using enums as a parameter called employee_type and based on which type you pass to employee_type, you can choose what kind of assignment you want to do in your constructor.
71,877,651
71,877,712
How to write the string representation of the contents of a file?
In my file let's assume it has the following content: my_file.txt /* My file "\n". */ Hello World If I wanted generate a file and pass this same content as a string in C code, the new file would look like this: my_generated_c_file.c const char my_file_as_string[] = "/* My file \"\\n\". */\nHello World\n\n"; In an unfortunate attempt, I tried to simply add the chars one by one: #include <stdio.h> int main () { FILE *fp_in = fopen("my_file.txt", "r"); FILE *fp_out = fopen("my_generated_c_file.c", "w"); fseek(fp_in, 0L, SEEK_END); long size = ftell(fp_in); fseek(fp_in, 0L, SEEK_SET); fprintf(fp_out, "const char my_file_as_string[] = \""); while (size--) { fprintf(fp_out, "%c", getc(fp_in)); } fprintf(fp_out, \";\n\n"); fclose(fp_in); fclose(fp_out); return 0; } But that doesn't work because a '\n' for example is read as a line break and not "\\n". How to solve this?
You could simply print a '\\' wherever a '\' was present in the original file: while (size--) { char next_c = getc(fp_in); if(next_c == '\\') { fputs("\\\\", fp_out); } else { fputc(next_c, fp_out); } } You'll probably also want to perform other such transformations as well, such as replacing line breaks with \n.
71,877,876
71,878,112
How to remove trailing zeros with scientific notation when convert double to string?
Live On Coliru FormatFloat I try to implement one conversion of Golang strconv.FormatFloat() in C++. #include <sstream> #include <iostream> #include <string> #include <iomanip> using namespace std; std::string convert_str(double d) { std::stringstream ss; if (d >= 0.0001) { ss << std::fixed << std::setprecision(4); // I know the precision, so this is fine ss << d; return ss.str(); } else { ss << std::scientific; ss << d; return ss.str(); } } int main() { std::cout << convert_str(0.002) << std::endl; // 0.0020 std::cout << convert_str(0.00001234560000) << std::endl; // 1.234560e-05 std::cout << convert_str(0.000012) << std::endl; // 1.200000e-05 return 0; } Output: 0.0020 1.234560e-05 // should be 1.23456e-05 1.200000e-05 // should be 1.2e-05 Question> How can I setup the output modifier so that the trailing zero doesn't show up? strconv.FormatFloat(num, 'e', -1, 64) The special precision value (-1) is used for the smallest number of digits necessary such that ParseFloat() will return f exactly.
At the risk of being heavily downvoted criticised for posting a C answer to a C++ question ... you can use the %lg format specifier in a call to sprintf. From cpprefernce: Unless alternative representation is requested the trailing zeros are removed, also the decimal point character is removed if no fractional part is left. So, if you only want to remove the trailing zeros when using scientific notation, you can change your convert_str function to something like the following: std::string convert_str(double d) { if (d >= 0.0001) { std::stringstream ss; ss << std::fixed << std::setprecision(4); // I know the precision, so this is fine ss << d; return ss.str(); } else { char cb[64]; sprintf(cb, "%lg", d); return cb; } } For the three test cases in your code, this will give: 0.0020 1.23456e-05 1.2e-05 From C++20 and later, the std::format class may offer a more modern alternative; however, I'm not (yet) fully "up to speed" with that, so I cannot present a solution using it. Others may want to do so.
71,878,217
71,878,326
Input validation C++
I need help with input validator, whenever the console gets a wrong input, it does the job to determine whether the input is valid or not but here I have a problem where if I put a wrong input first, I have to re-enter the next input twice for it to go to Enter operator line. #include <iostream> #include <windows.h> using namespace std; main() { // Declaring variables float num1; char user_operator; // Code Structure cout << "Junie's C++ Calculator v.1" << endl << endl; cout << "Enter first number >> "; // Error checking + Input while (! (cin >> num1)) { system("CLS"); cout << "Junie's C++ Calculator v.1\n\n"; // Clear the input cin.clear(); cin.ignore(); // Ask for the input again cout << "(!) Enter first number >> "; cin >> num1; } cout << "Enter operator >> "; }
I have to re-enter the next input twice That is because you are asking for input twice: while (! (cin >> num1)) { ... // Ask for the input again cout << "(!) Enter first number >> "; cin >> num1; // <-- } If the user enters bad input, !(cin >> num1) is true, so the loop is entered, and then cin >> num1 gets executed twice, once at the end of the current loop iteration, and then again in the while condition of the next loop iteration. The next loop iteration will only evaluate the 2nd input. So, you need to remove the cin >> num1 at the end of the loop: while (! (cin >> num1)) { ... // Ask for the input again cout << "(!) Enter first number >> "; // cin >> num1; // <-- remove this! } On a separate note: cin.ignore(); ignores only 1 character, but more times than not you need to ignore more characters than that. It is customary to use this instead: cin.ignore(numeric_limits<streamsize>::max(), '\n'); Which will ignore all characters up to the next Enter entered by the user. Using numeric_limits<streamsize>::max() as the number of characters to ignore is handled as a special-case: https://en.cppreference.com/w/cpp/io/basic_istream/ignore ignore behaves as an UnformattedInputFunction. After constructing and checking the sentry object, it extracts characters from the stream and discards them until any of the following conditions occurs: count characters were extracted. This test is disabled in the special case when count equals std::numeric_limits<std::streamsize>::max() end of file conditions occurs in the input sequence, in which case the function calls setstate(eofbit) the next available character c in the input sequence is delim, as determined by Traits::eq_int_type(Traits::to_int_type(c), delim). The delimiter character is extracted and discarded. This test is disabled if delim is Traits::eof() This is basically telling ignore() to not keep track of the count at all, just keep ignoring everything until another condition tells it to stop. If you specify any other value for the count, ignore() will have to keep track of how many characters it has ignored and then exit when that count has been reached. And there is no standard to how many characters constitute a line of input. Different console implementations have different limits on line input.
71,878,695
71,878,892
How to save a persistent value for application access across multiple runs?
As the title states, I would like to store a variable (which will always be an positive integer < 10,000) for my application to access and process as needed across multiple runs. My current implementation simply saves the value to a file, in the current directory, and then reads it in when needed. #include<fstream> int x = 5; std::ofstream write_file(file_handle); write_file << value; write_file.close(); However, I'm not too keen on the idea of having an orphaned text file if the user decides to place the .exe on their desktop. So, what other options do I have to store the value? I'm primarily concerned with Windows 8+.
There is nothing wrong with using a file, but you don't have to (and should not) store it in the same folder as the .exe file, as it may not work depending on where the .exe is located (for instance, non-admins can't write to Program Files). Windows sets aside special folders in the user's profile just for application-generated data, so you should store the file in one of those folders instead. Use the Win32 SHGetFolderPath() or SHGetKnownFolderPath() function to discover where those special folders are located, and then you should create a sub-folder for your application's use (you can even use SHGetFolderPathAndSubDir() for that purpose). For example: #include <fstream> #include <filesystem> #include <windows.h> #include <shlobj.h> namespace fs = std::filesystem; fs::path pathToMyValueFile() { WCHAR szPath[MAX_PATH]; if (SHGetFolderPathAndSubDirW(NULL, CSIDL_LOCAL_APPDATA | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, L"MyApp", szPath) != S_OK) { throw ...; } return fs::path(szPath) / L"value.dat"; /* alternatively: if (SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, szPath) != S_OK) throw ...; fs::path folder = fs::path(szPath) / L"MyApp"; fs::create_directory(folder); return folder / L"value.dat"; */ } ... int value = 0; std::ifstream read_file(pathToMyValueFile()); if (read_file.is_open()) { read_file >> value; read_file.close(); } ... int value = 5; std::ofstream write_file(pathToMyValueFile()); if (write_file.is_open()) { write_file << value; write_file.close(); } In the future, if the user ever uninstalls your app, be sure to delete that subfolder. Otherwise, you can store the value in the Windows Registry instead. Create a new key for your application under HKEY_CURRENT_USER\Software or HKEY_LOCAL_MACHINE\Software as needed, and then you can create values inside that key. For example: #include <fstream> #include <windows.h> int readMyValue() { int value; HKEY hKey; LSTATUS lRes = RegOpenKeyExA(HKEY_CURRENT_USER, "Software\\MyApp", 0, KEY_QUERY_VALUE, &hKey); if (lRes == ERROR_SUCCESS) { DWORD size = sizeof(value); lRes = RegQueryValueExA(hKey, "Value", NULL, NULL, (LPBYTE)&value, size); RegCloseKey(hKey); } if (lRes != ERROR_SUCCESS) { if (lRes != ERROR_FILE_NOT_FOUND) throw ...; value = 0; } return value; } void saveMyValue(int value) { HKEY hKey; LSTATUS lRes = RegCreateKeyExA(HKEY_CURRENT_USER, "Software\\MyApp", 0, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &hKey, NULL); if (lRes == ERROR_SUCCESS) { DWORD size = sizeof(value); lRes = RegSetValueExA(hKey, "Value", 0, REG_DWORD, (BYTE*)&value, sizeof(value)); RegCloseKey(hKey); } if (lRes != ERROR_SUCCESS) throw ...; /* alternatively: if (RegSetKeyValueA(HKEY_CURRENT_USER, "Software\\MyApp", "Value", REG_DWORD, &value, sizeof(value)) != ERROR_SUCCESS) throw ...; */ } ... int value = readMyValue(); ... int value = 5; saveMyValue(value); If your app is uninstalled later, be sure to delete the Registry key.
71,878,766
71,878,828
How to read n to n + i lines in c++?
This is the file to be read 5 Name1 Name2 Name3 Name4 Name5 My current code to read this is: void readData(string fileName, string names[], int n) { ifstream myFile("file.txt"); string line; if (myFile.is_open()) { myFile >> n; // read first line cout << n; for (int i = 0; i < n; ++i) { getline(myFile, line); names[i] = line; cout << names[i] << endl; } } } I want to put the names into the array names[], but even though n = 5, it seems like it runs only 4 times. Why is that? This is my current output that I get: 5 Name1 Name2 Name3 Name4
You didnt read the whole first line when you did myFile >> n. So the first getline just read the rest of that line, which is empty Do myFile >> n; getline(myFile, line); // read rest of line or getline(myFile, line); // read whole line n = stoi(line); // convert to int
71,879,059
71,886,748
fstream doesn't read the input Visual Studio Code but it works in Visual Studio Community
The code below works properly in Visual Studio Community 2019, the input file opens and gets read. When I try the same code in Visual Studio Code, it doesn't work, and returns "access denied". I need to use Visual Studio Code. The input file is in the .exe's directory in case of Visual Studio Code, and in the .cpp's directory in case of VS Community. VS Community Screenshot: VS Code Screenshot: #include <iostream> #include <fstream> #include <string> using namespace std; int main() { fstream file; string word; file.open("input.txt"); getline(file, word); if (file.is_open() == true) cout << "access aproval" << endl; else cout << "access denied" << endl; cout << word << endl; }
Try to give the full location of the file. file.open("C\..\input.txt");
71,879,337
72,507,796
Difference between calculating in line or two lines
Here is my code in C++. I'm using g++-11 with gcc version 11.2.0. #include<iostream> #include<vector> #include<algorithm> #include<cmath> #include<map> using namespace std; int main() { string t="90071992547409929007199254740993"; //separateNumbers(t); unsigned long long stringNum=0; for (int j=16;j<32;j++) { stringNum += (t[j]-'0')*pow(10,32-j-1); } cout << stringNum; return 0; } This simple code, which I expected to get the last 16 digits as a number, gives 9929007199254740992, not 9929007199254740993. However, the change of code #include<iostream> #include<vector> #include<algorithm> #include<cmath> #include<map> using namespace std; int main() { string t="90071992547409929007199254740993"; //separateNumbers(t); unsigned long long stringNum=0; for (int j=16;j<32;j++) { unsigned long long temp = (t[j]-'0')*pow(10,32-j-1); stringNum += temp; } cout << stringNum; return 0; } gives the desired result, 9007199254740993. How can we explain such a difference between two codes?
As mentioned in @PaulMcKenzie's comment, the source of the difference is mixing floating-point arithmetics with integers. Some more info for those who are interested: The difference manifests in the last iteration of your loop. In the first case, you have: stringNum += (t[j]-'0')*pow(10,32-j-1); which is equivalent to: stringNum = stringNum + (t[j]-'0')*pow(10,32-j-1); pow returns a double, and so the expresion (t[j]-'0')*pow(10,32-j-1) will be of type double, as well as: stringNum + (t[j]-'0')*pow(10,32-j-1). The value you expect (9007199254740993) cannot be represented in a double. The closest value is: 9007199254740992. When assigned back to integer stringNum it stays 9007199254740992. You can see more about this issue here: Is floating point math broken?. You can also see this easily if you try the following lines (your compiler will also give a warning about the possible loss of precision): double d = 9007199254740993; std::cout.precision(17); std::cout << d << std::endl; Which prints: 9007199254740992. In the second case you assign the value for the last digit to temp: unsigned long long temp = (t[j]-'0')*pow(10,32-j-1); (t[j]-'0')*pow(10,32-j-1) is a double with value 3, which incidently can be represented in a double. Then it gets assigned into an integer temp which is also 3. When you execute: stringNum += temp; You use integer arithmetic and get the correct result: 9007199254740993.
71,879,408
71,886,825
Persistent storage in Lambda C++
I am wanting to create a lambda that can store intermediate data between calls. Is this something that is possible? I never hit the Tokens Persisted even after the Storing Tokens is printed. auto process = [&in, &out, callback, tokens = std::deque<O>{}]() mutable { // Debug this is never reached if (!tokens.empty()) { printf("Tokens Persisted: %u\n",token.size()); } // Populate with new tokens if(tokens.empty() && in.ReadValid()) { auto new_tokens = callback(in.Read()); tokens.insert(tokens.begin(), new_tokens.begin(), new_tokens.end()); } // Drain the tokens while (!tokens.empty() && out.WriteValid()) { out.Write(tokens.front()); tokens.pop_front(); } // Debug should be hit if we couldn't all write tokens out if (!tokens.empty()) { printf("Storing Tokens %u\n", tokens.size()); } };
I achieved what I wanted by creating a shared_ptr and passing that into the process lambda. This allows each creation of process to have a unique buffer that it can store results in case of back pressure from the out. auto t = std::make_shared<std::deque<O>>(); auto process = [&in, &out, callback, tokens = t]() mutable { // Debug this is never reached if (!tokens->empty()) { printf("Tokens Persisted: %u\n",token->size()); } // Populate with new tokens if(tokens->empty() && in.ReadValid()) { auto new_tokens = callback(in.Read()); tokens->insert(tokens->begin(), new_tokens.begin(), new_tokens.end()); } // Drain the tokens while (!tokens->empty() && out.WriteValid()) { out.Write(tokens->front()); tokens->pop_front(); } // Debug should be hit if we couldn't all write tokens out if (!tokens->empty()) { printf("Storing Tokens %u\n", tokens->size()); } };
71,879,753
71,898,152
MacOS LLDB | Thread 1: EXC_BAD_ACCESS (code=1 & 2, address=0x123456789)
So to start, I am not too knowledageble in C++, I know very little from a class I took a while back. Almost everything I have so far is from this very generous and knowledgable community. I have to use a wack piece of custom software for work on MacOS and it doesn't have any form autosave and it occasionally likes to crash. Though I regularly save, its annoying loosing any amount of work because it crashes. What I am trying to do is use the save function address to save and repeat every 5 or so minutes. So far I have the process id, the runtime base memory address for the process, the offset of the save function address(I have subtracted the disassembler base address from the address I found with debugging and disassembling), and the arguments it requires. When I try to run the save function I get the lldb error Thread 1: EXC_BAD_ACCESS (code=1, address=0x10a106ecf) and sometimes it changes to Thread 1: EXC_BAD_ACCESS (code=2, address=0x10a106ecf). I have found other questions about this error on this website, but it either doesn't apply to my situation, or due to my limited knowledge I just don't understand how to solve it for my case. If anyone could explain in detail what I am doing wrong in detail along with a solution, it would be much appreciated because I would like to get an understanding and learn. The project is a Command Line Utility in Xcode. I'm not sure if it would need to be a .dylib and added into the process, but if it could be an external command line utility, that would be more optimal for me. Here is the problem code: mach_vm_address_t runtimeBase = 0; // Base process memory address. Set in the getProc() function mach_vm_address_t funcBase = 0x973ECF; // Function Address from disassembling. (0x100973ECF - 0x100000000 = 0x973ECF) int main() { if (!getProc()) throw std::logic_error("Failed to get Process."); typedef mach_vm_address_t(__cdecl* autoSave)(int saveType, const char* saveMessage); autoSave save = (autoSave)(runtimeBase + funcBase); for(;;) { save(0, "AutoSave");// <-- Error Here: Thread 1: EXC_BAD_ACCESS (code=1/2, address=0x10a106ecf) //sleep(5); //add sleep after I get save to work. } } /* saveType: 0 = Save local. 1 = Save server. saveMessage: Message for history/save log. */ More detail I get from code=1 error is: error: memory read failed for 0x10a106e00 <-- Thread 1: EXC_BAD_ACCESS (code=1, address=0x10a106ecf) And for code=2 is: 0x10a106ecf: addb %al, (%rax) <-- Thread 1: EXC_BAD_ACCESS (code=2, address=0x10a106ecf) 0x10a106ed1: addb %al, (%rax) 0x10a106ed3: addb %al, (%rax) 0x10a106ed5: addb %al, (%rax) 0x10a106ed7: addb %al, (%rax) 0x10a106ed9: addb %al, (%rax) 0x10a106edb: addb %al, (%rax) 0x10a106edd: addb %al, (%rax) 0x10a106edf: addb %al, (%rax) 0x10a106ee1: addb %al, (%rax) 0x10a106ee3: addb %al, (%rax) 0x10a106ee5: addb %al, (%rax) 0x10a106ee7: addb %al, (%rax) 0x10a106ee9: addb %al, (%rax) 0x10a106eeb: addb %al, (%rax) 0x10a106eed: addb %al, (%rax)
With assembly explanations from @Peter Cordes I managed to solve my issue. @Peter Cordes: addb %al, (%rax) is how 00 00 decodes. Crashing there indicates that execution jumped to some memory that's all zeros, perhaps due to overwriting a return address or function pointer. Or if you have any hand-written asm, due to getting something wrong with the stack. @Peter Cordes: The EXC_BAD_ACCESS (code=2, address=0x10a106ecf) is from trying to deref whatever garbage is in RAX, for read+write. The 00 00 garbage machine code decodes as instructions that try to access that "bad pointer". I haven't used LLDB much, or MacOS for development at all, but I'm guessing code=1 vs 2 might be read vs. write. (And I haven't really looked at the details of your question, just wanted to help out by explaining that seeing execution in a whole block of addb %al, (%rax) instructions means you jumped to a region full of zeros; any mem access it attempts is already bogus.) So, as @Peter Cordes said addb %al, (%rax) is how 00 00 decodes. Crashing there indicates that execution jumped to some memory that's all zeros. From this we can infer that when Thread 1: EXC_BAD_ACCESS (code=2, address=0x10a106ecf) happens it is because we jumped to a place in memory that is all zeros. But why are we jumping to a place in memory with all zeros? I am thinking it's because of how MacOS handles memory. Each process has its own memory space, and I was trying to jump to the address 0x10a106e00 in MY OWN process' memory, which does not exist. There are a multitude of resources explain how process memory works on modern OS's, just do a quick google search if you want to learn more. So what we know now is: Thread 1: EXC_BAD_ACCESS (code=1, address=0x10a106ecf) happens because my program fails to read the memory for the specified address. Thread 1: EXC_BAD_ACCESS (code=2, address=0x10a106ecf) happens because we are jumping an invalid place in memory, and for the wrong process. There was also some issues with the code, I was using code better suited for Windows, To create a function based on the memory address I did, typedef mach_vm_address_t(__cdecl* autoSave)(int saveType, const char* saveMessage); autoSave save = (autoSave)(runtimeBase + funcBase); And this is what I'm thinking a better/correct way of creating a function based on the memory address is: int (*autoSave)(int saveType, const char* saveMessage) = (int (*)(int , const char *))(runtimeBase + funcBase); The last thing I did was create a Dylib instead of a Command Line Utility. I did this because it is MUCH easier to access the target process' memory. Though what I am trying to achieve is probably possible through a Command Line Utility(CLU) and attaching to the target process as if the CLU was a debugger or some other method, for me it was much simpler and easier to just create a dylib. If anyone reading this has any questions about my explanation, or want more detailed explanation/example of my solution. Feel free to send me a message or comment. I once again want to thank @Peter Cordes for his explanations. They helped even though they said `I haven't used LLDB much, or MacOS for development at all'. The explanations were still extremely helpful and were explained in an easy to understand way.
71,879,770
71,917,565
Accumulating Doubles Into Bins via intrinsics
I have a vector of observations and an equal length vector of offsets assigning observations to a set of bins. The value of each bin should be the sum of all observations assigned to that bin, and I'm wondering if there's a vectorized method to do the reduction. A naive implementation is below: const int N_OBS = 100`000`000; const int N_BINS = 16; double obs[N_OBS]; // Observations int8_t offsets[N_OBS]; double acc[N_BINS] = {0}; for (int i = 0; i < N_OBS; ++i) { acc[offsets[i]] += obs[i]; // accumulate obs value into its assigned bin } Is this possible using simd/avx intrinsics? Something similar to the above will be run millions of times. I've looked at scatter/gather approaches, but can't seem to figure out a good way to get it done.
Modern CPUs are surprisingly good running your naïve version. On AMD Zen3, I’m getting 48ms for 100M random numbers on input, that’s 18 GB/sec RAM read bandwidth. That’s like 35% of the hard bandwidth limit on my computer (dual-channel DDR4-3200). No SIMD gonna help, I’m afraid. Still, the best version I got is the following. Compile with OpenMP support, the switch depends on your C++ compiler. void computeHistogramScalarOmp( const double* rsi, const int8_t* indices, size_t length, double* rdi ) { // Count of OpenMP threads = CPU cores to use constexpr int ompThreadsCount = 4; // Use independent set of accumulators per thread, otherwise concurrency gonna corrupt data. // Aligning by 64 = cache line, we want to assign cache lines to CPU cores, sharing them is extremely expensive alignas( 64 ) double accumulators[ 16 * ompThreadsCount ]; memset( &accumulators, 0, sizeof( accumulators ) ); // Minimize OMP overhead by dispatching very few large tasks #pragma omp parallel for schedule(static, 1) for( int i = 0; i < ompThreadsCount; i++ ) { // Grab a slice of the output buffer double* const acc = &accumulators[ i * 16 ]; // Compute a slice of the source data for this thread const size_t first = i * length / ompThreadsCount; const size_t last = ( i + 1 ) * length / ompThreadsCount; // Accumulate into thread-local portion of the buffer for( size_t i = first; i < last; i++ ) { const int8_t idx = indices[ i ]; acc[ idx ] += rsi[ i ]; } } // Reduce 16*N scalars to 16 with a few AVX instructions for( int i = 0; i < 16; i += 4 ) { __m256d v = _mm256_load_pd( &accumulators[ i ] ); for( int j = 1; j < ompThreadsCount; j++ ) { __m256d v2 = _mm256_load_pd( &accumulators[ i + j * 16 ] ); v = _mm256_add_pd( v, v2 ); } _mm256_storeu_pd( rdi + i, v ); } } The above version results in 20.5ms time, translates to 88% of RAM bandwidth limit. P.S. I have no idea why the optimal threads count is 4 here, I have 8 cores/16 threads in the CPU. Both lower and higher values decrease the bandwidth. The constant is probably CPU-specific.
71,879,837
71,880,103
A Hugeint object + Hugeint object = garbage value. Huh?
I'm making 2 Hugeint objects with this constructor HugeInt.h public: static const int digits = 30; // maximum digits in a Hugelnt HugeInt( long = 0 ); // conversion/default constructor HugeInt( const string & ); // conversion constructor //addition operator; Hugelnt + Hugelnt HugeInt operator+( const HugeInt & ) const; private: short integer[ digits ]; first I convert my int or string into an integer array HugeInt.cpp HugeInt::HugeInt( long value) { // initialize array to zero for ( int i = 0; i < digits; i++ ) integer[i] = 0; // place digits of argument into array for ( int j = digits - 1; value != 0 && j>= 0; j-- ) { integer[j] = value % 10; value /= 10; } // end for } // end Hugelnt default/conversion constructor // conversion constructor that converts a character string // representing a large integer into a HugeInt object HugeInt::HugeInt( const string &number) { // initialize array to zero for ( int i = 0; i < digits; i++ ) integer[i] = 0; // place digits of argument into array int length = number.size(); for ( int j = digits - length, k = 0; j < digits; j++, k++ ) if ( isdigit( number[ k])) // ensure that character is a digit integer[j] = number[ k ] - '0'; } // end Hugelnt conversion constructor operator+ for HugeInt + HugeInt HugeInt HugeInt::operator+( const HugeInt &op2 ) const { HugeInt temp; // temporary result int carry = 0; for ( int i = digits - 1; i >= 0; i-- ) { temp.integer[i] = integer[i] + op2.integer[i] + carry; // determine whether to carry a 1 if ( temp.integer[i] > 9) { temp.integer[i] %= 10; // reduce to 0-9 carry = 1; } // end if else // no carry carry = 0; } // end for } operator<< to output the HugeInt ostream& operator<<( ostream &output, const HugeInt &num ) { int i; for (i = 0; ( num.integer[i] == 0 ) && ( i <= HugeInt::digits ); i++ ) ;// skip leading zeros if ( i == HugeInt::digits ) output << 0 ; else for (; i < HugeInt::digits; i++ ) output << num.integer[i]; return output; } // end function operator<< in main.cpp it looks like this. HugeInt n3( "9999999999999999999999999999999999" ); HugeInt n4( "1" ); cout <<"n6 = n3 + n4 = " << n3 << " + "<< n4 << " = " << n3+n4 << "\n\n"; But the output become random numbers n6 = n3 + n4 = 9999999999999999999999999999999999 + 1 = 23919128293276100-2095744600-20957446000006832-2095744606848-2095744607519200006000-20957 I add return temp at the end of operator+, the result becomes = 0 if I add return *this, the results become = 9999999999999999999999999999999999 the result should be 10000000000000000000000000000000000 Please help explain this to me, my English is bad so sorry for bad question.
Your major problem is that you hard code maximum number of digits you can deal with to 30 But 9999999999999999999999999999999999 1234567890123456789012345678901234 this string is 34 digits Plus you build the result of the add into 'temp' but do nothing with it added return temp; increased digits to 40 n6 = n3 + n4 = 9999999999999999999999999999999999 + 1 = 10000000000000000000000000000000000
71,880,112
71,880,157
Why c++ no more shows index out of range on giving index for accessing character of a string, which is more than the length of string?
Think C++ Allen B. Downey, chapter 7, section 7.6 A run-time error After reading the excerpt about run time error and index out of range error in c++. I tried to execute the same in my compiler of c++ which is running in vs code. But even on trying positive out of range index as well as negative index. I wasn't getting any error instead getting an unexpected (erronous) character being printed on the console. The code I was trying to run is: int main(); { string user_input = "hello"; char a = user_input[100]; cout << a << endl; return 0; } positive index out of range was giving new line as the output. While negative index out of range (like -100) was each time giving different character on the console. Please explain the correct behaviour of c++ and why current c++ is not working as written in book? Is the book incorrect or it is recent version thing.
When you wrote: char a = user_input[100];//this is undefined behavior The expression user_input[100] leads to undefined behavior because you're going out of range of the std::string. If you want to make sure that you get an error while accessing out of range elements, then you can use std::string::at member function like: user_input.at(100)//this will perform bound checking and throw exception on invalid access Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash. So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program. 1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
71,880,135
71,880,170
How to use lambdas to use std::function with member functions?
I'm trying to move some global functions inside a class. The current code looks like this: struct S{}; void f(S* s, int x, double d){} void g(S* s, int x, double d){} /* ... ...*/ void z(S* s, int x, double d){} int main() { function<void(S*, int, double)> fp; //switch(something) //case 1: fp = f; //case 2: fp = g; //case n: fp = z; } Suppose I wanted to update the code above to something like (this code bellow doesn't compile): #include <iostream> #include <functional> using namespace std; struct S { void f(int x, double d){} void g(int x, double d){} /* ... ...*/ void z(int x, double d){} void method_that_has_some_logic_to_use_the_others_above(int x, double d) { function<void(int, double)> fp; // How do I have to declare here? //switch(something) //case 1: fp = f; // How can achieve something like this using lambdas here? //case 2: fp = g; //case n: fp = z; fp(x, d); } }; int main() { S s; s.method_that_has_some_logic_to_use_the_others_above(10, 5.0); } I've seen some solutions using std::bind but read somewhere to avoid using it and prefer lambdas. I'm using C++17, but I have little experience with lambdas and wasn't able to figure out how to solve it with the examples I've found in other answers.
Member functions require a specific class object to invoke, so you need to do function<void(S*, int, double)> fp = &S::f; fp(this, x, d); Or use lambda to capture a specific class object and invoke its member function internally function<void(int, double)> fp = [this](int x, double d) { this->f(x, d); }; fp(x, d); Demo
71,881,347
71,881,782
Bring nested name into scope in non-member function
I have a struct B that contains the declaration of a type anchor_point as a nested name. How can I bring anchor_point into scope in another function using the using-directive? I basically want to access the type as is without qualifiying it (just like from within a member function). I tried the following (see comments): CODE #include <memory> #include <iostream> struct B { struct anchor_point { int a_; }; int x; int y; }; int main() { // Here's what I want - doesn't compile // using B; // anchor_point ap1{5}; // This gets laborious if there are dozens of types inside of B B::anchor_point ap2{5}; // This is even more laborious using ap_t = B::anchor_point; ap_t ap3{5}; std::cout << ap2.a_ << ", " << ap3.a_ << "\n"; } The example is dumbed down but let's say I have a few dozens of those types declared inside the struct and I don't always want to type B::type, how can I do this?
As you have shown you can do using anchor_point = B::anchor_point; repeated for every relevant member. This has to appear only once in the scope enclosing all your uses of the member that you want to cover. There is no other way, in particular no equivalent to using namespace for namespaces which makes all members visible to unqualified name lookup.
71,882,268
71,882,337
For loop does not work (and Visual Studio gives a warning), why?
I isolated my code to the following test program: #include <iostream> using namespace std; int main() { cout << "Begin" << '\n'; for (unsigned int c = '\200'; c < 256; c++) { cout << c << '\n'; } cout << "End"; return 0; } And the for loop does not run, why? I suspect it has to do with the char sizes, because it works up to '\177' and from '\200' it stops working. It seems like the character literals are treated as octal numbers, but why? And even if that is the case then '\177' is 127 and '\200' is 128 and both are still below 256? The warning Visual Studio 2019 with the default C++ standard gives is: C6294: Ill-defined for-loop: initial condition does not satisfy test. Loop body not executed. Disclaimer: This is based on actual code and I'm trying to understand what it is doing.
Yes, the literals are in octal, but that does not matter. You would still have the problem with hex literals, too. The real problem is that the literals are using the char type, which is either signed or unsigned by default, the C++ standard leaves it up to the compiler implementation to decide which to use (some compilers have options to let the user decide). A signed char has a max value of 127, so anything higher than that will overflow to a negative value, which you are then assigning to an unsigned int, thus yielding a very large value that is > 256.
71,882,752
71,884,790
C++ constexpr std::array of string literals
I've been happily using the following style of constant string literals in my code for awhile, without really understanding how it works: constexpr std::array myStrings = { "one", "two", "three" }; This may seem trivial, but I'm hazy on the details of what is going on under the hood. From my understanding, class template argument deduction (CTAD) is used to construct an array of the appropriate size and element type. My questions would be: What is the element type of the std::array in this case, or is this implementation specific? Looking at the debugger (I'm using Microsoft C++), the elements are just pointers to non-contiguous locations. Is it safe to declare constexpr arrays of string literals in this way? I could do this instead, but it's not as tidy: const std::array<std::string, 3> myOtherStrings = { "one", "two", "three" };
As user17732522 already noted, the type deduction for your original code produces a const std::array<const char*, 3>. This works, but it's not a C++ std::string, so every use needs to scan for the NUL terminator, and they can't contain embedded NULs. I just wanted to emphasize the suggestion from my comment to use std::string_view. Since std::string inherently relies on run-time memory allocation, you can't use it unless the entirety of the associated code is also constexpr (so no actual strings exist at all at run-time, the compiler computes the final result at compile-time), and that's unlikely to help you here if the goal is to avoid unnecessary runtime work for something that is partially known at compile time (especially if the array gets recreated on each function call; it's not global or static, so it's done many times, not just initialized once before use). That said, if you can rely on C++17, you can split the difference with std::string_view. It's got a very concise literal form (add sv as a prefix to any string literal), and it's fully constexpr, so by doing: // Top of file #include <string_view> // Use one of your choice: using namespace std::literals; // Enables all literals using namespace std::string_view_literals; // Enables sv suffix only using namespace std::literals::string_view_literals; // Enables sv suffix only // Point of use constexpr std::array myStrings = { "one"sv, "two"sv, "three"sv }; you get something that involves no runtime work, has most of the benefits of std::string (knows its own length, can contain embedded NULs, accepted by most string-oriented APIs), and therefore operates more efficiently than a C-style string for the three common ways a function accepts string data: For modern APIs that need to read a string-like thing, they accept std::string_view by value and the overhead is just copying the pointer and length to the function For older APIs that accept const std::string&, it constructs a temporary std::string when you call it, but it can use the constructor that extracts the length from the std::string_view so it doesn't need to prewalk a C-style string with strlen to figure out how much to allocate. For any API that needs a std::string (because it will modify/store its own copy), they're receiving string by value, and you get the same benefit as in #2 (it must be built, but it's built more efficiently). The only case where you do worse by using std::string_views than using std::string is case #2 (where if the std::array contained std::strings, no copies would occur), and you only lose there if you make several such calls; in that scenario, you'd just bite the bullet and use const std::array myStrings = { "one"s, "two"s, "three"s };, paying the minor runtime cost to build real strings in exchange for avoiding copies when passing to old-style APIs taking const std::string&.
71,882,767
71,883,693
Multi-threaded input processing
I am new to using multithreading and I am working on a program that handles mouse movement, it consists of two threads, the main thread gets the input and stores the mouse position in a fixed location and the child thread loops through that location to get the value. So how do I reduce CPU utilization, I am using conditional variables to achieve this, is there a better way to do this? It seems that adding a delay to the subthreads would also work void Engine::InputManager::MouseMove(const MouseMoveEvent& ev) { cur_mouse_ev_.x_ = ev.x_; cur_mouse_ev_.y_ = ev.y_; cv_.notify_all(); } void Engine::InputManager::ProcessInput(MouseMoveEvent* ev) { while (true) { cv_.wait(u_mutex_); float dx = static_cast<float>(ev->x_ - pre_mouse_pos[0]) * 0.25f; float dy = static_cast<float>(ev->y_ - pre_mouse_pos[1]) * 0.25f; g_pGraphicsManager->CameraRotateYaw(dx); pre_mouse_pos[0] = ev->x_; pre_mouse_pos[1] = ev->y_; } }
Using std::condition_variable is a good and efficient way to achieve what you want. However - you implementation has the following issue: std::condition_variable suffers from spurious wakeups. You can read about it here: Spurious wakeup - Wikipedia. The correct way to use a condition variable requires: To add a variable (bool in your case) to hold the "condition" you are waiting for. The variable should be updated under a lock using the mutex. Again under a lock: calling wait in a loop until the variable satisfies the condition you are waiting for. If a spurious wakeup will occur, the loop will ensure getting into the waiting state again. BTW - wait method has an overload that gets a predicate for the condition, and loops for you. You can see some code examples here: Condition variable examples. A minimal sample that demonstrates the flow: #include <thread> #include <mutex> #include <condition_variable> std::mutex mtx; std::condition_variable cond_var; bool ready{ false }; void handler() { { std::unique_lock<std::mutex> lck(mtx); cond_var.wait(lck, []() { return ready; }); // will loop internally to handle spurious wakeups } // Handle data ... } void main() { std::thread t(handler); // Prepare data ... std::this_thread::sleep_for(std::chrono::seconds(3)); { std::unique_lock<std::mutex> lck(mtx); ready = true; } cond_var.notify_all(); t.join(); }
71,882,880
71,900,452
QMainWindow with member QWidget and QLayout crashes on exit, how to fix that?
The following is a single-file QWidget program. //main.cpp #include <QApplication> #include <QMainWindow> #include <QVBoxLayout> #include <QLabel> class MainWindow:public QMainWindow{ QLabel lb; QWidget wgt; QVBoxLayout lout{&wgt}; public: MainWindow(){ lout.addWidget(&lb);//line A setCentralWidget(&wgt); } }; int main(int argc, char *argv[]){ QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); } The program crashes on exit. The function-call trace on crash is system calls QObjectPrivate::deleteChildren() QWidget::~QWidget() QMainWindow::~MainWindow main If line A is removed then there is no crash. I want to figure out what causes the crash, and how to use member QWidget and QLayout without having a crash. Thanks in advance.
While the problem is due to an attempt to free memory that wasn't allocated on the heap I don't think the QMainWindow destructor or a 'double-delete' is the culprit (as suggested elsewhere). As well as deleting its children the QObject destructor will also remove itself from any parent's object hierarchy. In the code shown wgt is a data member of MainWindow meaning wgt's dtor will be invoked before that of the MainWindow instance. Hence, by the time ~MainWindow is invoked wgt is no longer a child and no attempt will be made to free it at that point. So that's not the issue. Instead the real problem is the order in which the data members lb, lout and wgt are declared in the MainWindow class... class MainWindow: public QMainWindow { QLabel lb; QWidget wgt; QVBoxLayout lout{&wgt}; The widget hierarchy is... wgt \_lb and the implicit construction order... lb lout wgt meaning the order in which the dtors is invoked is... wgt lout lb Thus, when wgt destructor is called lb is still a child and wgt will attempt to free it. That's the cause of the problem in this particular case. While it can be solved by allocating the various QObjects on the heap, an alternative solution would be to simply re-order the member declarations within MainWindow to ensure the correct order of construction and destruction... class MainWindow: public QMainWindow { QWidget wgt; QVBoxLayout lout{&wgt}; QLabel lb;
71,883,192
71,883,257
Reading CSV file lines with hex content and convert it to decimal
Here is my CSV file and its contents are in hex. a3 42 fe 9e 89 a3 43 14 9d cd a3 43 1e 02 82 a3 43 23 bd 85 a3 43 39 d5 83 a3 43 3e b9 8d a3 43 3f 44 c0 a3 43 50 c9 49 a3 43 67 29 c8 a3 43 67 43 0d I need only the second-last value and the code to extract that value is this. void getvalues(){ std::ifstream data("mydata1.CSV"); int row_count =0; std::string line; while(std::getline(data,line)) { row_count +=1; std::stringstream lineStream(line); std::string cell; int column_count = 0; while(std::getline(lineStream,cell,' ')) { column_count+=1; if ( column_count == 5){ std::cout << std::dec<< cell[0]<< std::endl; } } } Since I am reading the lines into a string cell, I am unable to do any conversion. At first I tried wrapping the cell with an int but it returns me the ASCII value of the character which is quite obvious and I shouldn't have done that.
If you want to convert a string to an integer, you can use std::stoi, which is included in the string package. By default, you can use stoi as such: int num = std::stoi(cell) However since we want to parse a base 16 hex number, then we need to use it like: int num = std::stoi(cell, 0, 16) Quick article about this: https://www.includehelp.com/stl/convert-hex-string-to-integer-using-stoi-function-in-cpp-stl.aspx
71,883,343
71,887,365
How to write to file in C++
I've tried to write to file in C++ on a mac in different ways and I can't. I've used: int bestScore = 3; QFile data("bestScore.txt"); data.open(QIODevice::WriteOnly); QTextStream out(&data); out << bestScore; data.close(); int bestScore = 3; FILE *out_file = fopen("bestScore.txt", "w"); if (out_file == NULL) { qDebug() << "File not open"; } fprintf(out_file, "%d", bestScore); Can anyone help?
First thing you need to include fstream. Second you declare the name of the file as an variable. You need to open it. #include <iostream> #include <fstream> using namespace std; int main () { ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); return 0; } If this dosen't work try to give the exact location of the file example myfile.open ("/Library/Application/randomfilename/example.txt");
71,883,656
72,577,297
How to add a administrative template in Group policy with C++?
I'm on Windows. Adding a administrative template in Group policy is easy, you just go to the gpo where you want to add the template, then right click, add template. I want to do this with C++, I looked at msdn and I only discovered functions where I can add a new gpo, but I couldn't find a function to add a template. These are the functions: https://learn.microsoft.com/en-us/windows/win32/api/gpedit/nn-gpedit-igrouppolicyobject How can I add an administrative template to Group policy with C++? Maybe I can do it with the registry?
I solved it a long time ago. The only thing the registry does is this: creating/deleting keys. When you use LGPO it actually creates those keys. You can manage registry keys using Windows API. You can also track the changes in the registry using a software or just simply pressing ctrl + f to search for those keys so you can create them in your program.
71,884,084
71,884,171
malloc size modified after changing stored value?
I have a program that uses malloc to allocate a void-typed space for my program the value I pass to malloc is 1 so it should allocate 1 byte. Now I cast the pointer to int and modify it's value to int (eg, 280). I am pretty sure that an int needs 4 bytes of memory to be stored, and I know for a fact that 280 is represented by at least 2 bytes My expectations are that since I only have a pointer of 1 byte size, the whole integer wouldn't fit in that space, I thought that there would be an error or something (there were none) Then I thought that the integer was stored to RAM starting from the pointer start and exceeding the allocated memory, and since I would print the pointer of the allocated memory I should get a value that represents the whole 1st byte of the number (in this case: 24) BUT: When I try to print the value of the pointer the value is still 280 Now what I am thinking is that somehow the program auto-allocates more size for that pointer But I also think that's weird, could anyone explain what is happening here? I would also like to know how to store ONLY the 1st byte of 280. #include <iostream> int main() { void* p = malloc(1); // This should allocate 1 byte *(int*)p = 280; // This should cast p to an integer, dereference it and set value to 280 std::cout << *(int*)p << std::endl; // This prints 280 but I think it should print 24 free(p); } The above is a pseudo-code that should do what a class I made does, instead of sending the whole class I just replaced the constructor, operator=, destructor to their actual code EDIT: I am using mingw32-g++ to compile the application gcc version 6.3.0 (MinGW.org GCC-6.3.0-1)
Malloc only allocates one byte but has no mechanism to avoid that you write on other memory addresses, by writing 4 bytes in the address of p you write the allocalted byte + 3 other consecutive bytes. After that when you deference the pointer you read 4 bytes that are the same ones you just wrote. What you are doing is writing and reading on memory that the program probably isn't using, but this is undefined behaviour and you shouldn't ever do it as it can lead to segmentation faults.
71,884,116
71,884,384
Why does C++ sometimes not identify overloaded operators?
I have been scratching my head at a problem with my program. At lines 4-6, I overload operator== to accept an int and a pair<int,int>. Then I try it at line 9. It works. So then, I try it at line 10, with find(). It... fails. C++ says that it can't find a operator==() overload that accepts an int and a pair<int,int>, even though I defined one. Can someone figure out what I did wrong? Can someone also give me a valid version of my program, that isn't to complicated? The error is message is below: In file included from main.cpp:1: In file included from /nix/store/dlni53myj53kx20pi4yhm7p68lw17b07-gcc-10.3.0/include/c++/10.3.0/x86_64-unknown-linux-gnu/bits/stdc++.h:54: In file included from /nix/store/dlni53myj53kx20pi4yhm7p68lw17b07-gcc-10.3.0/include/c++/10.3.0/ccomplex:39: In file included from /nix/store/dlni53myj53kx20pi4yhm7p68lw17b07-gcc-10.3.0/include/c++/10.3.0/complex:45: In file included from /nix/store/dlni53myj53kx20pi4yhm7p68lw17b07-gcc-10.3.0/include/c++/10.3.0/sstream:38: In file included from /nix/store/dlni53myj53kx20pi4yhm7p68lw17b07-gcc-10.3.0/include/c++/10.3.0/istream:38: In file included from /nix/store/dlni53myj53kx20pi4yhm7p68lw17b07-gcc-10.3.0/include/c++/10.3.0/ios:40: In file included from /nix/store/dlni53myj53kx20pi4yhm7p68lw17b07-gcc-10.3.0/include/c++/10.3.0/bits/char_traits.h:39: In file included from /nix/store/dlni53myj53kx20pi4yhm7p68lw17b07-gcc-10.3.0/include/c++/10.3.0/bits/stl_algobase.h:71: /nix/store/dlni53myj53kx20pi4yhm7p68lw17b07-gcc-10.3.0/include/c++/10.3.0/bits/predefined_ops.h:268:17: error: invalid operands to binary expression ('std::pair<int, int>' and 'const int') { return *__it == _M_value; } It is quite long and goes on for a long time. #include <vector> #include <algorithm> using namespace std; bool operator ==(pair<int,int>x , int y){ return x.second ==y; } int main() { vector<pair<int,int>>a_vector={{1,2},{2,3}}; cout<<(a_vector[0]==a_vector[0].second)<<"\n"; auto found = find(a_vector.begin(),a_vector.end(),a_vector[0].second); }
Then I try it at line 9. It works. Your main can see the overload of operator== you declared but std::find cannot. The only way for std::find to call your operator is through argument-dependent lookup (ADL). However, ADL won't find your operator== because it is not part of the innermost enclosing namespace of std::pair (which is std). I recommend you do: #include <algorithm> #include <iostream> #include <utility> #include <vector> using namespace std; bool secondEqual (pair<int, int> x, int y) { // ^ give it a meaningful name return x.second == y; } int main() { vector<pair<int, int>> avec = {{1, 2}, {2, 3}}; cout << secondEqual(avec[0], avec[0].second) << "\n"; auto found = find_if(avec.begin(), avec.end(), [&](pair<int, int> const& p) { return secondEqual(p, avec[0].second); }); } I don't encourage you to use: #include <bits/stdc++.h>; using namespace std. Edit: As noted by Aconcagua, if you only defined operator== to call it in std::find, a better solution would be: #include <algorithm> #include <utility> #include <vector> using namespace std; int main() { vector<pair<int, int>> avec = {{1, 2}, {2, 3}}; // | avec.begin() + 1 (?) auto found = find_if(avec.begin(), avec.end(), [&](auto const& p) { return p.second == avec[0].second; }); } Also, since we're at it, most probably you want to pass avec.begin() + 1 as std::find's first argument; otherwise std::find will always return you an iterator to avec[0].
71,884,150
71,884,190
Why can't cmd recognize g++
I installed the MinGW Compiler but when I type g++ in cmd, it just tells me that it's not recognized. But it is RECOGNIZED in every IDE/programming app I tried. I'm sorry if this is another not-recognized question, but none of the solutions I found on the Internet worked.
SET PATH=C:\MinGW\bin;%PATH% set the path via cmd (or manually) before running your commands
71,884,636
71,884,827
Forward Declaration using for a template method
Why do I get an error when using a template method with a forward declared class? I don't actually need a definition of this class, only a declaration. Or maybe I have misunderstood how it actually works? Do I really need to include a corresponding .h file of class B? Edited: And why then does forward declaration of class SomeInterface work with static_assert if I actually include "B.h"? I want to achieve forward declaration to use template method without including ".h" files Question after Kevin reply: bar() method is actually needed for a Template Method Pattern, so there will be like a family of namespace Second. The problem is if I include more ".h" files from namespace Second, doesn't it be less optimized? This bar() method will be executed only once at start of the program Example code: // A.cpp #include "A.h" namespace Second { class SomeInterface; class B; } namespace First { class A { public: A() = default; template <typename M> void foo() { static_assert(std::is_base_of<Second::SomeInterface, M>::value, "You need to use SomeInterface or Derived from it"); } void bar() // -- Template Method Pattern { foo<Second::B>(); // -- C2139 'Second::B': an undefined class is not allowed as // an argument to compiler intrinsic type trait '__is_base_of' foo<Second::C>(); foo<Second::D>(); //... } }; } // B.cpp #include "B.h" #include "SomeInerface.h" namespace Second { class B : public SomeInterface { public: B() = default; }; } If I add this to the A.cpp then it will work fine #include "B.h"
Why do I get an error when using a template method with a forward declared class? This is not generally a problem. I don't actually need a definition of this class, only a declaration. Or maybe I have misunderstood how it actually works? There is no general rule that template parameters need to be complete types, but there are specific cases, and yours is one of them. Do I really need to include a corresponding .h file of class B? In this case, yes. And why then does forward declaration work with static_assert? I'm not sure what you mean. The only static_assert in your code is in template method First::A::foo(). You get an error related to that static_assert (though not an assertion failure) when you instantiate the template with a certain template parameter. In what sense, then, do you think the behavior of the static_assert is inconsistent? The basic problem here is that the std::is_base_of template requires its second type argument to be a complete type. This is in its specifications. A class type that is (only) forward-declared, with no definition in scope, is not complete. Therefore, you get an error when you instantiate First::A::foo<Second::B> at a point where no definition of Second::B is in scope. That error is recognized before the assertion can be evaluated, so the static_assert doesn't factor in except as the context of the error.
71,884,726
71,885,159
template class has no acceptable convertion
The following code works fine: struct A { int d; A(int _d) : d(_d) {} }; A operator+(const A& x, const A& y) { return x.d + y.d; } int main() { A x = 6; cout << (x + 4).d << endl; cout << (4 + x).d << endl; } However, if I make A a template class, then it doesn't compile: template<int p> struct A { int d; A(int _d) : d(_d) {} }; template<int p> A<p> operator+(const A<p>& x, const A<p>& y) { return x.d + y.d; } int main() { A<0> x = 6; // OK cout << (x + 4).d << endl; // error: no operator found or there is no acceptable convertion cout << (4 + x).d << endl; // error: no operator found or there is no acceptable convertion } It works when I do explicit convertion A<0>(4) or (A<0>)4, but it's annoying. I would like to know what causes this difference between "normal" and "template" classes, and how can I get implicit convertion working. I'm using MSVC compiler, if that matters.
The problem is that template argument deduction doesn't consider implicit conversions like the one converting constructor that you've provided. From template argument deduction's documentation Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.
71,885,147
71,885,217
Create and fill a 10 bits set from two 8 bits characters
We have 2 characters a and b of 8 bits that we want to encode in a 10 bits set. What we want to do is take the first 8 bits of character a put them in the first 8 bits of the 10 bits set. Then take only the first 2 bits of character b and fill the rest. QUESTION: Do I need to shift the 8 bits in order to concatenate the other 2 ? // Online C++ compiler to run C++ program online #include <iostream> #include <bitset> struct uint10_t { uint16_t value : 10; uint16_t _ : 6; }; uint10_t hash(char a, char b){ uint10_t hashed; // Concatenate 2 bits to the other 8 hashed.value = (a << 8) + (b & 11000000); return hashed; } int main() { uint10_t hashed = hash('a', 'b'); std::bitset<10> newVal = hashed.value; std::cout << newVal << " "<<hashed .value << std::endl; return 0; } Thanks @Scheff's Cat. My cat says Hi
Do I need to shift the 8 bits in order to concatenate the other 2? Yes. The bits of a have to be shifted left to make room for the two bits of b. As there is room needed for two bits a left shift by 2 is appropriate. (Before my recent update, there was a wrong left shift by 8 which I didn't notice. Shame on me.) The bits of b have to be shifted right. The reason is that OP wants to combine the two most significant bits of b with them of a. As these two bits have to appear as least significant bits in the result they have to be shifted to that position. It should be: hashed.value = (a << 2) + ((b & 0xc0) >> 6); or hashed.value = (a << 2) + ((b & 0b11000000) >> 6); As b is of type char (which is signed or unsigned depending on the compiler), it is even better to swap the order of & and >>: hashed.value = (a << 2) + ((b >> 6) & 0x03); or hashed.value = (a << 2) + ((b >> 6) & 0b11); This ensures that any possible sign bit extension is eliminated which may occur if the type char is a signed type in the specific compiler and b has a negative value (i.e. the most significant bit is set and will be replicated in the conversion to int). MCVE on coliru: #include <iostream> #include <bitset> struct uint10_t { uint16_t value : 10; uint16_t _ : 6; }; uint10_t hash(char a, char b){ uint10_t hashed; // Concatenate 2 bits to the other 8 hashed.value = (a << 2) + ((b >> 6) & 0b11); return hashed; } int main() { uint10_t hashed = hash('a', 'b'); std::cout << "a: " << std::bitset<8>('a') << '\n'; std::cout << "b: " << std::bitset<8>('b') << '\n'; std::bitset<10> newVal = hashed.value; std::cout << " " << newVal << " " << hashed.value << std::endl; } Output: a: 01100001 b: 01100010 0110000101 389 One may wonder why the two upper bits of a are not lost although a is of type char which is usually an 8 bit type. The reason is that integral arithmetic operations work at least on int types. Hence, a << 2 involves the implicit conversion of a to int which has at least 16 bit.
71,885,286
71,885,369
is using an integer to store many bool worth the effort?
I was considering ways to reduce memory footprint, and it is constantly mentioned that a bool takes up more memory than it logically needs to, as a byproduct of processor design. it is also sometimes mentioned that one could store several bool within an int. I am wondering if this would actually be more memory efficient? if we have a usecase where we can use a significant portion of 32 (or 64) bool. and we decide to store all of them in a single int. then on the surface we have saved 7 (bits) * 32 (size of int) = 224 (bits) or 28 (bytes) but in order to get each of those bits from the int, we needed to use some method of masking such as: bit shifting the int both directions (int<<x)>>y here we need to load and store x,y which are probably an int, but you could get them smaller depending on the use case masking the int: int & int2 here we also store an additional int, which is stored and loaded even if these aren't stored as variables, and they are defined statically within the code, it still ends up using additional memory, as it will increase the memory footprint of the instructions. as well as the instructions for the masking steps. is there any way to do this that isn't actually worse for memory usage than just taking the hit on 7 wasted bits?
You are describing a text book example of a trade-off. Yes, several bools in one int is hugeley more memory efficient - in itself. Yes, you need to spend code to use that. Yes, for only a few bools (for different values of "few"), the code might take more space than you save. However, you could look at the kind of memory which is used. In some environments, RAM (which is saved by your idea) is much more expensive than ROM (which has to be paid for your idea). Also, the price to pay is mostly paid once for implementation and only paid a fraction for using, especially when the using code is reused, e.g. in loops. Altogether, in case of many bools, you can save more than you pay. The point of actually saving needs to be determined for the special case. On the other hand, you have missed on "currency" on the price-tag for the idea. You not only pay in memory, you also pay in execution time. You focused your question on memory, so I won't elaborate here. But for anything time critical, you should take the longer execution time into conisderation. You might find that saving memory is quite achievable with your idea, but the whole thing gets unbearably slow. Again from the other side, as Eric Postpischil points out in a comment, execution speed can also improve due to cache effects from better memory footprint.
71,885,720
71,885,920
Apparent bug in clang when assigning a r value containing a `std::string` from a constructor
While testing handling of const object members I ran into this apparent bug in clang. The code works in msvc and gcc. However, the bug only appears with non-consts which is certainly the most common use. Am I doing something wrong or is this a real bug? https://godbolt.org/z/Gbxjo19Ez #include <string> #include <memory> struct A { // const std::string s; // Oddly, declaring s const compiles std::string s; constexpr A() = default; constexpr A(A&& rh) = default; constexpr A& operator=(A&& rh) noexcept { std::destroy_at(this); std::construct_at(this, std::move(rh)); return *this; } }; constexpr int foo() { A i0{}; // call ctor // Fails with clang. OK msvc, gcc // construction of subobject of member '_M_local_buf' of union with no active member is not allowed in a constant expression { return ::new((void*)__location) _Tp(std::forward<_Args>(__args)...); } i0 = A{}; // call assign rctor return 42; } int main() { constexpr int i = foo(); return i; } For those interested, here's the full version that turns const objects into first class citizens (usable in vectors, sorting, and such). I really dislike adding getters to maintain immutability. https://godbolt.org/z/hx7f9Krn8
Yes this is a libstdc++ or clang issue: std::string's move constructor cannot be used in a constant expression. The following gives the same error: #include <string> constexpr int f() { std::string a; std::string b(std::move(a)); return 42; } static_assert(f() == 42); https://godbolt.org/z/3xWxYW717 https://en.cppreference.com/w/cpp/compiler_support does not show that clang supports constexpr std::string yet.
71,885,770
71,885,820
C++ memory leak. Valgrind - mismatched delete
I receive objects from Thread #1 - its a 3rd party lib code - my callback called on it. Objects have fixed-length string fields wrapped: typedef struct somestr_t { char * Data; int Len; } somestr_t; I have to create copy of the objects by hand every time, before I can pass it further to my code. So amongst other things I copy these strings too using this helper: inline void CopyStr(somestr_t * dest, somestr_t * src) { if (src->Len == 0) { dest->Len = 0; return; } char* data = new char[src->Len]; memcpy(data, src->Data, src->Len); dest->Data = data; dest->Len = src->Len; } Then somewhere down the road I delete the object and its string fields: if (someobj != nullptr) { if (someobj ->somestr.Len != 0) delete someobj ->somestr.Data; . . . delete someobj ; } When I run valgrind I get these in places where I would expect the strings to be deleted: ==33332== Mismatched free() / delete / delete [] ==33332== at 0x48478DD: operator delete(void*, unsigned long) (vg_replace_malloc.c:935) ==33332== by 0x41B517: cleanup() (Recorder.cpp:86) ==33332== by 0x41BB29: signal_callback(int) (Recorder.cpp:129) ==33332== by 0x4C11DAF: ??? (in /usr/lib64/libc.so.6) ==33332== by 0x4CD14D4: clock_nanosleep@@GLIBC_2.17 (clock_nanosleep.c:48) ==33332== by 0x4CD6086: nanosleep (nanosleep.c:25) ==33332== by 0x4D02DE8: usleep (usleep.c:32) ==33332== by 0x41C3EF: Logger(void*) (LogThreads.h:28) ==33332== by 0x4C5C6C9: start_thread (pthread_create.c:443) ==33332== by 0x4BFC2B3: clone (clone.S:100) ==33332== Address 0xd661260 is 0 bytes inside a block of size 12 alloc'd ==33332== at 0x484622F: operator new[](unsigned long) (vg_replace_malloc.c:640) ==33332== by 0x419E72: CopyStr (CbOverrides.h:23) and summary report: ==34077== HEAP SUMMARY: ==34077== in use at exit: 328,520 bytes in 3,828 blocks ==34077== total heap usage: 124,774 allocs, 120,946 frees, 559,945,294 bytes allocated ==34077== ==34077== LEAK SUMMARY: ==34077== definitely lost: 0 bytes in 0 blocks ==34077== indirectly lost: 0 bytes in 0 blocks ==34077== possibly lost: 0 bytes in 0 blocks ==34077== still reachable: 328,520 bytes in 3,828 blocks ==34077== suppressed: 0 bytes in 0 blocks I never used valgrind (or any c++ tool) before so I am not sure - why mismatch delete is reported? why there are 328K unreleased memory on exit?
char* data = new char[src->Len]; and if (someobj ->somestr.Len != 0) delete someobj ->somestr.Data; That delete should be delete []. Why are there still reachable: 425,333 bytes in 3,860 blocks. Sorry, my crystal ball isn't working. Normally Valgrind does give a hint as to what you need to do ==19283== Rerun with --leak-check=full to see details of leaked memory It's a little bit mean in that after you've done that it will tell you about another option ==21816== Reachable blocks (those to which a pointer was found) are not shown. ==21816== To see them, rerun with: --leak-check=full --show-leak-kinds=all Try those and start working through the non-freed memory.
71,886,042
71,886,761
Is there a higher performing implementation of powf(10,floorf(log10f(x)))
I have a need to truncate a float to the nearest power of 10. For example, 1.1 would truncate to 1.0 and 4.7e3 would truncate to 1e3. I am currently doing it with the seemingly complicated powf(10,floorf(log10f(x))). I am wondering whether there is a better performing (as in faster execution speed) solution? My target CPU architecture is both x86-64 and arm64. #include <stdio.h> #include <math.h> int main() { float x = 1.1e5f; while (x > 1e-6f) { float y = powf(10,floorf(log10f(x))); printf("%e ==> %g\n", x, y); x /= 5.0f; } } when run, this produces 1.100000e+05 ==> 100000 2.200000e+04 ==> 10000 4.400000e+03 ==> 1000 8.800000e+02 ==> 100 1.760000e+02 ==> 100 3.520000e+01 ==> 10 7.040000e+00 ==> 1 1.408000e+00 ==> 1 2.816000e-01 ==> 0.1 5.632000e-02 ==> 0.01 1.126400e-02 ==> 0.01 2.252800e-03 ==> 0.001 4.505600e-04 ==> 0.0001 9.011199e-05 ==> 1e-05 1.802240e-05 ==> 1e-05 3.604480e-06 ==> 1e-06
It is possible to use a lookup table to speed up the computation. This technique should work for all normal floating point numbers. Subnormal numbers and NaN won't work without some dedicated logic, 0 and infinity can be handled by extreme values in the table. Although I expect this technique to be actually faster than original implementation, measurements are needed. The code uses C++20 std::bit_cast to extract the exponent from the float value. If not available, other older techniques like frexpf exist. #include <bit> #include <cstdint> #include <cstdio> #include <limits> constexpr float magnitudeLUT[] = { 0.f, 1e-38f, 1e-38f, 1e-38f, 1e-38f, 1e-37f, 1e-37f, 1e-37f, 1e-36f, 1e-36f, 1e-36f, 1e-35f, 1e-35f, 1e-35f, 1e-35f, 1e-34f, 1e-34f, 1e-34f, 1e-33f, 1e-33f, 1e-33f, 1e-32f, 1e-32f, 1e-32f, 1e-32f, 1e-31f, 1e-31f, 1e-31f, 1e-30f, 1e-30f, 1e-30f, 1e-29f, 1e-29f, 1e-29f, 1e-28f, 1e-28f, 1e-28f, 1e-28f, 1e-27f, 1e-27f, 1e-27f, 1e-26f, 1e-26f, 1e-26f, 1e-25f, 1e-25f, 1e-25f, 1e-25f, 1e-24f, 1e-24f, 1e-24f, 1e-23f, 1e-23f, 1e-23f, 1e-22f, 1e-22f, 1e-22f, 1e-22f, 1e-21f, 1e-21f, 1e-21f, 1e-20f, 1e-20f, 1e-20f, 1e-19f, 1e-19f, 1e-19f, 1e-19f, 1e-18f, 1e-18f, 1e-18f, 1e-17f, 1e-17f, 1e-17f, 1e-16f, 1e-16f, 1e-16f, 1e-16f, 1e-15f, 1e-15f, 1e-15f, 1e-14f, 1e-14f, 1e-14f, 1e-13f, 1e-13f, 1e-13f, 1e-13f, 1e-12f, 1e-12f, 1e-12f, 1e-11f, 1e-11f, 1e-11f, 1e-10f, 1e-10f, 1e-10f, 1e-10f, 1e-09f, 1e-09f, 1e-09f, 1e-08f, 1e-08f, 1e-08f, 1e-07f, 1e-07f, 1e-07f, 1e-07f, 1e-06f, 1e-06f, 1e-06f, 1e-05f, 1e-05f, 1e-05f, 1e-04f, 1e-04f, 1e-04f, 1e-04f, 1e-03f, 1e-03f, 1e-03f, 1e-02f, 1e-02f, 1e-02f, 1e-01f, 1e-01f, 1e-01f, 1e+00f, 1e+00f, 1e+00f, 1e+00f, 1e+01f, 1e+01f, 1e+01f, 1e+02f, 1e+02f, 1e+02f, 1e+03f, 1e+03f, 1e+03f, 1e+03f, 1e+04f, 1e+04f, 1e+04f, 1e+05f, 1e+05f, 1e+05f, 1e+06f, 1e+06f, 1e+06f, 1e+06f, 1e+07f, 1e+07f, 1e+07f, 1e+08f, 1e+08f, 1e+08f, 1e+09f, 1e+09f, 1e+09f, 1e+09f, 1e+10f, 1e+10f, 1e+10f, 1e+11f, 1e+11f, 1e+11f, 1e+12f, 1e+12f, 1e+12f, 1e+12f, 1e+13f, 1e+13f, 1e+13f, 1e+14f, 1e+14f, 1e+14f, 1e+15f, 1e+15f, 1e+15f, 1e+15f, 1e+16f, 1e+16f, 1e+16f, 1e+17f, 1e+17f, 1e+17f, 1e+18f, 1e+18f, 1e+18f, 1e+18f, 1e+19f, 1e+19f, 1e+19f, 1e+20f, 1e+20f, 1e+20f, 1e+21f, 1e+21f, 1e+21f, 1e+21f, 1e+22f, 1e+22f, 1e+22f, 1e+23f, 1e+23f, 1e+23f, 1e+24f, 1e+24f, 1e+24f, 1e+24f, 1e+25f, 1e+25f, 1e+25f, 1e+26f, 1e+26f, 1e+26f, 1e+27f, 1e+27f, 1e+27f, 1e+27f, 1e+28f, 1e+28f, 1e+28f, 1e+29f, 1e+29f, 1e+29f, 1e+30f, 1e+30f, 1e+30f, 1e+31f, 1e+31f, 1e+31f, 1e+31f, 1e+32f, 1e+32f, 1e+32f, 1e+33f, 1e+33f, 1e+33f, 1e+34f, 1e+34f, 1e+34f, 1e+34f, 1e+35f, 1e+35f, 1e+35f, 1e+36f, 1e+36f, 1e+36f, 1e+37f, 1e+37f, 1e+37f, 1e+37f, 1e+38f, 1e+38f, std::numeric_limits<float>::infinity() }; float decimalMagnitude(float val) { uint32_t intVal = std::bit_cast<uint32_t>(val); uint8_t exponent = intVal >> 23; if (val >= magnitudeLUT[exponent + 1]) return magnitudeLUT[exponent + 1]; else return magnitudeLUT[exponent]; } int main() { for (float v = 1e-38f; v < 1e38f; v *= 1.78) printf("%e => %e\n", v, decimalMagnitude(v)); }
71,886,160
71,886,291
How to use classes prototypes in C++?
I study C ++, I am also not strong in it, so do not judge strictly, played with classes, and decided to make 2 classes so that you can try their prototypes, to which I received in response, in the 1st case, not a complete description of the class, and in the second There is no access to the fields and in general to class. I watched the lesson on the OOP, and there the person worked this code, I decided to try myself what I was surprised, and I don't even know what to do who can explain why and how, I will be happy to hear. thanks in advance. class human; class apple { private: int weight; string color; public: apple(const int weight, const string color) { this->weight = weight; this->color = color; } friend void human::take_apple(apple& app); }; class human { public: void take_apple(apple& app) {}; }; Error: Incomplete type 'human' named in nested name specifer. class apple; class human { public: void take_apple(apple& app) { cout << app.color << '\n'; }; }; class apple { private: int weight; string color; public: apple(const int weight, const string color) { this->weight = weight; this->color = color; } friend void human::take_apple(apple& app); }; Error: Member access into incomplete type 'apple'.
Before befriending a member function, there must be a declaration for that member function in the respective class(which is human in this case). To solve this you can declare the member function before and the define it afterward the class apple's definition as shown below: class apple; //friend declaration for apple class human { public: void take_apple(apple& app);//this is a declaration for the member function }; class apple { private: int weight; std::string color; public: apple(const int weight, const std::string color) { this->weight = weight; this->color = color; } friend void human::take_apple(apple& app); }; //this is the definition of the member function void human::take_apple(apple& app) {}; Working demo Note: In case you want to put the implementation of member function take_apple inside a header file make sure that you use the keyword inline.
71,886,342
71,886,391
How to separate a two digit hexadecimal number into its digits?
Suppose I have a hexadecimal number 4e. How to get 4 and e separately and store it in two separate variables?
if you mean 'how can I get the upper and lower nibbles of a byte into two variables' char x = 0x4e; int low = x & 0x0f; int high = (x & 0xf0) >> 4;
71,886,441
71,888,951
(C++) How to write a clone method for a class which has a unique pointer as a data member?
I have the following set up: class Base { private: // data members public: // methods // pure virtual methods virtual Base* clone() const =0; } class Derived : public Base{ private: // more data members public: // more methods // pure virtual methods overridden Derived* clone() const override{ return new Derived(*this); } I now want to introduce a new derived class which, in the context of a decorator pattern, has a unique pointer to a Base class object as a data member. My question is then how to properly implement the clone() method because the "standard" implementation leads to a compile time error as the unique pointer can't be copied: class DecoratedDerived : public Base{ private: unique_ptr<Base> ptr; // more data members public: // more methods // pure virtual methods overridden DecoratedDerived* clone() const override{ return new DecoratedDerived(*this); // compiler error } One solution would be to just construct a new DecoratedDerived class object in the clone method (by explicitly deep copying all the members associated to the current object) and then passing a pointer to this. However this is quite time consuming if the class has a lot of other members. I should also say that I am only using a unique pointer because this seems the standard smart pointer to use in modern C++. In particular before I used C+11 I had just designed my own smart pointer which took care of all the memory management etc. so that for that type of smart pointer there would be no issue with the clone method in the decorated class. Thanks in advance for your help!
Simply add a copy constructor to DecoratedDerived that clone()'s the data member, eg: class DecoratedDerived : public Base { private: unique_ptr<Base> ptr; // ... public: DecoratedDerived(const DecoratedDerived &src) : Base(src), ptr(src.ptr ? src.ptr->clone() : nullptr) { } // ... DecoratedDerived* clone() const override{ return new DecoratedDerived(*this); } }; Online Demo
71,886,569
71,886,952
cmake on Mac with ARM M1 is running linker with x86_64 architecture instead of arm64
I am trying to compile glfw from source on Mac with M1 arm64 processor, and while running the linker, cmake strangely is trying to link the project for x86_64 architecture, while the binaries were built for arm64. I clone the project, create build folder named cmake-build-debug, generate build system in it with the Makefile etc. as follows: git clone https://github.com/glfw/glfw.git cd glfw mkdir cmake-build-debug cd cmake-build-debug cmake -S .. -B . -DCMAKE_BUILD_TYPE=Debug -DCMAKE_HOST_SYSTEM_PROCESSOR=arm64 -DCMAKE_SYSTEM_PROCESSOR=arm64 This works fine. But now that I build it with make or cmake --config Debug --build ., the .o binaries are generated perfectly fine, but linker script is incorrectly invoked by cmake with x86_64 target architecture for some reason: -- Could NOT find Doxygen (missing: DOXYGEN_EXECUTABLE) -- Including Cocoa support -- Configuring done -- Generating done -- Build files have been written to: /Users/burkov/Documents/Projects/open-source/glfw/cmake-build-debug [ 47%] Built target glfw Scanning dependencies of target wave [ 50%] Linking C executable wave.app/Contents/MacOS/wave ld: warning: ignoring file CMakeFiles/wave.dir/wave.c.o, building for macOS-x86_64 but attempting to link with file built for unknown-arm64 ld: warning: ignoring file ../src/libglfw3.a, building for macOS-x86_64 but attempting to link with file built for macOS-arm64 Undefined symbols for architecture x86_64: "_main", referenced from: implicit entry/start for main executable ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) make[2]: *** [examples/wave.app/Contents/MacOS/wave] Error 1 make[1]: *** [examples/CMakeFiles/wave.dir/all] Error 2 make: *** [all] Error 2 I look at the failing Makefile in glfw/cmake-build-debug/examples/CMakeFiles/wave.dir/build.make and see the line, where cmake is crashing: cd /Users/me/Documents/Projects/open-source/glfw/cmake-build-debug/examples && $(CMAKE_COMMAND) -E cmake_link_script CMakeFiles/wave.dir/link.txt --verbose=$(VERBOSE) I manually open the file glfw/cmake-build-debug/examples/CMakeFiles/wave.dir/link.txt file and see the following link script code there: /Library/Developer/CommandLineTools/usr/bin/cc -g -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.1.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names CMakeFiles/wave.dir/wave.c.o -o wave.app/Contents/MacOS/wave ../src/libglfw3.a -framework Cocoa -framework IOKit -framework CoreFoundation If I manually execute this line from shell, it successfully builds my binary for arm64 architecture, as expected. But when this link.txt script is automatically invoked with cmake via cmake -E cmake_link_script CMakeFiles/wave.dir/link.txt --verbose=$(VERBOSE), it fails, apparently, trying to build the binary for the wrong x86_64 architecture. Why is this happening and how to fix this?
For anyone running into the same problem, it looks like the first version of cmake with an adequate support for Apple Silicon is 3.19. I was using 3.17.5 as my slightly out-of-date version of CLion does not support versions of cmake above that. After an update to cmake 3.22.4 the problem is gone.
71,886,576
71,887,705
why can CMake Build files not be generated correctly
I am trying a simple test to see if CMake is working on my windows system correctly. I keep getting a error. Here is the command with the error. cmake . -- Selecting Windows SDK version 10.0.19041.0 to target Windows 10.0.19044. -- Configuring done CMake Error at CMakeLists.txt:5 (add_executable): No SOURCES given to target: main.cpp CMake Generate step failed. Build files cannot be regenerated correctly. code for file named main.cpp #include <iostream> int main() { std::cout << "hello world\n" << "this is a test" <<std::endl; } and my CMake file cmake_minimum_required(VERSION 3.10) project(test) add_executable(main.cpp) I have used CMake in Linux before so not sure why this is failed. I used Microsoft package manager to install it. I am using the command line for this, i tried the GUI it also failed. I have also deleted the CMake files and cache multiple times. I have not been able to find anything online.
Can't add a comment since my reputation is too low, so I will write an answer instead. In the last line of your CMakeLists.txt file add_executable(main.cpp) you are missing the name of the executable add_executable(name_exe main.cpp) CMake is telling you that in the error message. CMake tries to create a target main.cpp without source files, since CMake suggests the name of the executable at the first place in the command add_executable().
71,886,827
71,887,466
Is it ok that with fp:fast 3000.f/1000.f != 3.f?
I'm using MSVC 2019 v16.11.12. When I tried compiling my code with /fp:fast instead of /fp:precise, my tests started failing. The simplest case is: BOOST_AUTO_TEST_CASE(test_division) { float v = 3000.f; BOOST_TEST((v / 1000.f) == 3.f); } Failing with result: error: in "test_division": check (v / 1000.f) == 3.f has failed [3.00000024 != 3] I understand that /fp:fast can have worse floating-point precision in some cases; but, here, it seems excessive... How come it can't accurately divide 3000 by 1000? I understand that 0.1 + 0.2 is not 0.3, but here all the numbers are representable and the division returns exactly 3 with fp:precise. Is it possible that I have some other flag flipped which decreased the floating-point precision even more?
One of the optimizations which is enabled by gcc's -ffast-math option (and probably msvc's /fp:fast option) is converting a "divide by constant" into a "multiply by reciprocal", as floating point divides are quite slow -- on some machines more than 10x as expensive as a multiply, as multipliers are commonly pipelined while dividers are less commonly pipelined. With this, the / 1000.f would get turned into a * .001 of some precision, and .001 cannot be exactly represented in floating point, so some imprecision will occur. More precisely, the closest 32-bit FP value to .001 is 0x1.0624dep-10, while the closest 64-bit FP is 0x1.0624dd2f1a9fcp-10. If that 32-bit value is multiplied by 3000 you'll get 0x1.80000132p+1 or about 3.0000001425. If you round that to 32 bits, you'll get 0x1.800002p+1 or about 3.0000002384. Interestingly, if you use the 64-bit value and multiply by 3000, you'll get 0x1.800000000000024p+1, which when rounded to 64 bits is the exact 0x1.8p+1 value.
71,887,767
71,887,824
cannot overload functions distinguished by return type alone but it is not a real mistake
I have different variants of some function, that are choosed by preprocessor definition #if defined(V2) bool getAICoord(TTT_Game& game) { // // 4x4 field // return false; } #elif defined(V3) bool getAICoord(TTT_Game& game) { // // renju field // return false; } #else // V1 bool getAICoord(TTT_Game& game) { // some code return false; } #endif And it compiles well, but IntelliSense gives me error cannot overload functions distinguished by return type alone I know, that it is not perfect, but is there any way to exclude this one function from its checklist or something like this?
You could workaround this error by only typing the function signature once and using the preprocessor definitions on the body of the function; e.g. bool getAICoord(TTT_Game& game) { #if defined(V2) // // 4x4 field // return false; #elif defined(V3) // // renju field // return false; #else // V1 // some code return false; #endif }