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,218,664
71,219,422
is it efficient to define random number generator inside function integrator?
Consider an Euler integrator that solves a stochastic differential equation: void euler(vector<double> &x0, vector<double> &dxdt, const double dt) { std::random_device rd; std::mt19937 rng(rd()); std::normal_distribution<> dist(0, 1); f(dxdt, t, dt) for (int i=0; i<x0.size(); ++i) x0[i] += dxdt[i] * dt + sqrt(dt) * 0.01 * dist(rng); } is this efficient to define the random generator for each time step integration? and probably there is a better option? another problem with this method is that when I try to fix the random seed const unsigned int seed = 2; std::mt19937 rng(seed); for each time step, I get the same random numbers and this affects the answer.
Seeding a PRNG if often costly and should usually only be done once during the whole program run so, no, this is not efficient. I suggest that you break the creation of the PRNG out into a separate function that has a static PRNG (only initialized once). std::mt19937& rng() { static std::mt19937 instance{std::random_device{}()}; return instance; } or, if the PRNG is going to be used from multiple threads simultaneously: std::mt19937& rng() { thread_local std::mt19937 instance{std::random_device{}()}; return instance; } You can then use rng() in every function that needs a PRNG: void euler(std::vector<double>& x0, std::vector<double>& dxdt, const double dt) { // Now use rng() instead of rng in here }
71,218,831
71,219,192
Undefined reference to shared object when linking with cmake
I am trying to create a shared object library that I can share with another person without sharing the ".cpp" files and without having to install it in "/usr/". In order to do so, since I am inexpert with cmake, I am starting with a minimal example, but I am having problems when importing the library. I have an ExampleLib with: include/example.h #ifndef EXAMPLE_H #define EXAMPLE_H namespace example { class Example { public: Example(); bool is_working(); }; } #endif src/example.c #include "example.h" namespace example { Example::Example() {}; bool Example::is_working(){ return true; } } CMakeLists.txt cmake_minimum_required(VERSION 2.8.9) project (Example) set(CMAKE_CXX_STANDARD 11) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) add_library(Example SHARED src/example.cpp) I am building it with cmake and make and then I am copying the ".so" and ".h" code to another project, project with the following structure: ExampleCode ├── build ├── include │ └── example.h ├── lib │ └── libExample.so ├── src │ └── main.c └── CMakeLists.txt Where I have the following code: src/main.c #include <iostream> #include "../include/example.h" int main(int argc, char** argv) { example::Example ex; if(ex.is_working()){ std::cout << "It is working. \n"; } } CMakeLists.txt cmake_minimum_required(VERSION 2.8.9) project (testing_example) set(CMAKE_CXX_STANDARD 11) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) add_library(EXAMPLELIB SHARED IMPORTED) set_property(TARGET EXAMPLELIB PROPERTY IMPORTED_LOCATION "lib/libExample.so") add_executable(testing_example src/main.cpp) target_link_libraries(testing_example PRIVATE ${EXAMPLELIB}) But when I try to build it with cmake and make I get the following error: [ 50%] Building CXX object CMakeFiles/testing_example.dir/src/main.cpp.o [100%] Linking CXX executable testing_example /usr/bin/ld: CMakeFiles/testing_example.dir/src/main.cpp.o: in function `main': main.cpp:(.text+0x2a): undefined reference to `example::Example::Example()' /usr/bin/ld: main.cpp:(.text+0x36): undefined reference to `example::Example::is_working()' collect2: error: ld returned 1 exit status make[2]: *** [CMakeFiles/testing_example.dir/build.make:84: testing_example] Error 1 make[1]: *** [CMakeFiles/Makefile2:76: CMakeFiles/testing_example.dir/all] Error 2 make: *** [Makefile:84: all] Error 2 I am pretty sure that my mistake is in the last CMakeLists.txt and I am aware that there are similar questions asked, however, I have not been able to find the solution in this case. Edit: I corrected the CMakeList.txt to use a variable and now I have a different error message: CMakeLists.txt cmake_minimum_required(VERSION 2.8.9) project (testing_example) set(CMAKE_CXX_STANDARD 11) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) add_library(EXAMPLELIB SHARED IMPORTED) set_property(TARGET EXAMPLELIB PROPERTY IMPORTED_LOCATION "lib/libExample.so") add_executable(testing_example src/main.cpp) target_link_libraries(testing_example PRIVATE EXAMPLELIB) outcome make[2]: *** No rule to make target 'lib/libExample.so', needed by 'testing_example'. Stop. make[1]: *** [CMakeFiles/Makefile2:76: CMakeFiles/testing_example.dir/all] Error 2 make: *** [Makefile:84: all] Error 2
The problem was fixed changing ${EXAMPLELIB} -> EXAMPLELIB set_property(TARGET EXAMPLELIB PROPERTY IMPORTED_LOCATION "lib/libExample.so") -> set_property(TARGET EXAMPLELIB PROPERTY IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/lib/libExample.so) As the user @KamilCuk suggested.
71,218,884
71,222,608
Dealing with multiple special opcodes
So I've been working on making a disassembler for Rockstar's scripting engine, and I'm currently dealing with adding all of the opcodes. To give a bit of background, each opcode is a string of bytes, with the first byte being the identifier to which opcode it is, followed by the data that opcode needs. The main problem I'm running into is that there are over 150 opcodes, all with different lengths and all needing different operations done to the following bytes to extract the correct data from them. So I'm mainly just asking for some other peoples opinions, but what would be the best way to handle all 150+ opcodes uniquely? I know I could use a big switch statement, but it would end up being extremely long, and I was thinking there must be a "cleaner" way to do it, I just can't think of one. If anyone has any ideas it would be much appreciated. Thanks!
If you need performance, I would go with the hardcoded table. If design is a big concerned and you can accept some performance lost, you could use the strategy design pattern. For example: class IOpcodeHandlingStrategy { public: virtual ~IOpcodeHandlingStrategy() = default; // Override this for every opcode, to handle it as it needs. virtual void Handle() = 0; }; Then, you implement the interface for each opcode: class OpcodeAHandlingStrategy : public IOpcodeHandlingStrategy { public: OpcodeAHandlingStrategy(const std::string& opcode_) : m_opcode{opcode_} {} void Handle() override { // Use m_opcode and handle it here, for this concrete // opcode... } private: std::string m_opcode; }; With this, the switch statement can be moved inside a factory function, which would only be responsible in creating the right strategy and returning it (using the first byte). Something like: // ... const std::string someOpcode = GetOpcode(); std::unique_ptr<IOpcodeHandlingStrategy> handlingStrategy = CreateOpcodeHandlingStrategy(someOpcode); handlingStrategy->Handle(); // ... What is neat about this solution is that the strategy interface and the factory method completely hide away the details of how opcode are handled to the rest of your application. If you need to change it later, the impact on the rest of the code would be minimal (only the factory and the strategies would be affected, which is where the responsibility lies). This also opens the door to unit testing.
71,220,383
71,234,093
C++: Array of differents types of objects (access to the methods of the child class)
I have created an array of Position which is a parent class of several classes : Player, Item, Mob, and Map. I want to create an array of several types of objects in my Position array (dynamically created object) and then want to use the methods of my objects which are unique. I can't use the virtual type because I would have to write the methods of all my classes and it would be incoherent. So I ask you to try to solve this problem. Map.h : ... static constexpr int mapColonne{14}; static constexpr int mapLigne{6}; Position *positionObject[mapLigne][mapColonne]; ... Map.cpp : ... positionObject[i][j] = new Player("Player1"); positionObject[i][j]->infoPlayer(); ... Error: class "Position" has no member "infoPlayer
You have following options, depending on what do you want to happen if the element doesn't contain the type you think it does: static_cast<Player *>(positionObject[i][j])->infoPlayer(); - undefined behavior on type mismatch. dynamic_cast<Player *>(positionObject[i][j])->infoPlayer(); - cast returns null on type mismatch, which you can check for. If you don't check for null, calling a method on a null pointer might crash. dynamic_cast<Player &>(*positionObject[i][j]).infoPlayer(); - exception on type mismatch. I would use: (3) if I think I know the right type. (1) if I'm absolutely certain I know the type. (2) if I want to check the type first, and do something else if it doesn't match. dynamic_cast is often a sign of bad design. I see no reason to use it here. All your classes should have common methods (declared in base class), such as draw(), update(), etc, which you would call for every object on the board.
71,220,593
71,220,935
What is the reason for "stack smashing detected"?
I am new to programming and am currently studying about address typecasting. I don't seem to understand why I am getting this : *** stack smashing detected ***: terminated Aborted (core dumped) when I run the following code?? #include<iostream> using namespace std; void updateValue(int *p){ *p = 610 % 255; } int main(){ char ch = 'A'; updateValue((int*)&ch); cout << ch; } Here's what I understand about the code: The address of ch is typecasted to int* and passed into the function updateValue(). Now, inside the updateValue() stack, an integer pointer p is created which points to ch. When p is dereferenced, it interprets ch as an int and reads 4(or 8) bytes of contiguous memory instead of 1. So, 'A'(65) along with some garbage value gets assigned to 610%255 i.e. 20. But I don't understand, what and where things are going wrong?
The problem is that you're typecasting a char* to an int* and then dereferencing p which leads to undefined behavior. Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. The program may just crash. 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 which happens in your case. For example, here the program crashes, but here it doesn't 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,221,127
71,221,321
What is the difference between a Technical Report and a Technical Specification?
The terms Technical Specification and Technical Report are used seemingly interchangably when talking about upcoming C++ features (e.g. here or cppreference.com), however I could not find any meaninful distinction or definition of the terms. What is the difference if there even is one?
Quoting The different types of ISO publications: International Standards An International Standard provides rules, guidelines or characteristics for activities or for their results, aimed at achieving the optimum degree of order in a given context. It can take many forms. Apart from product standards, other examples include: test methods, codes of practice, guideline standards and management systems standards. Technical Specification A Technical Specification addresses work still under technical development, or where it is believed that there will be a future, but not immediate, possibility of agreement on an International Standard. A Technical Specification is published for immediate use, but it also provides a means to obtain feedback. The aim is that it will eventually be transformed and republished as an International Standard. Technical Report A Technical Report contains information of a different kind from that of the previous two publications. It may include data obtained from a survey, for example, or from an informative report, or information of the perceived “state of the art”.
71,222,176
71,229,159
fmt Library - Formatting to a (compile-time) string_view
I would like to use the fmt library to create a string_view from my format args. There is plenty documented about passing in a compile-time string as the format string, however, I want to output a compile-time string, so that I may use it in other static parts of my code. Is there a way to do this? So far, all the functions I have seen return a std::string; I also tried format_to, but it seems to be explicitly disabled for a string_view iterator (which I am assuming wouldn't work compile-time anyway, as it's mutating). It may be simple and I'm just looking in the wrong places, I don't know. I would like to be able to do something akin to the following: consteval std::string_view example(unsigned i){ return fmt::something<std::string_view>("You sent {}"sv, i); } So far, this library seems to provide what I need, but, it would be advantageous to avoid a second dependency.
You can do this with format string compilation (FMT_COMPILE): #include <fmt/compile.h> consteval auto example(unsigned i) -> std::array<char, 16> { auto result = std::array<char, 16>(); fmt::format_to(result.data(), FMT_COMPILE("You sent {}"), i); return result; } constexpr auto result = example(42); This gives an array rather than a string_view but you can make one from the other. Godbolt: https://godbolt.org/z/TqoEfTfWs
71,222,185
71,230,635
Boost::Graph-algorithm does not write data with PropertyMap (kamada_kawai_spring_layout, bundled properties)
I have a an adjacency_list graph with randomly connected nodes using Erdos-Renyi edge generation. The graph uses bundled properties by defining data structures both for the vertices (Graph_Node) and edges (Graph_Edge), which is used to assign the position of the nodes and the weights of the edges. I'm trying to use force-directed graph drawing to assign good positions for the nodes, using kamada_kawai_spring_layout. #include <boost/graph/adjacency_list.hpp> #include <boost/graph/erdos_renyi_generator.hpp> #include <boost/random/linear_congruential.hpp> #include <boost/graph/kamada_kawai_spring_layout.hpp> using namespace boost; struct Graph_Node { typedef convex_topology<2>::point tPoint; tPoint Position; }; struct Graph_Edge { unsigned int ID; double weight = 100.; }; typedef adjacency_list<vecS, vecS, undirectedS, Graph_Node, Graph_Edge> Graph; static random::minstd_rand rng; typedef erdos_renyi_iterator<random::minstd_rand, Graph> ERGen; static const int ER_INIT_NODES = 50; static const double p = 0.05; static Graph g(ERGen(rng, ER_INIT_NODES, p), ERGen(), ER_INIT_NODES); int main() { ball_topology<2> T(1.); detail::graph::edge_or_side<1, double> scaling(1.); kamada_kawai_spring_layout(g, get(&Graph_Node::Position, g), get(&Graph_Edge::weight, g), T, scaling); Graph::vertex_iterator v, v_end; for (std::tie(v, v_end) = vertices(g); v != v_end; ++v) std::cout << g[*v].Position[0] << ", " << g[*v].Position[1] << std::endl; } Graph_Node::Position is intended to be assigned using kamada_kawai_spring_layout, but the Position of all the vertices in g are 0,0 after assignment. Why?
The return value of the algorithm: Returns: true if layout was successful or false if a negative weight cycle was detected or the graph is disconnected. When you print it, you'll see that it is false. So, your graph doesn't satisfy the requirements. Raising the edge probability makes for connected graphs: Live On Compiler Explorer #include <boost/graph/adjacency_list.hpp> #include <boost/graph/circle_layout.hpp> #include <boost/graph/erdos_renyi_generator.hpp> #include <boost/graph/graphviz.hpp> #include <boost/graph/kamada_kawai_spring_layout.hpp> #include <boost/random/linear_congruential.hpp> #include <fmt/ranges.h> using tPoint = boost::convex_topology<2>::point; struct Graph_Node { tPoint Position{}; }; struct Graph_Edge { /*unsigned int ID;*/ double weight = 100; }; using Graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, Graph_Node, Graph_Edge>; static constexpr int ER_INIT_NODES = 20; // 50 static constexpr double p = 1; // 0.05 Graph make_graph() { boost::random::minstd_rand rng; using Gen = boost::erdos_renyi_iterator<boost::random::minstd_rand, Graph>; return {Gen(rng, ER_INIT_NODES, p), Gen(), ER_INIT_NODES}; } int main() { auto g = make_graph(); //write_graphviz(std::cout, g); auto print_position = [pos = get(&Graph_Node::Position, g)](size_t v) { fmt::print("Vertex {:3} Position {:9.4f}, {:9.4f}\n", v, pos[v][0], pos[v][1]); }; auto mid_vertex = vertex(ER_INIT_NODES / 2, g); print_position(mid_vertex); boost::circle_graph_layout(g, get(&Graph_Node::Position, g), 25.0); if (true) { // ball-topology print_position(mid_vertex); bool ok = kamada_kawai_spring_layout( // g, // get(&Graph_Node::Position, g), // get(&Graph_Edge::weight, g), // boost::ball_topology<2>(1.), // boost::detail::graph::edge_or_side<true, double>(1.) // ); fmt::print("kamada_kawai_spring_layout ok: {}\n", ok); } else { print_position(mid_vertex); bool ok = kamada_kawai_spring_layout( // g, // get(&Graph_Node::Position, g), // get(&Graph_Edge::weight, g), // boost::square_topology<>(50.0), // boost::side_length(50.0) // ); fmt::print("kamada_kawai_spring_layout ok: {}\n", ok); } print_position(mid_vertex); fmt::print("----\n"); for (auto v : boost::make_iterator_range(vertices(g))) print_position(v); } Prints Vertex 10 Position 0.0000, 0.0000 Vertex 10 Position -25.0000, 0.0000 kamada_kawai_spring_layout ok: true Vertex 10 Position 20.3345, -102.5760 ---- Vertex 0 Position -35.8645, -19.4454 Vertex 1 Position -72.7690, -130.3436 Vertex 2 Position -8.5828, -138.2843 Vertex 3 Position -44.7830, -52.9697 Vertex 4 Position -43.0101, 30.9041 Vertex 5 Position -69.7531, 38.7188 Vertex 6 Position -0.4328, 43.2208 Vertex 7 Position 31.3758, -30.9816 Vertex 8 Position 47.1809, 12.8283 Vertex 9 Position -76.9535, 9.7684 Vertex 10 Position 20.3345, -102.5760 Vertex 11 Position -19.5602, -103.9834 Vertex 12 Position -68.2476, -78.6953 Vertex 13 Position -95.3881, -46.8710 Vertex 14 Position -131.4928, 7.9270 Vertex 15 Position 24.0966, -4.9534 Vertex 16 Position 59.0794, -86.1642 Vertex 17 Position -102.4687, -148.9986 Vertex 18 Position -10.8986, -52.8234 Vertex 19 Position -131.8706, -60.2588
71,222,196
71,237,113
Visual Studio project dependancy question
I have a Visual Studio solution with projects A, B, and C. A and B are indpendant and should do some task T every time they are build. Project C is denendant to A, B and when C is built, task T should be done as well. For any case it's needed task T to be done once. First approach: I tried to trigger task T as pre-build event on projects A and B. That doesn't work when I build C because then A and B are build in parallel and two instances of task T is run in parallel and disturb each other. Second approach: I want to create new project D that will do pre-build event T. It will not have C++ or C# sources, just one script to perform T. Both A and B will be dependant to D. This solves the issue with paralelism but has other problems with Visual studio logic. Visual Studio will build D only when it is outdated but I need it to be run always? Is it possible? When project D is built it should not make A and B outdated. Can you help to resolve these issues with Second approach or maybe there is better solution?
My colleague suggested to add this to vsxproj file: <ItemGroup> <UpToDateCheckInput Include="$(SolutionDir)\a.txt" /> </ItemGroup> It is path to a nonexisting file a.txt. Now it is built every time
71,222,422
71,222,423
How can I auto-format Rust (and C++) code on commit automatically?
I would like to automatically format the code when I do commit using rustfmt the same way as I did it before for clang-format -i. I.e. format only the lines of code which has been updated in the commit without touching other code. How to do it?
It might be done using git pre-commit hook in the following way: Add file pre-commit to the folder .githooks in your repo with the following text: #!/bin/bash exe=$(which rustfmt) if [ -n "$exe" ] then # field separator to the new line IFS=$'\n' for line in $(git status -s) do # if added or modified if [[ $line == A* || $line == M* ]] then # check file extension if [[ $line == *.rs ]] then # format file rustfmt $(pwd)/${line:3} # add changes git add $(pwd)/${line:3} fi fi done else echo "rustfmt was not found" fi Run in your repo folder: chmod +x .githooks/pre-commit git config core.hooksPath .githooks To make it work for clang-format you need to replace rustfmt with clang-format -i and do corresponding modifications in the check for file extension (cpp\h\hpp\etc).
71,223,105
71,223,374
c++ equivalent to python self.attribute = ObjectInstance()
i want to know if there is an equivalent way of doing this in c++: class B: def foo(self,parameter): print("B method call from A, with non static method",parameter) class A: def __init__(self): self.b = B() parameter = 10 a = A() a.b.foo(parameter)
self.b in C++ could be this->b, but also just b as this is implicit in C++. However, in C++, you have to declare (member) variables, while in Python you create them by assigning to them and the type of the variable is determinated by this assignment and can be changed. So next code is similar (not compiled, tested): #include <iostream> class B { public: void foo(int x) { std::cout << x << "\n"; } }; class A { public: B b; } int main() { A a; a.b.foo(3); }
71,223,301
71,223,330
C++20 No more dependent scope needed
I have upgraded to c++20 recently and noticed that the compiler doesnt throw an error when i dont put typename infront of a dependent cope type alias e.g. using iterator = (no typename here) std::vector<int>::iterator Is this now part of the new c++20 standart or is it just a gcc thing and not all compilers do this?
It is a C++20 thing: In some contexts, only type names can validly appear. In these contexts, a dependent qualified name is assumed to name a type and no typename is required: A qualified name that is used as a declaration specifier in the (top-level) decl-specifier-seq of: a simple declaration or function definition at namespace scope; a class member declaration; a parameter declaration in a class member declaration (including friend function declarations), outside of default arguments; a parameter declaration of a declarator for a function or function template whose name is qualified, outside of default arguments; a parameter declaration of a lambda expression outside of default arguments; a parameter declaration of a requires-expression; the type in the declaration of a non-type template parameter; A qualified name that appears in type-id, where the smallest enclosing type-id is: the type in a new expression that does not parenthesize its type; the type-id in an alias declaration; a trailing return type, a default argument of a type template parameter, or the type-id of a static_cast, dynamic_cast, const_cast, or reinterpret_cast. see dependent_name#The_typename_disambiguator_for_dependent_names for more details.
71,223,385
71,223,840
Using a function with a variable number of arguments
Consider the following code: #include <iostream> int var_arg_func(...) { std::cout << "Func called!"; } int main() { var_arg_func(0, 1, 2); } As you can see here I can pass a variable number of arguments to the function var_arg_func. But my question is how can I access those arguments from the function itself? (I'm using C++20)
You can use variadic templates. One example for printing out all the passed argument is given below: #include <iostream> //provide an ordinary function to end recursion void print () { } template<typename T, typename... Types> void print (T firstArg, Types... args) { std::cout << firstArg << "\n"; // printing the very first argument passed print(args...); // printing the rest of the argument by calling print() } int main() { print(1, 2, 3, "some string literal");//call function template print() with arguments `1`, `2`, `3` and `"some string literal"` return 0; } In the above snippet, if we call print() with one or more arguments then the templated version of print will be used/called which just prints the very first argument passed(which is 1 in my example) using cout and then calls print with the remaining arguments(which are 2, 3 and "some string literal. Now the whole process repeats. In particular, the very first argument 2 is printed using cout and then print is called with the remaining arguments(3, "some string literal"). This goes on until there are no more arguments to pass and in this case when print is called with no arguments then the ordinary non-template function print will be used/chosen, thus ending the recursion. The output of the above program can be seen here: 1 2 3 some string literal Note that there are other ways as well like using fold expression(with C++17) to do the same. Also, in the above example, the arguments are passed by value. You can modify the program to pass them by reference according to your needs. With C++17, you can use fold expression: #include <iostream> template<class... Args> void print(const Args&... args) { (std::cout << ... << args) << "\n"; //uses fold expression } int main() { print(1, 2, 3, "some string literal"); return 0; }
71,225,774
71,227,357
segmentation fault when acessing attribute of an smart pointer to class, inside another class
i tried to make this: #include <iostream> #include <memory> class B { public: std::string var; B() { var = "original"; } void print() { std::cout << "composition " << std::endl; } }; class A { public: int a_attribute = 10; std::unique_ptr<B> b; }; int main() { A a; a.b->print(); } That seems to work fine, except when i try to access the attributes of B, with e.g: std::string test = a.b->var; which leads to segmentation fault error why i'm not getting an error to a.b->print(); but getting segfault to a.b->var; ?
You problem is here, in A you have std::unique_ptr<B> b; this creates a smart pointer to a B object. But it there is no B object that it points at. Before you can use it you must create a B object and set 'b' to point at it. I dont know exactly how and when you want to create your B but you can do this A a; a.b = std::make_unique<B>(); a.b->print(); this will create a new B using the default contructor and make 'a.b' point at it. This is more effiecient short hand for A a; B *b1 = new B; a.b.reset(b1); a.b->print(); which explicitly creates a B and then sets a.b to point at it. Note that you do not have to free the B object. Thats the point of smart pointers they will do it for you. You asked why some combinations work and some dont. You had Undefined Behavior. This can do anyting , including worst of all, appearing to work. Then at midnight on Christmas eve your largest customer submits a huge order to your system and it crashes. Every professional dev has had some occurrence of this. Ways to avoid: crank up the compiler warning levels, never ignore warnings. Use a tool like valgrind or other commercial checker tools. For me your original code as posted worked. Why, because the invoked method doesnt actually need any data in the B object. But If I change to this void print() { std::cout << "composition " << std::endl; std::cout << var << std::endl; } it fails because now we are referencing data in the B object, but there isn't one. Note that on a different compiler your original code will not work
71,226,082
71,226,403
ITK image allocation and sysmalloc
I am currently inheriting old code and trying to run it. As part of this there is an image generation done through ITK (which has been built and installed on the system) The (truncated) function causing issue at the moment is the following void PrintDensityImage(std::vector<float> *HU, imageDimensions dimensions, std::string nameFile) { ImageType::Pointer image = ImageType::New(); ImageType::RegionType region; ImageType::IndexType start; start[0] = 0; start[1] = 0; start[2] = 0; ImageType::SizeType size; size[0] = 512;//dimensions.nbVoxel.x; size[1] = 512;//dimensions.nbVoxel.y; size[2] = 8;//dimensions.nbVoxel.z; ImageType::SpacingType inputSpacing; inputSpacing[0] = 0.9;//dimensions.voxelSize.x; inputSpacing[1] = 0.9;//dimensions.voxelSize.y; inputSpacing[2] = 1.1;//dimensions.voxelSize.z; std::cout << inputSpacing << endl; std::cout << size << " " << start << " " << region << endl; region.SetSize(size); region.SetIndex(start); image->SetRegions(region); image->SetSpacing(inputSpacing); printf("I hit here...\n"); std::cout << region << endl; image->Allocate(); printf("But I do not get here\n"); ImageType::IndexType pixelIndex; ......... } And the header includes #include <itkImageFileReader.h> #include <itkImageFileWriter.h> #include <itkHDF5ImageIO.h> #include "itkGDCMImageIO.h" #include "itkGDCMSeriesFileNames.h" #include "itkNumericSeriesFileNames.h" #include "itkImageSeriesReader.h" typedef itk::Image< float, 3 > ImageType; The current console output is [0.9, 0.9, 1.1] [512, 512, 8] [0, 0, 0] ImageRegion (0x7ffd0e7a6910) Dimension: 3 Index: [0, 0, 0] Size: [0, 0, 0] I hit here... ImageRegion (0x7ffd0e7a6910) Dimension: 3 Index: [0, 0, 0] Size: [512, 512, 8] Followed by the error CT_GPUMCD: malloc.c:2379: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed. Aborted (core dumped) I am not certain what is the cause of this error but it seems to spur from the image->Allocate() line which I can't quite grasp why. As far as I can read from the ITK docs (https://itk.org/ITKSoftwareGuide/html/Book1/ITKSoftwareGuide-Book1ch4.html) this should be fine. If there is any insight into the matter I would greatly appreciate it as I really don't see what the issue is here.
The error comes from malloc.c, so from C run-time library. Are you using some experimental or beta version of compiler? Or some modified CRT? Or some software which replaces malloc by their own version (e.g. to track memory leaks)? I doubt this has much to do with ITK. What happens if you replace image->Allocate(); by float * p = new float[512*512*8];? For reference, Allocate is here, which boils down to new T[size].
71,226,137
71,226,232
Does accessing the 4 bytes of a float break C++ aliasing rules
I need to read the binary content of a file and turn the extracted bytes into single precision floating point numbers. How to do this has already been asked here. That question does have proper answers but I'm wondering whether a particular answer is actually valid C++ code. That answer gives the following code: float bytesToFloat(uint8_t *bytes, bool big_endian) { float f; uint8_t *f_ptr = (uint8_t *) &f; if (big_endian) { f_ptr[3] = bytes[0]; f_ptr[2] = bytes[1]; f_ptr[1] = bytes[2]; f_ptr[0] = bytes[3]; } else { f_ptr[3] = bytes[3]; f_ptr[2] = bytes[2]; f_ptr[1] = bytes[1]; f_ptr[0] = bytes[0]; } return f; } Is this actually valid C++ code? I'm not sure whether it violates any aliasing rules. Note that I'm targeting platforms with big endian where a float is guaranteed to be at least 32 bits long.
Is this actually valid C++ code? Potentially yes. It has some pre-conditions: std::uint8_t must be an alias of unsigned char sizeof(float) must be 4 bytes + 3 mustn't overflow a buffer. You can add a checks to ensure safe failure to compile if the first two don't hold: static_assert(std::is_same_v<unsigned char, std::uint8_t>); static_assert(sizeof(float) == 4); I'm not sure whether it violates any aliasing rules. unsigned char is excempted of such restrictions. std::uint8_t, if it is defined, is in practice an alias of unsigned char, in which case the shown program is well defined. Technically that's not guaranteed by the rules, but the above check will handle the theoretical case where that doesn't apply. float is guaranteed to be at least 32 bits long. It must be exactly 32 bits long for the code to work. It must also have exactly the same bit-level format as was on the system where the float was serialised. If it's standard IEE-754 single precision on both ends then you're good; otherwise all bets are off.
71,227,116
71,227,159
Default initialization explicit constructor c++
How does default initialization work in C++11 if the default constructor is explicit? For example: #include <iostream> struct Foo { int x; explicit Foo(int y = 7) : x{y} {} } int main() { Foo foo; std::cout << foo.x << std::endl; } In main, the variable foo is default initialized. Based on my understanding, this will call a default constructor, if one exists. Otherwise, no initialization occurs, foo contains indeterminate values, and printing foo.x is undefined behavior. There is a default constructor for Foo, but it is explicit. Is that constructor guaranteed to be called, or is the last line of the program undefined behavior?
Your use is okay. The worst thing that could happen would be that the compiler would not be able to use the constructor since it is explicit and fail to compile. However, defining a variable as you have will correctly call the explicit default constructor. The use of explicit for a default constructor prevents uses like the following: Foo some_fn() { return {}; // Fails as the default constructor is explicit. return Foo{}; // OK }
71,227,360
71,227,535
CMake Release evaluates bool when compiling, not during execution
I'm working on a multi-threaded project. I am using CMake to compile. I have one file/function that sets a bool to true every so often #include <chrono> void mainloop_click(int *cpm, bool *click, bool *end) { auto start_time = std::chrono::system_clock::now(); while (!*end) { *click = false; while (std::chrono::duration<double>(std::chrono::system_clock::now() - start_time).count() < (60.0 / (double) *cpm)); *click = true; start_time = std::chrono::system_clock::now(); } } My test function that is having problems is void counter(int *count, bool *click, bool *end) { while (!*end) { if (*click) { // TODO Fix Release testing error. This always evaluates to false in release (*count)++; while (*click) {} } } } The basic outline of my test for this is: Start mainloop_click in its own thread Start counter in its own thread, passing the same click pointer. Test if the counter found as many clicks as would be expected for whatever the speed was set to (by cpm) after a set period of time. As far as I can tell, in Debug mode, the compiler actually has the if statement evaluating in the executable, but not when compiled as a Release executable, it automatically evaluates the bool, click, as false (since that's what it is before the thread starts), and doesn't actually check it, but "knows" it's false. Is there anyway to make the Release not do this? I have added print statements, and know that the third line in the test ( With the // TODO ) is where the problem occurs.
Your code contains several errors which results in Undefined Behavior. I'll highlight two in this answer that could explain the behavior you observe. A bool, like most objects, can't be used to communicate between threads without synchronization. You have two threads, one that writes to and one that reads from the same variable, which is a data race. Having a data race means the program has Undefined Behavior. You are not allowed to read from an object that another thread might be simultaneously writing to. The second error is due to the progress guarantee. This guarantee makes it Undefined Behavior to have an infinite loop with no side effects. One possible result of this UB is that the compiler can see that once the thread enters counter it never changes *click, so it can assume that *click remains constant for the duration of the execution. bool is not allowed to be shared between threads without synchronization, so this is a valid assumption on the compiler's part. The compiler could also see that while (*click) {} has no side effects, so it could assume *click is eventually false as the loop may not be infinite. Since the compiler can assume *click is a constant, and *click must eventually be false, it can assume *click is always false. The easiest solution to this problem is to use a std::atomic<bool> instead of a bool. This wraps a bool in a way that makes it shareable between threads. However, it looks like you are using non-synchronized objects for many other inter-thread communication applications. You'll have to address each of these. Multithreading is very difficult to get right, it isn't something that should be learned by trial and error. Consider getting a book on the topic.
71,227,845
71,227,919
C++ inline initialize static function member
I want to implement a member function as follows: void X() {} class Foo { static void(*Bar)() = X; }; This does not compile: error: 'constexpr' needed for in-class initialization of static data member 'void (* Foo::Bar)()' of non-integral type I know this is not legal. I have to either initialize Bar outside of the class scope or make it "inline static". The problem is that the latter is a C++17 feature and I must do with C++11 (BCC32X limitations). So my question is: Is there a way to do this on the same line? Maybe making it const? I know we can do this(Source)... class Foo { static int const i = 42; } But can we apply it to functions somehow? PD: I know there are infinite solutions to my question all over SO, but up until now all I've seen end up relying on later C++ features not available to me.
Since C++11 you can use constexpr to initialize static members of non-integral/enumeration types in the class declaration. As @paddy comments below, this makes Bar const so it would only be a viable solution if you don't plan to modify it, what you are not doing in the question's code. [Demo] #include <iostream> // cout void X() { std::cout << "Blah\n"; } struct Foo { static constexpr void(*Bar)() = X; }; int main() { Foo::Bar(); }
71,228,609
71,228,651
How to compare number in a string with length of the string?
I'm new at programming and I'm trying to make a code that checks if a number inside of a string equals to the length of a string. I don't understand why it doesn't work. Can somebody explain what's wrong with my code? #include <iostream> using namespace std; int main() { string str; cin >> str; int length = str.length(); for (int i = 0; i < str.size(); i++) { if (('0'<str[i])&&(str[i]<='9')) { cout<<"the length is: "<<length<<endl; cout<<"the num is: "<<str[i]<<endl; cout<<"the current string is: "<<str<<endl; if (length == str[i]) { cout<<"yes"<<endl; } else { cout<<"no"<<endl; } } } return 0; } Here is an output: aa5aa the length is: 5 the num is: 5 the current string is: aa5aa no
You forgot to parse the value of the character into an actual integer: #include <iostream> using namespace std; int main() { string str; cin >> str; int length = str.length(); int number = 0; for (int i = 0; i < str.size(); i++) { int a = 1; if (('0' < str[i]) && (str[i] <= '9')) { number = str[i] - '0'; cout << "the length is: " << length << endl; cout << "the num is: " << str[i] << endl; cout << "the current string is: " << str << endl; if (length == number) { cout << "yes" << endl; } else { cout << "no" << endl; } } } return 0; } str[i] represents a character, not an integer. The actual numerical code value of character '0' is not the same as the value of the number 0. Also, this is a crude way of converting character digits into integer values, but it does happen in real code in the wild so it's a common enough trick to know.
71,228,700
71,228,740
Storing an unsigned integer in std::any
Can I make ::std::any hold an unsigned integer? Something like: ::std::any a = 4; unsigned int x = ::std::any_cast<unsigned int>(a); results in an ::std::bad_any_cast exception because a actually holds a signed integer.
Yes, just put an unsigned integer in it: ::std::any a = 4u; // or ::std::any a = static_cast<unsigned>(4); https://godbolt.org/z/vzrYnKKe9 I have to caution you. std::any is not a magical tool to convert C++ into a dynamically typed language like python or javascript. Its use cases are very narrow and specific. It's not really meant to be used in user code as a "catch all" type. It's meant as a type safe alternative to void * in low level library code.
71,229,047
71,229,216
returning multiple value in a loop
In my program I try to return two values after performing operations in the "Durchfluss" method. These values should then be displayed in the loop. but when I display them I get 0 for f_ml1 and 170 for f_ml. why do I get 0 for the variable f_ml1? where is the error? This Method has been calling in a loop. class Sensor { float _flowRateTrinkwasser; unsigned int _f_ml; unsigned long _wasserMengeTrinkwasser; float _flowRateReinwasser; unsigned int _f_ml1; unsigned long _wasserMengeReinwasser; public: Sensor( float flowRateTrinkwasser, unsigned int f_ml, unsigned long wasserMengeTrinkwasser, float flowRateReinwasser, unsigned int f_ml1, unsigned long wasserMengeReinwasser) { // Konstruktor _flowRateTrinkwasser = flowRateTrinkwasser; _f_ml = f_ml; _wasserMengeTrinkwasser = wasserMengeTrinkwasser; _flowRateReinwasser = flowRateReinwasser; _f_ml1 = f_ml1; _wasserMengeReinwasser = wasserMengeReinwasser; } Durchfluss() { _flowRateTrinkwasser = 120; // Formel zur Berechnung von Flow Rate _wasserMengeTrinkwasser = 50; _f_ml = _flowRateTrinkwasser + _wasserMengeTrinkwasser ; _flowRateReinwasser = 70; _wasserMengeReinwasser = 40; _f_ml1 = _flowRateReinwasser + _wasserMengeReinwasser; return (_f_ml1, _f_ml); } }; #include "test.h" //Durchflussmessung Variable Trinkwasser// float flowRateTrinkwasser; unsigned int f_ml; unsigned long wasserMengeTrinkwasser; //Durchflussmessung Variable Trinkwasser// //Durchflussmessung Variable Reinwasser// float flowRateReinwasser; unsigned int f_ml1; unsigned long wasserMengeReinwasser; //Durchflussmessung Variable Reinwasser// Sensor sensorOne( flowRateTrinkwasser, f_ml, wasserMengeTrinkwasser, flowRateReinwasser, f_ml1, wasserMengeReinwasser ); // Objekt vom Konstruktor Sensor1 void setup() { Serial.begin(9600); } void loop() { (f_ml1, f_ml) = sensorOne.Durchfluss(); Serial.println(f_ml1); Serial.println(f_ml); delay(1000); }
Frankly, I would add a pair of getter methods and read f_ml1 and f_ml directly from your sensor object: class Sensor { ... public : int get_f_ml1 () { return f_ml1; } int get_f_ml () { return f_ml; } ... } void loop() { sensorOne.Durchfluss(); Serial.println(sensorOne.get_f_ml1()); Serial.println(sensorOne.get_f_ml()); delay(1000); }
71,229,120
71,229,237
Using a std::vector<std::array<T,N>> as a flat contiguous array of T
A std::vector stores its elements contiguously in memory. An std::array<T,N> is just a wrapper around N contiguous T elements, stored directly in the object itself. Hence I am wondering if a std::vector<std::array<T,N>> of size n can also be seen as an array of T of size N*n. Consider the following code (also here): int main() { // init a vector of 10 arrays of 3 elements each std::vector<std::array<int,3>> v(10); // fill it for (int i=0; i<10; ++i) { v[i] = {3*i,3*i+1,3*i+2}; } // take the first array std::array<int,3>* a_ptr = v.data(); // take the first element of the array int* i_ptr = a_ptr->data(); // dereference the pointer for 3*10 elements for (int i=0; i<30; ++i) { std::cout << i_ptr[i] << ','; } return 0; } It appears to work for my setup, but is the code legit or is it undefined behavior? If I were to replace std::array<int,3> with a struct: struct S { int i,j,k; }; std::vector<S> v(10); S* s_ptr = v.data(); int* i_ptr = &S.i; Would it work the same? What would be the alternatives that would not trigger undefined behavior? Context: I have a std::vector<std::array<int,3>> and I want to serialize it to send it over a network.
No, but yes. No, the C++ standard does not let you treat structs with arrays in them, or even structs with uniform elements, packed together as a single contiguous larger array of the base type. Yes, in that enough in world production code requires this to work that no compiler is going to break it from working any time soon. Things to watch out for include packing. Add static asserts that the size of the structs and arrays is what you expect. Also, avoid being fancy with object lifetime or going "backwards" from an index besides the first one; the reachability rules of C++ are slightly more likrly to bite you if you do strange things. Another concern is that these constructs are under somewhat active investigation; the fiasco that std vector cannot be implemented in standard C++, for example, or std::launder and bit_cast. When a real standard way to do what you want develops, switching to it might be a good idea, because the old technique will become less likely to be supported.
71,229,230
71,229,489
C++ Raylib how to detect the side of a rectangle that a circle has collided with
I can use the function CheckCollisionCircleRec(Vector2{ x, y }, radius, paddleRect) to find out simply if my circle has collided with my rectangle, but I want to be able to find out what side of the rectangle my circle has collided with. How would I go about doing this? None of the algorithms I've made are working. Example of my most recent blunder: if (x - radius <= 0 || x + radius >= screenWidth) { speedX *= -1; } else if (y - radius <= 0 || y + radius >= screenHeight) { speedY *= -1; } else if (CheckCollisionCircleRec(Vector2{ x, y }, radius, paddleRect)) { float paddleBottom = paddleRect.y + paddleRect.height; float paddleRight = paddleRect.x + paddleRect.width; if (range(paddleRect.x, paddleRect.x + speedX / 100, x + radius)) { x = paddleRect.x - radius; speedX *= -1; } if (range(paddleRight - speedX / 100, paddleRight, x - radius)) { x = paddleRight + radius; speedX *= -1; }; if (range(paddleRect.y, paddleRect.y + speedY / 100, y + radius)) { y = paddleRect.y - radius; speedY *= -1; } if (range(paddleBottom - speedY / 100, paddleBottom, y - radius)) { y = paddleBottom + radius; speedY *= -1; }; EDIT: Here's the function I used to get the working end result: // px and py are the ball's previous locations // x and y are the ball's current locations void checkCollision(Rectangle rectangle) { int left = rectangle.x; int right = rectangle.x + rectangle.width; int top = rectangle.y; int bottom = rectangle.y + rectangle.height; if (CheckCollisionCircleRec(Vector2{ x, y }, radius, rectangle)) { if (px < left) { speedX = negative(speedX); x = left - radius; } else if (px > right) { speedX = positive(speedX); x = right + radius; } else if (py < top) { speedY = negative(speedY); y = top - radius; } else if (py > bottom) { speedY = positive(speedY); y = bottom + radius; }; }; };
A simply way is to use the PREVIOUS location of your circle. Not sure if you can in your program, but since you have an x and y handy, I'll assume you can have a prevX and prevY. I'll also assume these values represent the CENTER of the circle. Now if (prevX < paddleRect.x), then you likely collided with the left side (not guaranteed, but resolving ambiguities with complete accuracy requires recursively simulating your physics at smaller and smaller timesteps, which is likely unnecessary here). You can also constrain this more tightly with something like if (prevX < paddleRect.x && prevY > paddleRect.y && prevY < paddleRect.y + paddRect.height). There are various constraints you can add depending on how cleanly you want the side to be hit before detecting it. You can add corner hits, etc. The reason for using the previous location is that, if your circle is moving fast enough, then in a single frame it can jump straight into the middle of the rectangle. It's usually necessary to use the previous position to give more specific collision information in the current-location collision
71,229,468
71,229,641
C++ Is there any fast way to detect how many std::vector elements has been updated/modified?
I'm currently implementing a caching system that has a similar API to std::vector, but it has a member function called Flush, which is for transferring elements to somewhere(e.g. hardware, network, etc.). What I want to do is to make the caching system be able to minimize the transfer overhead through flushing, by just transferring the modified elements instead of the entire array, and also the frequency of transfer should be limited because it needs time cost to initiate a transfer. What I've tried to do is to inherit std::vector, then try to find out if there are any interfaces like on_element_modified or on_element_updated for me to use to detect if the user modified any of the elements (via operator[], iterators, or push_back insert remove, etc.) then when flushing, I can just transfer these modified elements, but it looks like std::vector doesn't have such interfaces for me to use. template<typename Ty, typename Allocator = std::allocator<Ty>> class MyFlushableVector : public std::vector { protected: using size_type = typename std::vector::size_type; std::vector<bool> updated; // These imagined functions is what I need void on_element_modified(size_type index) override { updated[index] = true; } void on_new_element() override { updated.push_back(true); } void on_popped_element() override { updated.pop_back(); } void Transfer(Ty *Pointer, size_type count) { // Do some transfer } public: void Flush() { // Minimize the frequency of transfer by finding the updated blocks to transfer. size_type i, first_updated = 0; bool is_modified = false; for (i = 0; i < size(); i++) { if (is_modified == false) { if (updated[i]) { first_updated = i; is_modified = true; } } else { if (!updated[i]) { Transfer(data() + first_updated, i - first_updated); is_modified = false; } } updated[i] = false; } if (is_modified) { Transfer(data() + first_updated, i - first_updated); } } }; As I couldn't find these imagination interfaces to use, I'm now trying to implement a new class that isn't inherited from std::vector but it has the same interfaces as std::vector and I implemented each of them except it doesn't support iterators (because I don't know how to implement an iterator that can detect any write operations to the vector and set the corresponding updated element to true). I'm not sure this is the true way to do it in modern C++.
The short answer to the question that's contained in the title of this question is simply "no", there's nothing like that, neither in vector nor any other C++ library container. If you need to track changes to the values in the container it will be up to you to implement the entire scaffolding that does so. Other than that, the only other thing you appear to be asking, indirectly, is in the last paragraph which I'll address in the rest of my answer: I don't know how to implement an iterator that can detect any write operations to the vector and set the corresponding updated element to true) I am presuming you're asking how to do that. Well, you can use the same approach that already happens to be used in the C++ library by std::ostreambuf_iterator, which you can simply appropriate for your own purposes. std::ostreambuf_iterator<char> iter{std::cout}; *iter++ = 'H'; *iter++ = 'e'; // and so on, for the remainder of "Hello world!", which will get written // to C++ The key factor here is that iterators are not pointers. They are just objects that implement * and several other operators (depending on the requirements of the iterator's declared category). std::ostreambuf_iterator implements the * and the ++ operator that do ...absolutely nothing. They return the iterator itself. Then, std::ostreambuf_iterator also implements the = operator, that takes the char given to it, and writes it to the output stream buffer. So, the expression *iter++ is a big-fat-nothing, it's only there to meet the requirements for this iterator's category, and all the action happens in the = operator overload. *iter++='H'; only actual work that happens is in the invoked operator= overload. Your custom iterator class simply needs to do the same thing: implement an operator Ty and operator=(const Ty&). The former hands over the actual Ty value that your iterator is referencing. The latter assigns a new value to it, and then sets the corresponding modified flag. Your container hands over these iterators, to iterate itself over. The End. Mission accomplished.
71,229,527
71,229,662
Why does a Member initialized list for a default constructor in a composite class not call the member object constructor?
The Member initialized list for a default constructor in a composite class does not call the member object constructor. #include <iostream> struct test{ test(){ std::cout << "defualt is called" << std::endl; } test(int num){ std::cout <<"parameter is called" << std::endl; } }; struct test2{ test a; test2():a(21){} }; int main(){ test2 b(); } Nothing is outputted, but if I change the default constructor in the composite class to a parameterized one then it works as expected #include <iostream> struct test{ test(){ std::cout << "defualt is called" << std::endl; } test(int num){ std::cout <<"parameter is called" << std::endl; } }; struct test2{ test a; test2(int num):a(21){} }; int main(){ test2 b(4); } output is: parameter is called
test2 b(); is a function declaration, not a variable declaration. It declares a function named b that takes no arguments and returns a test2. Either of the following would produce a test2 variable that uses the default constructor: int main(){ test2 b; // No parentheses at all } int main(){ test2 b{}; // Curly braces instead of parentheses }
71,229,574
71,229,642
C++ GetCursorPos always returns NULL
I'm writing a MFC program and I want to get the selected tree item by using HitTest(). Below is part of my code: POINT ptMouse; GetCursorPos(&ptMouse); TRACE("x = %f, y = %f\r\n", ptMouse.x, ptMouse.y); TRACE("Error Code %s\r\n", GetLastError()); m_Tree.ScreenToClient(&ptMouse); TRACE("x = %f, y = %f\r\n", ptMouse.x, ptMouse.y); HTREEITEM hTreeSelected = m_Tree.HitTest(ptMouse, 0); It should return a point and map it to the client window. But all I get is NULL. The TRACE information is as following: Is there anyone can tell me what I'm doing wrong?
The problem is that ptMouse.x is not a float! But %f parses a float. Replace %f with %d and it should print a proper value. For example, this program: #include <Windows.h> #include <cstdio> int main() { POINT p; GetCursorPos(&p); printf("\nx: %f\n", p.x); printf("\nx: %d\n", p.x); return 0; } Gives this output: x: 0.00000 x: 1325 The real value is 1325, of course.
71,229,810
71,229,883
Implementing Delta Time (In Seconds) into Velocity
Using C++, SDL2, and Vulkan, I'm trying to implement delta time into my game movement by multiplying movement speed by delta time like so: velocity += speed * dt; I've got this code below which apparently calculates delta time dt, but I don't really understand much of it and what I need to modify in order to be able to update the velocity by pixels per second. EDIT: SDL_GetTicks() returns the current time by milliseconds. deltaTime = (SDL_GetTicks() - lastTime) * (TARGET_FPS / 1000.f); if (deltaTime > TARGET_DELTATIME) deltaTime = TARGET_DELTATIME; lastTime = SDL_GetTicks(); With a given TARGET_FPS (lets say 60 for now), and a speed of 50 pixels per second, how can I update the velocity correctly?
Never change the velocity, instead let your physics calculations include delta time as a component. In general, multiply by (delta_since_last_frame/arbitrary_constant_you_tune). EDIT* For example: position += velocity * (delta * ARBITRARY_TUNING_CONSTANT); It's tempting to set ARBITRARY_TUNING_CONSTANT to TARGET_FPS/1000.0f, which you can, but set it to whatever lets you set your velocity values to something that feels intuitive to you. Define a sort of base velocity value, for example let's say you want a velocity of 10.0 to represent moving at 50 px per second. Then set arbitrary_constant_you_tune to make this true. (the arbitrary constant is CONSTANT always, just set once during program initialization or config). Also once you really write it in code, use multiplication rather than division (e.g. prefer 0.2 to 1/5) because multiplication is faster to compute. One nuance to this: be aware that the game physics will be slightly different for people at different frame rates if you use delta time in a simple manner like this. For example, maximum jump height will be different, 2 games running side-by-side at different frame rates will show a different course of events, etc. Just be aware of this as you tune your game physics and game logic
71,229,874
71,230,110
With FlatBuffer full reflection get the underlying vector type?
Using the FlatBuffer full reflection Relevant code const reflection::Schema& schema = *reflection::GetSchema( binary_fbs_file.c_str() ); auto root_table = schema.root_table(); auto fields = root_table->fields(); for (size_t = 0; i < fields->size(); i++) { auto field = fields->Get( i ); // 14 is the enum number for vector. if ( field->type()->base_type() == 14 ) { // How do I check the type of the vector here? } } Relevant question in the code but how do I check what's the type of the vector? Is it an int32, double, string?
field->type()->element() Is the type of the vector contents. See reflection.fbs for details on element.
71,230,435
71,231,202
How to fix gcc warning "friend declaration declares a non-template function"
So I have some code here that compiles with gcc, clang, and msvc: #include <cstdio> #include <type_traits> struct c_class; template <class T> struct holder { friend auto adl_lookup(holder<T>); }; template <class C, class T> struct lookup { friend auto adl_lookup(holder<T>) { return holder<C>{}; } }; struct cpp_class : lookup<cpp_class, c_class *> { cpp_class() {} }; int main() { static_assert(std::is_same<holder<cpp_class>, decltype(adl_lookup(holder<c_class *>{}))>{}, "Failed"); } The reason adl_lookup is defined in the lookup class instead of the holder class is so that you can do a "reverse" lookup from c_class to cpp_class when you inherit from the CRTP class lookup<cpp_class, c_class *>. So the friend function can't be moved to the holder class. However, on gcc I get a warning about non template friend function: <source>:9:37: warning: friend declaration 'auto adl_lookup(holder<T>)' declares a non-template function [-Wnon-template-friend] 9 | friend auto adl_lookup(holder<T>); | ^ <source>:9:37: note: (if this is not what you intended, make sure the function template has already been declared and add '<>' after the function name here) If I try to fix this by forward declaring the function and then using <>, it doesnt compile with gcc or msvc(although it does compile with clang): #include <cstdio> #include <type_traits> struct c_class; template <class T> struct holder; template <class T> auto adl_lookup(const holder<T> &); template <class T> struct holder {}; template <class C, class T> struct lookup { friend auto adl_lookup<>(const holder<T> &) { return holder<C>{}; } }; struct cpp_class : lookup<cpp_class, c_class *> { cpp_class() {} }; int main() { static_assert(std::is_same<holder<cpp_class>, decltype(adl_lookup(holder<c_class *>{}))>{}, "Failed"); } Am I using standard-compliant C++ here(in both snippets)? Is there a reason to be concerned about gcc's warning about non-template friend or is it just a false positive that I can safely ignore?
The second snippet is ill-formed, because a friend declaration cannot be a definition of a template specialization. An open clang bug report for accepting this is here. The first one seems valid to me. The warning by GCC is annoying, because defining a non-template function as friend is what you want to do here. Unfortunately I don't think there is any way to indicate in code that this is really what you want to do, but you can disable the warning with -Wno-non-template-friend. According to the documentation it is there for historical reasons, to identify pre-ISO-C++ compatibility issues where the syntax had a different meaning. You should be aware that the ability to use friend injections of this kind to enable stateful metaprogramming may be considered unintended feature of the language and could maybe (I don't know) be restricted at some point in the future, see this question.
71,231,065
71,231,258
How to declare a member variable that is only visible to one class method per class instance?
Is there a way to declare member4 that only visible to Function1 and it is not shared by all instances? class Test { public: void Function1() { ???? int member4 //visble to Function1 (single instance) } void Function2() { static int member3;// visble to Function2 (all instances) } private: int member1; // visble to Function1 and Function2 (single instance) static int member2;//visble to Function1 and Function2 (all instances) };
Your question looks like an XY Problem. Anyway, here are two possible solutions. First, you could wrap the field into a class and declare the method as a friend: class Test { public: // Don't forget to init Data: Test(); void function1(); void function2(); private: class Data; Data *data; }; class Test::Data { int get() { return 42; } friend void Test::function1(); }; void Test::function1() { int secretData = data->get(); } void Test::function2() { // Will not compile: // int secretData = data->get(); } This solution smells. Much better would be to extract the entity that has this secret member into a separate class: class AnotherEntity { public: void function1() { // use secretData here; } private: int secretData; }; class Test : public AnotherEntity { public: void function2(); private: };
71,231,731
71,231,968
Recursively finding all paths in a grid
I am writing a small program that calculates--recursively--all paths to (0,0) on the grid given some walls that need to be avoided. The grid looks something like this: . . . . . . . . . . . | . . | . . . . . . . . . | . . . . . . . . . . - - - . . - - - - . | . . . . . | . . . . . . . . | . | . . . . . . . . . - - . . . . - - - . . . | . . . . | . . . . . | . . . . | . . . . . . . . . . . . | . . . . . . O You must get to the origin without ever increasing distance to the origin in your path. I have written this code to find all paths: int recursive_find_path(unsigned int x, unsigned int y, unsigned int distance, std::vector<std::vector<GRID_STATUS> > blocked_grid){ //if(x>blocked_grid.size()-1 or y>blocked_grid[x].size()-1 or x<0 or y<0 or x+y > distance or blocked_grid[y][x] == GRID_BLOCKED or blocked_grid[y][x] == GRID_TRAVELLED) if(x>blocked_grid.size()-1 or y>blocked_grid[x].size()-1 or x<0 or y<0 or x+y<distance or blocked_grid[y][x] == GRID_BLOCKED){ return 0; } if(blocked_grid[y][x] == GRID_TRAVELLED){ return 0; } if(x==0 and y==0){ return 1; } blocked_grid[y][x] = GRID_TRAVELLED; // set position to 'travelled' on to avoid infinite recursion return recursive_find_path(x-1,y, distance-1,blocked_grid)+recursive_find_path(x,y-1, distance-1, blocked_grid)+recursive_find_path(x+1,y, distance-1, blocked_grid); } NOTE: GRID_TRAVLLED and GRID_BLOCKED are values defined elsewhere in the program but essentially are just tokens to indicate that there is a wall or the point has been travelled on. However, when running, the program outputs that there are zero paths! Admittedly, I am not sure how many paths there are but I can at least count a few thus it can't be zero. Does anyone know what is going wrong here? Thanks in advance edit . . . . . . . . . . . . . . . . . . . X . . X . . . . . . . . . . . . . . . . . X . . . . . . . . . . . . . . . . . . X X X . . X X X X . . . . . . . . . X . . . . . X . . . . . . . . . . . . . . . . X . X . . . . . . . . . . . . . . . . . X X . . . . . . . . . . . . X X X . . . X . . . . . . . . . . . . X . . . . . X . . . . . . . . . . . . X . . . . . . . . . . . . . . . . . . . . X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . X . . . . X . . . . . . . . . . . . . X . . . . . X X X X X X . . . . . . . X . . . . . . . . . . . . . . . . . . X . . . . . . . . . . . . . . . . . . X . . . . . . . . . X S Using this grid, I get an infinite loop.... updated code: if(x>blocked_grid.size()-1 or y>blocked_grid[x].size()-1 or x<0 or y<0 or blocked_grid[y][x] == GRID_BLOCKED){ return 0; } if(x==0 and y==0){ return 1; } return recursive_find_path(x-1,y,blocked_grid)+recursive_find_path(x,y-1, blocked_grid); } after letting it sit for a while it did return 540. I am almost certain there can't be 540 paths in this case
I noticed at: return recursive_find_path(x-1,y, distance-1,blocked_grid)+recursive_find_path(x,y-1, distance-1, blocked_grid)+recursive_find_path(x+1,y, distance-1, blocked_grid); The two points (x + 1, y) and (x - 1, y) cannot both be closer to the origin, yet you pass (distance - 1) to both of those recursive calls. This will cause distance to eventually equal -1 for many paths, which will then return 0, but until they return 0, those paths will be marked as travelled despite being spurious paths that should have been prevented from being travelled. You should only check paths that move closer to the origin, those being (x -1, y) and (x, y - 1)
71,232,149
71,232,518
Inter-process communication (C++ to C#) using Memory mapped file (IOException)
There are two processes: one written in C++ and the other written in C#. Simply, C++ process will create a file name "test.dat", map the file to its memory, and keep on writing on it. C# process on the other hand will open the file and read whenever there is a change on the memory. The problem is that on the C# end, it does not let me open the file. (IOException saying the other process is in use" Here is what I've tested. //C++ // Test create & open void CTestDlg::OnBnClickedBtn1() { WCHAR wcsDebug[1024]; HANDLE hFile, hMapFile; UINT size = sizeof(syncData); hFile = CreateFile(L"C:\\Users\\test\\Documents\\2134\\test.dat", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile != INVALID_HANDLE_VALUE) { hMapFile = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, size, NULL); if (hMapFile) { g_pb = (BYTE*)MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0); } } } // Test Writing void CLibTestDlg::OnBnClickedBtn2() { WCHAR sz[] = L"C:\\Users\\test\\Documents\\2134\\"; WCHAR wcsFilePath[MAX_PATH]; CString str; GetDlgItemText(IDC_EDIT_FID, str); if (str != L"\0") { swprintf_s(wcsFilePath, _countof(wcsFilePath), L"%s%s", sz, str.GetBuffer()); if (g_pb) { syncData sd; sd.dwCurrent = nCurr; sd.dwTotal = 15; sd.eSyncType = TYPE_DOWNLOAD; StringCchCopy(sd.wcsFileName, _countof(sd.wcsFileName), wcsFilePath); sd.eReqType = TYPE_DOWNLOAD; sd.ullTimeStamp = GetTickCount(); nCurr++; memcpy(g_pb, &sd, sizeof(sd)); } } } C# portion below: private void Button_MouseUp(object sender, RoutedEventArgs e) { Console.WriteLine("Click"); FileStream fs = File.Open(@"C:\\Users\\test\\Documents\\2134\\test.dat", FileMode.Open, FileAccess.ReadWrite); // Error Here! IOException: The file is being used by another process. using (var mmf = MemoryMappedFile.CreateFromFile(fs, "mmf", 0, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true)) { using (var accessor = mmf.CreateViewAccessor(0, 544)) { DWORD dwCurrent; accessor.Read(0, out dwCurrent); Console.WriteLine("Hello" + dwCurrent); } } } Any ideas on approaching the file sharing between the two processes?
FileStream defaults to only allowing read sharing which is not compatible with how you've opened your c++ file. You need to request write sharing too: File.Open(@"...", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
71,233,059
71,253,039
`ld` undefined reference error, but libraries are linked to by CMake and symbols exist
I have a CMake file like this: cmake_minimum_required(VERSION 3.12) project(cpp-service VERSION 0.1.0) add_compile_definitions(OPENVDB_7_ABI_COMPATIBLE) list(APPEND CMAKE_MODULE_PATH "/usr/local/lib64/cmake/OpenVDB/") find_package(OpenVDB REQUIRED) ### https://stackoverflow.com/a/69290761/3405291 list(APPEND CMAKE_MODULE_PATH "deps/tbb/cmake/") find_package(TBB REQUIRED) add_executable(${PROJECT_NAME} src/main.cpp ) target_link_libraries(${PROJECT_NAME} PUBLIC OpenVDB::openvdb TBB::tbb ) All the libraries are linked-to by CMake. The symbols are all available. But, linker cannot link find symbols at all. With many errors like this: ... [ 92%] Building CXX object ... [ 96%] Building CXX object ... [100%] Linking CXX executable cpp-service /usr/lib64/gcc/x86_64-suse-linux/7/../../../../x86_64-suse-linux/bin/ld: CMakeFiles/cpp-service.dir/src/main.cpp.o: in function `hollowing::mesh_to_grid(hollowing::Contour const&, openvdb::v7_2::math::Transform const&, float, float, int)': /home/m3/repos/cpp-service/src/hollowing.h:268: undefined reference to `openvdb::v7_2::initialize()' /usr/lib64/gcc/x86_64-suse-linux/7/../../../../x86_64-suse-linux/bin/ld: CMakeFiles/cpp-service.dir/src/main.cpp.o: in function `tbb::task_group_context::task_group_context(tbb::task_group_context::kind_type, unsigned long)': /home/m3/repos/cpp-service/deps/tbb/include/tbb/task.h:499: undefined reference to `tbb::task_group_context::init()' ... Guess One guess is that I'm having this problem: ...It seems that gcc now send the linker flag --as-needed to ld. This has the effect of discarding any specified libraries that do not have symbols that are required for linking. Tried I tried this, but it had no effect. The same link errors are thrown: target_link_options(${PROJECT_NAME} PUBLIC "LINKER:-no-as-needed" ) Question I ran out of options debugging this problem. Does anybody have any suggestion to try out? CMake commands export CC=/usr/bin/gcc-11 export CXX=/usr/bin/g++-11 mkdir build cd build cmake .. cmake --build . --verbose >> log.txt 2>&1 # Save log to file. Compile commands CMake shows the compile logs are like: [ 3%] Building CXX object CMakeFiles/cpp-service.dir/src/main.cpp.o /usr/bin/g++-11 -I/home/m3/repos/cpp-service/deps/tbb/include -I/.../more/include/paths/.../... -g -std=c++17 -MD -MT CMakeFiles/cpp-service.dir/src/main.cpp.o -MF CMakeFiles/cpp-service.dir/src/main.cpp.o.d -o CMakeFiles/cpp-service.dir/src/main.cpp.o -c /home/m3/repos/cpp-service/src/main.cpp Link command CMake log shows the link command is: [100%] Linking CXX executable cpp-service /usr/local/bin/cmake -E cmake_link_script CMakeFiles/cpp-service.dir/link.txt --verbose=1 /usr/bin/g++-11 -g CMakeFiles/cpp-service.dir/src/main.cpp.o CMakeFiles/cpp-service.dir/src/***.cpp.o CMakeFiles/cpp-service.dir/src/***more***object***files***.cpp.o -o cpp-service The errors are thrown exactly right after the above link command. Errors like: undefined reference to `openvdb::v7_2::initialize()' Symbols Symbols are defined inside the linked libraries: nm /usr/local/lib64/libopenvdb.so | less The above command shows the initialize symbol is available:
Fix The cause of the linker errors was this statement: if(LINUX) The fix was to replace it with this: if(UNIX AND NOT APPLE) This commit fixes the problem: Reference: https://stackoverflow.com/a/40152725/3405291 Strangely, CMake wasn't complaining about anything and just throwing random linker errors.
71,233,631
71,234,540
c++ implement of array broadcast
In python language, we can use A[A!=0]=-10 to trans all the non-zero value in A to -10. How can I implement this function in C++ language or is here any similar function in 3rd party? #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <iostream> using namespace std; using namespace cv; int main() { Mat A(3, 3, CV_16SC1); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { A.at<short>(i, j) = i + j; } } for (auto& value : A) if (value != 2) value = -10; }
Range-based for loops will not work since the cv::Mat::begin() is a member function template. You'll have to use begin<mat_type>() and end<mat_type>(). Example: #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <algorithm> #include <iostream> #include <iterator> int main() { cv::Mat A(3, 3, CV_16SC1); using mtype = short; // convenience typedef for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { A.at<mtype>(i, j) = i + j; // using mtype } } // using mtype: for(auto it = A.begin<mtype>(); it != A.end<mtype>(); ++it) { if(*it != 2) *it = -10; } // print result: std::copy(A.begin<mtype>(), A.end<mtype>(), std::ostream_iterator<mtype>(std::cout, "\n")); } Or using the std::replace_if algorithm to replace all non 2's with -10: std::replace_if(A.begin<mtype>(), A.end<mtype>(), // using mtype [](auto& value) { return value != 2; }, -10); Output: -10 -10 2 -10 2 -10 2 -10 -10
71,233,815
71,234,161
MySQL statement is exiting my for loop without finishing the iteration C++
I am working on a project, and I need to push a list to my database. I want to iterate through the said list and execute a statement that adds said list to my table. Running the exact script within MySQL works perfectly fine. However, when I try to iterate through the list and run the script, it does it once before exiting my for loop. It won't even run any code past the executeQuery(). My code is as follows: for (int i = 0; i < addList.size(); i++) { stmt = con->createStatement(); stmt->executeQuery("INSERT INTO comboboxtable (combobox, user, text) VALUES (" + std::to_string(id) + ", \'" + username.toStdString() + "\', \'" + addList[i].toStdString() + "\')"); } I have a driver and connection already established, and everywhere else in my code it seems to execute queries just fine. I also have this code in a try/catch set for catching SQL exceptions, but it isn't throwing anything. I am using the MySQL C++ connector to do this. The size of the loop is fine and everything should be working on the iteration side.
I seem to have figured it out after a bit of digging on the website and found that I needed to use execute() not executeQuery().
71,234,694
71,253,885
Why this include order causes link error on unordered_map?
I had a problem with include order that I cannot explain. I will show you a minimal example with four files: // A.h #pragma once #include <functional> struct A {}; namespace std { template<> class hash<A> { public: size_t operator()(const A&) const { return 0; }; }; } // B.h #pragma once #include <unordered_map> struct A; struct B { const std::unordered_map<A, int>& GetMap() const; }; // B.cpp #include "B.h" #include "A.h" const std::unordered_map<A, int>& B::GetMap() const { static std::unordered_map<A, int> m; return m; } // main.cpp #include "A.h" // To be included AFTER B.h #include "B.h" int main() { B b{}; const auto& m = b.GetMap(); } With this example I get the following error: error LNK2019: unresolved external symbol "public: class std::unordered_map<struct A,int,class std::hash<struct A>,struct std::equal_to<struct A>,class std::allocator<struct std::pair<struct A const ,int> > > const & __cdecl B::GetMap(void)const " (?GetMap@B@@QEBAAEBV?$unordered_map@UA@@HV?$hash@UA@@@std@@U?$equal_to@UA@@@3@V?$allocator@U?$pair@$$CBUA@@H@std@@@3@@std@@XZ) referenced in function main 1>Z:\Shared\sources\Playground\x64\Debug\Playground.exe : fatal error LNK1120: 1 unresolved externals But if in main.cpp I include A.h after B.h, the program compiles successfully. Can someone explain why? It took me a long time to find the problem in real code, there is some method to make me understand easily that the error is related to include order? Edit: I made some other test to investigate the problem. The error occurs also if I change the std::unordered_map<A, int> with std::unordered_set<A> but not with std::map<A, int> and std::set<A>, so I think that there is some problem with the hash. As suggested, including A.h in B.h instead of forward declaring A makes the build succeed without modifying the include order in main.cpp. So I think that the question become: why forward declaring A, and thus having an incomplete type for the key of unordered map, causes the error?
I tested the same code in Visual Studio 2022 and got the same error. After my exploration, I found the problem. Firstly, I copied the contents of A.h and B.h into main.cpp and removed the #include directive. After compiling, I still got the same error. Then I tested and found that as soon as I moved namespace std {...} after the definition of class B, the error went away. I read the assembly code generated by the compiler and found that the names generated for GetMap in main.cpp and b.cpp are different: main.asm: GetMap@B@@QEBAAEBV?$unordered_map@UA@@HV?$hash@UA@@@std@@U?$equal_to@UA@@@3@V?$allocator@U?$pair@$$CBUA@@H@std@@@3@@std@@XZ b.asm: GetMap@B@@QEBAAEBV?$unordered_map@UA@@HU?$hash@UA@@@std@@U?$equal_to@UA@@@3@V?$allocator@U?$pair@$$CBUA@@H@std@@@3@@std@@XZ I looked up MSVC's name mangling rules and found U for struct and V for class. So I change the definition of template<> class hash<A> to template<> struct hash<A>. Then the error disappeared. I think it's legal to use class keyword instead in the specialization, but I can't find a description of this in the standard. However, I think the problem may not be that simple. A key issue here is that the specialization of std::hash in B.cpp appears after the definition of class B, while in main.cpp the order is completely reversed. I think this violates the ODR and should result in undefined behavior. This is also why the program is correct after swapping the order of the header files (making it consistent with the order in B.cpp). I looked up some sources and couldn't find a standard description of the problem: In B.cpp, the declaration of GetMap does not cause unordered_map to be instantiated, but it is instantiated in the function definition. A specialization of std::hash was inserted in the middle of declaration and definition, which could cause unordered_map to see a different definition of std::hash. Can the compiler see this specialization? Should the compiler choose this specialization? If the compiler can see the specialization, why is the primary template used in the generated assembly code? (The compiler-generated name in B.cpp uses "U", which is for struct)
71,235,133
71,235,160
Iterate over two possible types of iterable objects C++
I'd like a program of mine to be flexible and for it to either be able to iterate over a list of files in a directory for which I'm currently using for(const auto& dirEntry : fs::directory_iterator(input_dir)) where fs is filesystem. I'd also like the possibility of iterating over a vector of strings, and to choose between these two different types at runtime. however my best idea so far is to just have two different for loops and choosing the correct one with an if/else statement but that feels like a poor coding choice. Is there any way to generically iterate over one or the other?
You can extract the code with the loop into a template, e.g. template<class Range> void DoWork(Range&& dirEntries) { for (const auto& dirEntry : dirEntries) ; // ... } and then instantiate/call the template with DoWork(fs::directory_iterator(input_dir)); or DoWork(myVectorOfStrings); Note that whatever you do in the loop body must work with whatever element type the range has (std::string, fs::path etc.).
71,235,171
71,236,368
Function with single optional parameter and default value in template function
I want a function with has only 1 argument which is optional with generic type and has assigned boost::none as default value. Is that possible? #include <iostream> #include <string> #include <boost/optional.hpp> template <typename T> void f(boost::optional<T> v = boost::none) { if (v) { std::cout<<"v has value: " << v.get(); } else { std::cout<<"v has no value!"; } } int main() { f(12); f("string"); return 0; }
Mmm the other answer is close. But not quite there. f(12) doesn't "try to instantiate f<int&&>". In fact, it fails to deduce T because T is in non-deduced context. Also, your question was beside the point: even without a default value you have the same problem: Compiler Explorer template <typename T> void f(boost::optional<T> v) { if (v) { std::cout<<"value: " << v.get() << "\n"; } else { std::cout<<"no value\n"; } } int main() { f(12); f("string"); } Now, before I blindly show you how you can fix all that, ask yourself the question: What are we doing here. If you want default arguments, doesn't that by definition mean that they aren't optional values? Maybe you simply need: Compiler Explorer template <typename T> void f(T const& v) { std::cout << "value: " << v << "\n"; } void f() { std::cout << "no value\n"; } int main() { f(12); f("string"); f(); } Printing value: 12 value: string no value With some hackery you can combine the overloads by defaulting the template type argument: template <typename T = struct not_given*> void f(T const& v = {}) { if constexpr(std::is_same_v<T, not_given*>) { std::cout << "no argument\n"; } else { std::cout << "value: " << v << "\n"; } } Prints Compiler Explorer value: 12 value: string no argument What If You Require optional<> In that case, in you specific example you would probably want optional<T const&> to avoid needlessly copying all the arguments; but see std::optional specialization for reference types. If You Really Really Want¹ Say, you MUST have the semantics you were looking for. You do not care that you won't be able to know the difference between calling with no argument vs. calling with an uninitialized optional (none). This is kinda like many scripting languages, right? Now you have to make the template argument become deduced context, and then want to ensure that... it is an optional<T>: template <typename T, typename = void> struct is_optional : std::false_type { }; template <typename T> struct is_optional<boost::optional<T>> : std::true_type { }; template <typename T = boost::optional<void*> > std::enable_if_t<is_optional<T>::value> f(T const& v = {}) { if (v) { std::cout << "value: " << *v << "\n"; } else { std::cout << "no value\n"; } } template <typename T> std::enable_if_t<not is_optional<T>::value> f(T const& v) { return f(boost::make_optional(v)); } int main() { f(12); f("string"); f(); } One "advantage" is that that now you clearly see the copying being done. Another "advantage" is that now you can support std::optional the same way: https://godbolt.org/z/1Mhja83Wo template <typename T> struct is_optional<std::optional<T>> : std::true_type { }; Summary I hope this answer gets the point across that C++ is not a dynamically typed language. This implies that the idea of optional arguments of "unknown" type is really not idiomatic. (It might be a bit unfortunate that Boost called it boost::none instead of e.g. std::nullopt, perhaps giving people associations with Python's None.) Instead, you can use static polymorphism. The simplest version of that was the first I showed, using function overloading. If you were to mimic a dynamic type interface in C++, you would probably use std::variant or std::any instead. To restrict the bound types you would use concepts (this is getting a bit deep, but see e.g. Boost Type Erasure). ¹ i really really really wanna zig a zig ah
71,235,683
71,235,825
Unnamed union member has non-trivial operator
I am working on a project started back to 1980s, my mission is to substitute the primitive double with the Dummy class I create. The following is the simplified problematic code: class Dummy{ private: double d; public: Dummy(){}; Dummy(double d1): d{d1}{}; Dummy& operator = ( const Dummy& dm ) { d = dm.d; return *this; } Dummy& operator = ( const volatile Dummy& dm ) { d = dm.d; return *this; } }; struct A{ bool isDummy; union{ Dummy dm ; int i; }B; }; int main(){ struct A a1; a1.B= 1.1; struct A a2; a2.B = a1.B; return 0; } And the following is the error message I got, when I compiled it with x86-64 gcc 11.2: <source>: In function 'int main()': <source>:38:14: error: use of deleted function 'A::A()' 38 | struct A a1; | ^~ <source>:17:8: note: 'A::A()' is implicitly deleted because the default definition would be ill-formed: 17 | struct A{ | ^ <source>:17:8: error: use of deleted function 'A::<unnamed union>::<constructor>()' <source>:19:10: note: 'A::<unnamed union>::<constructor>()' is implicitly deleted because the default definition would be ill-formed: 19 | union{ | ^ <source>:20:15: error: union member 'A::<unnamed union>::dm' with non-trivial 'Dummy::Dummy()' 20 | Dummy dm ; | ^~ <source>:40:14: error: use of deleted function 'A::A()' 40 | struct A a2; | ^~ <source>:41:15: error: use of deleted function 'A::<unnamed union>& A::<unnamed union>::operator=(const A::<unnamed union>&)' 41 | a2.B = a1.B; | ^ <source>:19:10: note: 'A::<unnamed union>& A::<unnamed union>::operator=(const A::<unnamed union>&)' is implicitly deleted because the default definition would be ill-formed: 19 | union{ | ^ <source>:20:15: error: union member 'A::<unnamed union>::dm' with non-trivial 'Dummy& Dummy::operator=(const Dummy&)' 20 | Dummy dm ; | ^~ However when I compiled the original project with g++ 9.3.0, only the problem on the line 41 is reported, which is the problem I want to solve. I need the overloaded operator to enable copying fromm volatile instances to non-volatile ones for the project. I have seen the solution here, which is to name the unnamed union and make it a tagged union, but the problem of this solution is that this struct is widely used, if I do it in this way, it will involve too many manual modifications. I tried to overload operator "=" for the unnamed union with the following code, which doesn't work: union { Dummy dm ; int i; void* operator=(const Dummy& d){ this->dm = d; return this; }; }B; How can I solve this problem? Thank you.
Not sure if those modifications are possible for you, but following compiles class Dummy { private: double d; public: Dummy() = default; Dummy(double d1): d{d1}{} Dummy& operator = ( const Dummy& dm ) = default; }; struct A{ bool isDummy = true; union{ Dummy dm; int i; decltype(auto) operator=(double d) { dm = d; return *this; } }B; }; Demo
71,235,818
71,236,051
OpenCV: Stack Vectors to Mat
I got 3 Vec3f and want to stack them to a 3x3 Matrix (C++). Is there a nice way to to so? In python its easy with numpy, however I dont know if there is a better way than assigin every single value from Vector to the corresponding Mat entry? Cheers
Yes you can. It depends on the precise packing arrangement that you want, but the simplest way is to simply copy their bytes into a properly sized Mat. You access the bytes of a single Vec3f instance Vec3f v by using &v[0]. You access the bytes of a matrix Mat m by using m.data (not a function). Here's an example: cv::Mat m(3, 3, CV_32FC3); cv::Vec3f vecs[3]; memcpy((void*)m.data, (const void*)&vecs[0][0], m.width * m.height * 3 * sizeof(float));
71,235,900
71,236,432
Why can variables be initialized(and used) without its declaration and definition "being run"?
C++ disallows "goto-ing over a definition:" goto jumpover; int something = 3; jumpover: std::cout << something << std::endl; This will raise an error as expected, because "something" won't be declared(or defined). However, I jumped over using assembly code: #include<iostream> using namespace std; int main(){ asm("\njmp tag\n"); int ptr=9000;//jumped over cout << "Ran" << endl; asm("\ntag:\n"); cout << ptr << endl; return 0; } It printed 9000, although the int ptr=9000;//jumped over line is NOT executed, because the program did not print Ran. I expected it would cause a memory corruption/undefined value when ptr is used, because the memory isn't allocated(although the compiler thinks it is,because it does not understand ASM). How can it know ptr is 9000? Does that mean ptr is created and assigned at the start of main()(therefore not skipped,due to some optimizations or whatever) or some other reason?
Jumping between asm() statements is not supported by GCC; your code has undefined behaviour. Literally anything is allowed to happen. There's no __builtin_unreachable() after it, and you didn't even use asm goto("" ::: : "label") (GCC manual) to tell it about a C label the asm statement might or might not jump to. Whatever happens in practice with different versions of gcc/clang and different optimization levels when you do that is a coincidence / implementation detail / result of whatever the optimizer actually did. For example, with optimization enabled it would do constant-propagation assuming that the int ptr=9000; statement would be reached, because it's allowed to assume that execution comes out the end of the first asm statement. You'd have to look at the compiler's full asm output to see what actually happened. e.g. https://godbolt.org/z/MbGhEnK3b shows GCC -O0 and -O2. With -O0 you do indeed get it reading uninitialized stack space since it jumps over a mov DWORD PTR [rbp-4], 9000, and with -O2 you get constant-propagation: mov esi, 9000 before the call std::basic_ostream<char,... operator <<(int) overload. because the memory isn't allocated Space for it actually is allocated in the function prologue; compilers don't generate code to move the stack pointer every time they encounter a declaration inside a scope. They allocate space once at the start of a function. Even the one-pass Tiny C Compiler works this way, not using a separate push to alloc+init separate int vars. (This is actually a missed optimization in some cases when push would be useful to alloc + init in one instruction: What C/C++ compiler can use push pop instructions for creating local variables, instead of just increasing esp once?) Even moreso than most other kinds of C undefined behaviour, this is not something the compiler can actually detect at run-time to warn you about. asm statements just insert text into GCC's asm output which is fed to the assembler. You need to accurately describe to the compiler what the asm does (using constraints and things like asm goto) to give the compiler enough information to generate correct code around your asm statement. GCC does not parse the instructions in the asm template, it just copies it directly to the asm output. (Or for Extended asm, substitutes the %0, %1 etc. operands with text generated according to the operand constraints.)
71,236,946
71,240,197
How to interface an existing class
I have this Class that have an enum "AT_Color" inside: class K_DxfDwgColor { enum AT_Color { Normal = 0, ByLayer = 1, ByBlock = 2 }; COLORREF m_crColor = 0; AT_Color m_atColor = AT_Color::Normal; public: K_DxfDwgColor(COLORREF pkColorref) :m_crColor(pkColorref) {}; K_DxfDwgColor(K_DxfDwgColor::AT_Color paColor):m_atColor(paColor){}; OdCmColor colorClone; OdCmColor SetLayerColor(bool pbDefaultForegroundColor, bool pbByLayer, bool pbIsSolidFill); COLORREF GetColor(){ return m_crColor;} AT_Color GetType() { return m_atColor;} }; The enum is declared private in the class, which means it is not accessiblefrom the main. Now, we want to declare an object for this class and use the constructor which gets an AT_Color. K_DxfDwgColor colorDefiner(K_DxfDwgColor::ByBlock); Every time I declare my object this way, I get an error message that the enum is inaccessible. Can someone show me how to declare it correctly? Thanks in advance
Move the enum outside of the class, it is necessary to be known from the calling party: enum AT_Color { Normal = 0, ByLayer = 1, ByBlock = 2 }; class K_DxfDwgColor { public: K_DxfDwgColor(AT_Color paColor):m_atColor(paColor){}; }
71,237,422
71,238,172
Where to use an rvalue as a function parameter?
I know there are plenty of questions about the argument, but I still don't understand some basic stuff about rvalues. Supposing I have a function of this kind: /* 1 */ void func( std::string s ) { /* do something with s */ } which I use in this way: int main() { func( "a string" ); } In a case like that, in which I pass this string to the function func wouldn't be better to always define this kind of function in this way: /* 2 */ void func( std::string&& s ) { /* do something with s */ } My question is: wouldn't be always better to use /* 2 */ instead of /* 1 */ in cases like the one of this example? And if not, why and where should I use the one or the other? The fact is that, if I understood well, in /* 2 */ the parameter is moved and will never be used outside of the function scope, right?
In your specific example where a temporary string is created at call time, both expressions are equivalent. Indeed, you could not keep both and use overload resolution, because they capture the same type of object (again, only in your example). They both can capture the temporary string and have it available in parameter s.
71,238,176
71,239,650
How can I pass args to a curl request executed via boost::process:child?
I'm able to execute a http POST request using curl via boost::process::child by passing the entire command line. However, I would like to pass the arguments via boost::process::args but I cannot get it work. This works: const std::string cmdDiscord = "curl -X POST https://discord.com:443/api/webhooks/1234567890 -H \"content-type: application/json\" -d \"{\"content\": \"test\"}\""; boost::process::child c(cmdDiscord); // this works boost::process::child c(boost::process::cmd = cmdDiscord); // strangely, this doesn't work I want to use boost::process::args but this fails: std::vector<std::string> argsDiscord {"-X POST", "https://discord.com:443/api/webhooks/1234567890", "-H \"content-type: application/json\"", "-d \"{\"content\": \"test\"}\""}; boost::process::child c(boost::process::search_path("curl"), boost::process::args (argsDiscord)); The error is curl: (55) Failed sending HTTP POST request which is quite a vague error message. I couldn't find any examples calling curl. Does anyone have any suggestions on getting this to work?
It should be std::vector<std::string> argsDiscord {"-X", "POST", "https://discord.com:443/api/webhooks/1234567890", "-H", "content-type: application/json", "-d", "{\"content\": \"test\"}"}; Since command interpretators pass arguments like -X POST are two arguments, not one. The double quotes are a shell syntax as well. The shell interprets (removes) them during command line expansion. Alternatively curl accepts adjacent values in short options (without space) std::vector<std::string> argsDiscord {"-XPOST", "https://discord.com:443/api/webhooks/1234567890", "-H", "content-type: application/json", "-d", "{\"content\": \"test\"}"};
71,238,876
71,239,229
Can a VAO name be re-used after calling glDeleteVertexArrays by calling glGenVertexArrays later?
It is my understanding from the OpenGL documentation that a VAO can be deleted (glDeleteVertexArrays), and then later regenerated (glGenVertexArrays). However, I have an issue when I am getting an OpenGL error when trying to re-use an existing VAO variable in a Chunk class (for a Minecraft clone). This only happens for some chunks and I cannot understand why. I output the VAO value (unsigned int type) and it doesn't seem to change after deleting with glDeleteVertexArrays. It was my understanding from the documentation that this value would be reset to zero after running this function. See Chunk class code below. void Chunk::load() { // Update chunk state loaded = true; // Set up OpenGL buffers glGenVertexArrays(1, &VAO); glGenBuffers(1, &vertexVBO); glGenBuffers(1, &textureVBO); glGenBuffers(1, &EBO); // VAO bound before setting up buffer data glBindVertexArray(VAO); // Indices glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_DYNAMIC_DRAW); // Vertices glBindBuffer(GL_ARRAY_BUFFER, vertexVBO); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(float), &vertices[0], GL_DYNAMIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(unsigned int), (void*)0); glEnableVertexAttribArray(0); // Texture Coordinates glBindBuffer(GL_ARRAY_BUFFER, textureVBO); glBufferData(GL_ARRAY_BUFFER, texCoords.size() * sizeof(float), &texCoords[0], GL_DYNAMIC_DRAW); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0); glEnableVertexAttribArray(1); // Unbind glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void Chunk::unload() { // Update chunk state loaded = false; // Delete arrays/buffers. glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &vertexVBO); glDeleteBuffers(1, &textureVBO); glDeleteBuffers(1, &EBO); }
Just as delete ptr; in C++ or free(ptr); in C does not actually change the pointer value of ptr variable, calling glDelete* on an OpenGL object does not change the value of the variables you give it. It is up to you to not use the variable again or to assign it to a neutral value. That having been said, if your intent is to immediately create a new VAO... why bother? Just clear out the old one by disabling all of the attribute arrays and buffer bindings, and its ready to be used anew: glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); GLint maxAttrib; glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &maxAttrib); for(int attribIx = 0; attribIx < maxAttrib; ++attribIx) { glDisableVertexAttribArray(attribIx); glVertexAttribPointer(attribIx, 4, GL_FLOAT, GL_FALSE, 0, nullptr); glVertexAttribDivisor(attribIx, 0); }
71,239,663
71,783,407
Does callback copy jnienv, jinstance inside a JNI function?
The lambda that I pass to builder is populated into className object, and called at regular intervals (every hour) of time to refresh the other members. It gets called the first time successfully. I'm not sure if the lambda retains env, instance to legally call the reverse JNI function? JNIEXPORT jint JNICALL Java_com_company_app_ClassName_JniInit(JNIEnv *env, jobject instance){ int data = 0; auto builder = new Builder(data, [env, instance]() -> std::string { std::string stringObj = populateData(env, instance); // This function makes a reverse JNI call to get data from a java function in the class return stringObj; } ); std::shared_ptr<className> = builder->build(); return 1; } I seem to be getting a SIGNAL 11 error, SIGSEGV. Is this kind of segmentation fault catchable in any way, so the app doesn't crash? Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x228 in tid 21785 (ClassName), pid 21573 (.company.app) It seems to be crashing at this line inside populateData- jstring data = (jstring)(env)->CallObjectMethod(instance, javaFunctionName); Is there a way to check if this function will fail before calling it? I checked if env (JNIEnv* argument in populateData) is NULL, but its not, and has a valid address along with instance (jinstance argument in populateData).
To answer this question, I have found a slightly different kind of hack. Don't copy the JNIEnv, and object or create references to them. They get deleted as soon as your JNI function goes out of scope. I'm not sure why copying doesn't work (if someone could answer this, that would be great). Alternatively, I've used JavaVM* to maintain a local reference of the jvm, you can do this in your JNI_OnLoad. Use the function below, and it would work fine. JavaVM* jvm; // Initialise this in OnLoad JNIEnv *getJNIEnv() { JNIEnv *env = nullptr; jint ret = jvm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6); if (ret == JNI_EDETACHED || !env) { env = nullptr; } return env; } If you need the class instance, you'll need to initialise it via JNIEnv, but I use a static method for my class, so I just fetched the class using env->FindClass and then you can do env->GetStaticMethodID along with env->CallStaticObjectMethod.
71,240,104
71,240,299
How do c/c++ preprocessors work when encountering unknown directives?
Do c/c++ preprocessors process all lines that begin with #? Does is errors out when encountering unknown macros or will it just ignore them? for an example, #include <stdio.h> #hello int main(){ printf("Hello World!"); return 0; } what happens in this situation?will it produce an error or will it work (ignoring #hello line)?
The language grammar specifies all pre-processor directives that exist in the language. If you use any other name for the directive, then that is a "conditionally-supported-directive". If the conditionally supported directive isn't supported, then the the language implementation is required to issue a diagnostic message and is free to refuse to proceed.
71,240,128
71,241,469
Writing to Framebuffer using multiple shaders
I'm currently implementing skeletal animation in my deferred rendering pipeline. Since each vertex in a rigged mesh will take at least an extra 32 bytes (due to the bone's vertex IDs & weights), I thought it would be a good idea to make a different shader that will be in charge of drawing animated meshes. That being said, I have a simple geometry buffer (framebuffer) that has 4 color attachments. These color attachments will be written to using my static geometry shader. C++ code looks like: glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glBindFramebuffer(GL_FRAMEBUFFER, gID); // Bind FBO glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(staticGeometryShaderID); // Bind static geometry shader // Pass uniforms & draw static meshes here glBindFramebuffer(GL_FRAMEBUFFER, 0); // Unbind FBO The code above functions correctly. The issue is when I try to add my animation shader into the mix. The following code is what I am currently using: glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glBindFramebuffer(GL_FRAMEBUFFER, gID); // Bind FBO glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(staticGeometryShaderID); // Bind static geometry shader // Pass uniforms & draw static meshes here glUseProgram(animationShaderID); // Bind animated geometry shader // Pass uniforms & draw animated meshes here glBindFramebuffer(GL_FRAMEBUFFER, 0); // Unbind FBO The above example is the same as the last, except another shader is bound after the static geometry is drawn, which attempts to draw the animated geometry. Keep in mind that the static geometry shader and animated geometry shader are the EXACT SAME (besides the animated vertex shader which transforms vertices based on bone transforms). The result of this code is my animated meshes are being drawn, not only for the current frame, but for all previous frames as well. The result looks something like this: https://gyazo.com/fef2faccbfd03377c0ffab3f9a8cb8ec My initial thought when writing this code was that the things drawn using the animated shader will simply just overwrite the previous data (assuming that the depth is lower) since I'm not clearing the depth or color buffers. This obviously isn't the case. If anyone has an idea as to how to fix this, that would be great!
Turns out that I wasn't clearing my vector of render submissions, so I was adding a new mesh to draw every frame.
71,240,343
71,243,977
How do I pack a Gtk::Entry into a Gtk::HeaderBar so the entry completely fills the header bar?
I'm making a program in gtkmm-3.0 which has a Gtk::HeaderBar as the title bar. I'm trying to pack a Gtk::Entry into it using this code: Gtk::HeaderBar headerBar; Gtk::Entry entry; headerBar.set_hexpand(); headerBar.set_halign((Gtk::Align)GTK_ALIGN_FILL); entry.set_hexpand(); entry.set_halign((Gtk::Align)GTK_ALIGN_FILL); headerBar.pack_start(uriEntry); headerBar.set_show_close_button(); The entry is correctly packed, but it only fills half the space of the header bar, which is very confusing. Using headerBar.add(entry) or headerBar.pack_end(entry) does not help the slightest (The entry still fills half the space it's supposed to take). Also, using headerBar.pack_start() with a Gtk::Button before the headerBar.pack_start(entry) line will put the button in its place, but the entry will stop the expansion at the same point that it stopped before, being shorter than before. How can I make the entry fill the whole header bar?
The problem is that Gtk::HeaderBar also has a "title" widget taking space. You could set a title, resulting in this: An you see why only half the screen was given to the entry. One workaround is to define your own, custom, header bar. Here is an extremely minimal example: #include <gtkmm.h> class MainWindow : public Gtk::ApplicationWindow { public: MainWindow(); private: Gtk::Box m_customHeaderBar; Gtk::Entry m_entry; }; MainWindow::MainWindow() { m_entry.set_hexpand_set(true); m_entry.set_hexpand(); m_customHeaderBar.pack_start(m_entry); set_titlebar(m_customHeaderBar); } int main(int argc, char *argv[]) { auto app = Gtk::Application::create(argc, argv, "org.gtkmm.examples.base"); MainWindow window; window.show_all(); return app->run(window); } Which results in this: Of course, you will have to add a close button and everything yourself (I would recommend making a class). I will leave this part to you.
71,240,481
71,240,723
why the below boost variant visitor code doesnt work
I have a struct A: struct A { //some implementation } My boost variants are: boost::variant<double, A> v1 = 1.0; boost::variant<double, A> v2 = 2.0; My visitor functor is defined as: class SomeWork: public boost::static_visitor<int> { public: int operator()(const A& data1, const A& data2) const { //some work return 1; } int operator()(const double& data1, const double& data2) const { //some work return 2; } }; int main() { boost::variant<double, A> v1 = 1.0; boost::variant<double, A> v2 = 2.0; boost::apply_visitor(SomeWork(), v1 ,v2); return 0; }; When I do above I get an error saying: error C2664: 'int SomeWork::operator ()(const A&, const A&) const': cannot convert argument 2 from 'T' to 'const double &' Not sure why this happening. boost version I am using is 107200 Thanks in advance.
boost::apply_visitor needs to consider every possible combination of types that your variant instances hold. This means SomeWork is missing the following combinations: int operator()(const A& data1, const double& data2) const { //some work return 3; } int operator()(const double& data1, const A& data2) const { //some work return 4; } When adding those, I'm able to compile your code.
71,240,604
71,240,761
Can I use a const char* or std::string variable containing grammar as argument to libfmt?
Hopefully this is a silly question. I have the following code: #include <iostream> #include <fmt/format.h> #include <string> int main(){ double f = 1.23456789; std::cout << fmt::format( "Hello {:f} how are you?\n", f ) << "\n"; return 0; } And this works as expected --Hello 1.234568 how are you? But if I want to encapsulate the string passed into fmt::format as a variable, I run into a compiler error: #include <iostream> #include <fmt/format.h> #include <string> int main() { double f = 1.23456789; const char* m = "Hello {:f} how are you?\n"; //can't be constexpr, generated at run time std::cout << fmt::format( m, f ) << "\n"; return 0; } However, on MSVC 2022 using #include <format>, this works perfectly... #include <iostream> //#include <fmt/format.h> #include <format> #include <string> int main() { double f = 1.23456789; const char* m = "Hello {:f} how are you?\n"; std::cout << std::format( m, f ) << "\n"; return 0; } Is this possible using libfmt? It appears libfmt wants a constexpr value passed in whereas msvc's <format> evaluates this at runtime. What silly mistake am I making here?
Since libfmt 8.1, you can wrap the format string in fmt::runtime to enable runtime formatting: #include <iostream> #include <fmt/format.h> #include <string> int main() { double f = 1.23456789; const char* m = "Hello {:f} how are you?\n"; //can't be constexpr, generated at run time std::cout << fmt::format(fmt::runtime(m), f ) << "\n"; return 0; }
71,240,646
71,242,266
C++ Template explicit rvalue type
#include <iostream> using namespace std; namespace mine { template <typename T> struct remove_rval { using type = T; }; template <typename T> struct remove_rval<T&&> { using type = T; }; template <typename T> void g(const T& = typename remove_rval<T>::type()) cout << __PRETTY_FUNCTION__ << endl; } } int main() { mine::g<int&&>(); // doesn't work, because of explicit template? const int& i2 = mine::remove_rval<int&&>::type(); // works, sanity check return 0; } The function template I wrote fails to compile. From my understanding of c++, you can assign an rvalue to a constant lvalue reference. But, in this situation, it is like the deduced type disregards the 'const' qualifier when assigning the function default value. Why is this?
From dcl.ref/p6: If a typedef-name ([dcl.typedef], [temp.param]) or a decltype-specifier ([dcl.type.decltype]) denotes a type TR that is a reference to a type T, an attempt to create the type lvalue reference to cv TR creates the type lvalue reference to T, while an attempt to create the type rvalue reference to cv TR creates the type TR. Thus in your example, when T = int&& : const T& collapses to T&(which isint&) and not const T&(which is const int&) according to the above quoted statement. And since we can't bind an rvalue like remove_rval<T>::type() to a non-const lvalue reference, you get the mentioned error. Thus, even though the form of the function parameter in g is a reference to const T aka const lvalue reference(i.e., const T&), the first call to g instantiates g with a reference to non-const T aka non-const lvalue reference(i.e., T& =int&) as the parameter: template<> void g<int &&>(int&) { //operator<< called here } And since the parameter is int&, we cannot bind an rvalue like remove_rval<int&&>::type() to that parameter.
71,240,929
71,241,106
why infinite loop terminates? or go infinite
I was trying a test and I wrote this program... #include<iostream> using namespace std; main() { int arr[5]={1,2,3,5,3}, num=5; for(int i=0; i< num; i++) { for(int j=(i+1); i< num; j++) { if (arr[i]==arr[j]) { cout<<"test"; } cout<<j<<endl; } } } hmmm... In the below code I know I used "i" instead of "j",So just to create the problem I used this for(int j=(i+1); i< num; j++) And my problematic part of the program is- for(int j=(i+1); i< num; j++) { if (arr[i]==arr[j]) { cout<<"test"; } cout<<j<<endl; } in the above code when I remove this if block- if (arr[i]==arr[j]) { cout<<"test"; } the program goes infinite......... But when I put this if block again the program terminates automatically after some execution. I also read about this on this link but it shows example of java And there they show the reason of negative value, but in my program there is no garbage value comes.
Without the if (arr[i]==arr[j]), you simply have an infinite loop, which is perfectly valid in this case. j will just keep getting incremented (eventually this will overflow, which in undefined behaviour, see [basic.fundamental]/2), and the condition will never be met, since i does not change. However, with the if (arr[i]==arr[j]) in the code, j is being incremented, and you will go outside the bounds of the array (as you know). In C++, this is Undefined Behaviour, meaning anything can happen. In your case, it seems to be causing the program to crash (which is actually a good thing, since it indicates an error).
71,241,706
71,241,790
Sum of 1 + 1/2 + 1/3 +.... + 1/n without iterations using digamma function and Euler's constant
So i like to make my life hard, i've got a task to calculate the sum of 1 + 1/2 + 1/3 + 1/4 +.... + 1/n. The conditions is to not use iterations but a closed formula. On this post : https://math.stackexchange.com/questions/3367037/sum-of-1-1-2-1-3-1-n I've found a pretty neat looking solution: 1+1/2+1/3+⋯+1/n=γ+ψ(n+1) where γ is Euler's constant and ψ is the digamma function. For digamma I'm using the boost c++ libraries and I calculate the Euler's constant using exp(1.0). The problem is that I don't get the right answer. Here is my code: #include <iostream> #include <cmath> #include <boost/math/special_functions/digamma.hpp> int main(){ int x; const double g = std::exp(1.0); std::cin >> x; std::cout<<g + boost::math::digamma(x+1); return 0; } Thanks in advance) !
Euler is known for having a lot of things named for him. That can easily become confusing, as seems to be case here. What you are adding to the digamma function result is Euler's number. You are supposed to add Euler's constant, which is a different number named after Euler. You can find the correct number in boost as boost::math::constants::euler, e.g.: const double g = boost::math::constants::euler<double>(); (Thanks @Eljay) For some context on such how much is named after Leonhard Euler and how confusing it can get, here is the Wikipedia page's section on just numbers named after him, counting 11 different items: https://en.wikipedia.org/wiki/List_of_things_named_after_Leonhard_Euler#Numbers
71,241,717
71,241,827
How to initialize nested array of structs in C++?
I have the following definitions: struct Display_font_char { unsigned char * data; int originX; int originY; unsigned int width; unsigned int height; unsigned int delta; }; struct Display_font { Display_font_char * chars; unsigned char rangeStart; unsigned char rangeEnd; }; How can I initialize it inplace? I'm trying: const Display_font font = { { { { 1, 2, 3 }, 1, 2, 3u, 4u, 5u } }, 1u, 2u } However, I'm getting an error: "Cannot use value of type int to initialize field of type Display_font_char *"
You cannot initialise a pointer with a braced init list of multiple values. Here is an example of how you could initialise an instance of the class: unsigned char uc[] = { 1, 2, 3 }; Display_font_char fc { uc, 1, 2, 3u, 4u, 5u, }; const Display_font font = { &fc, 1u, 2u, }; As a sidenote, if you were to switch to C, then you could use compound literals: const struct Display_font font = { &(struct Display_font_char){ (unsigned char []){ 1, 2, 3 }, 1, 2, 3u, 4u, 5u }, 1u, 2u }; But alas, compound literals don't exist in C++.
71,241,817
71,242,096
Returning a pair of objects
The following is an anti-pattern: auto f() { std::vector<int> v(100000); return std::move(v); // no need to use std::move thanks to RVO (return value optimization) } Using a std::move can even produce worst code (see here) However, what should I do in the following situation: auto f() { std::vector<int> v0(100000); std::vector<int> v1(100000); return std::make_pair(std::move(v0),std::move(v1)); // is the move needed? }
For the second snippet, auto f() { std::vector<int> v0(100000); std::vector<int> v1(100000); return std::make_pair(std::move(v0),std::move(v1)); // is the move needed? } return returns the result of the std::make_pair() function. That's an RValue. However, the OP's question probably condenses to whether (or why not) Named Return Value Optimization still applies to v0/v1 when returned as a std::pair. Thereby, it's overlooked that v0/v1 aren't subject of return anymore, but become arguments of std::make_pair(). As such, v0/v1 are LValues – std::move(v0), std::move(v1) have to be applied to turn them into RValues if move-semantic is intended. Demo on coliru: #include <iostream> template <typename T> struct Vector { Vector(size_t n) { std::cout << "Vector::Vector(" << n << ")\n"; } Vector(const Vector&) { std::cout << "Vector::Vector(const Vector&)\n"; } Vector(const Vector&&) { std::cout << "Vector::Vector(const Vector&&)\n"; } }; auto f1() { Vector<int> v(100000); return std::move(v); // over-pessimistic } auto f2() { Vector<int> v(100000); return v; // allows NRVO } auto f3() { Vector<int> v0(100000); Vector<int> v1(100000); return std::make_pair(v0, v1); // copy constructor called for v0, v1 } auto f4() { Vector<int> v0(100000); Vector<int> v1(100000); return std::make_pair(std::move(v0),std::move(v1)); // move constructor called for v0, v1 } #define DEBUG(...) std::cout << #__VA_ARGS__ << ";\n"; __VA_ARGS__ int main() { DEBUG(f1()); DEBUG(f2()); DEBUG(f3()); DEBUG(f4()); } Output: f1(); Vector::Vector(100000) Vector::Vector(const Vector&&) f2(); Vector::Vector(100000) f3(); Vector::Vector(100000) Vector::Vector(100000) Vector::Vector(const Vector&) Vector::Vector(const Vector&) f4(); Vector::Vector(100000) Vector::Vector(100000) Vector::Vector(const Vector&&) Vector::Vector(const Vector&&)
71,241,987
71,472,305
How to assert that constructor throws exception using CppUnitTestFramework
Looking to verify that the constructor throws exceptions in the required places using CppUnitTestFramework. Assert::ExpectException<std::exception>(Service pService = Service(hServiceManager, L"NotValidName")); The above code doesn't work but I can't figure out how this should be implemented. Also can't seem to only expect specific exceptions: Assert::ExpectException<ERROR_INVALID_SERVICENAME>(Service pService = Service(hServiceManager, L"NotValidName")); Thanks!
"Solution": Move to GTest if using Visual Studio
71,242,632
71,244,017
why "#define BOOST_ASIO_ENABLE_HANDLER_TRACKING 1" doesn't work as expected?
Reference: https://www.boost.org/doc/libs/1_78_0/doc/html/boost_asio/overview/core/handler_tracking.html https://www.boost.org/doc/libs/1_78_0/doc/html/boost_asio/example/cpp11/handler_tracking/async_tcp_echo_server.cpp Based on the documentation, when enabled by defining BOOST_ASIO_ENABLE_HANDLER_TRACKING, Boost.Asio writes debugging output to the standard error stream. I made the following changes to the source code of async_tcp_echo_server.cpp. 17 #define BOOST_ASIO_ENABLE_HANDLER_TRACKING 1 18 using boost::asio::ip::tcp; Above the using boost::asio::ip::tcp;, I added #define BOOST_ASIO_ENABLE_HANDLER_TRACKING 1 and expect this will trigger the debugging track. However, it doesn't work. $ g++ -std=gnu++2a -Wall -g -ggdb -Werror -I /usr/include/boost -pthread async_tcp_echo_server.cpp -o async_tcp_echo_server $ ./async_tcp_echo_server 3333 ^C Instead, I removed the added macro definition from the source code and added -DBOOST_ASIO_ENABLE_HANDLER_TRACKING to the command line for the compiler and now it works as expected. $ g++ -std=gnu++2a -Wall -g -ggdb -Werror -I /usr/include/boost -pthread async_tcp_echo_server.cpp -o async_tcp_echo_server -DBOOST_ASIO_ENABLE_HANDLER_TRACKING $ ./async_tcp_echo_server 3333 @asio|1645642051.016866|0^1|in 'do_accept' (async_tcp_echo_server.cpp:95) @asio|1645642051.016866|0*1|socket@0x7ffec2082aa8.async_accept @asio|1645642051.017322|.1|non_blocking_accept,ec=system:11 From g++ online manual, -D name Predefine name as a macro, with definition 1. Question> Why the macro definition within the source code doesn't work? Thank you
As the commenter helpfully pointed out: you have to define the preprocessor define before the first inclusion of any (!) Asio header. However, there's another reason why specifying it in your build script is FAR superior. Using BOOST_ASIO_ENABLE_HANDLER_TRACKING breaks interface. It must be defined in every translation unit participating in a link or else you will have undefined behaviour (ODR violations). See e.g. Valgrind errors from boost::asio
71,243,379
71,243,564
pointer type operator VS const bool operator precedence
#include <cstdint> #include <iostream> struct a_struct { int64_t* le_int; bool not_ok; a_struct() : le_int{ new int64_t(0) }, not_ok{ false } {} ~a_struct() { delete le_int; } operator bool() const { return !not_ok; } operator int64_t* () { return le_int; } }; int main(int argc, char** argv) { a_struct s; s.not_ok = true; if (!s)//<- std::cout << "o no." << std::endl; else if (s.not_ok) std::cout << "waddu heck?" << std::endl; return 0; } In this example the !s resolution prefers the int64_t*() operator over the const bool() operator. Why?
Since your object s is not const, it prefers the non-const way of calling the type cast operator. So, removing the const from your bool type cast operator does the trick.
71,243,671
71,243,762
C++ vs Python execution time mathematical operations
I have the same code in two different languages: C++ and Python. C++ code: #include <iostream> float m = 16442.34; float c = 2434.1; float t = 0.34; int n = 3; float i = 934380.72; int k = 111; int ris = 0; int tot = 0; int main() { while(tot<1000000){ ris++; tot = (ris * (m - c)) - (int(ris/n) * t * m * n) - (i * int(ris/k)); } std::cout << ris << " steps\n"; } Python code: m = 16442.34 c = 2434.1 t = 0.34 n = 3 i = 934380.72 k = 111 ris = 0 tot = 0 while tot<1000000: ris+=1 tot = (ris * (m - c)) - (int(ris/n) * t * m * n) - (i * int(ris/k)) print(ris, "steps") Why is there a huge difference in execution time? Is it possible to speed up the Python code? How?
Python is an interpreted language while C++ gets compiled to machine code. This enables a C++ compiler to produce highly optimized code while the python interpreter "has to think more in order to execute the program". You could compile the python code (as Samwise said), e.g., with Cython. Also, you are using 32-bit floats in C++ which yield different floating point errors than the 64-bit (?) numbers of python. Changing the type from float to double at least created the same (apart from minor floating point errors) result for tot and ris. Thanks @Michael Szczesny for pointing towards this bug.
71,243,721
71,246,506
absl::FormatSpec results in ambiguous function call under clang
Under Clang, the following code gives me an ambiguous function call error: #include "absl/strings/str_format.h" struct Foo {}; template<typename... Args> void func(absl::FormatSpec<Args...> format, const Args&... args) {} template<typename... Args> void func(Foo, absl::FormatSpec<Args...> format, const Args&... args) {} int main() { func("%s", "Hello"); func(Foo{}, absl::string_view{"Test"}); } I'm trying to understand why Clang can not determine that it should call the func that is overloaded to explicitly accept Foo as its first argument, whereas GCC can. There's a Godbolt link here.
The reason why you see different behaviour on GCC and Clang is that GCC and Clang are seeing different versions of the FormatSpec class, which is defined here On GCC, the ABSL_INTERNAL_ENABLE_FORMAT_CHECKER feature is off because this feature relies on the compiler-specific enable_if attribute, which is only supported by Clang. Consequently, GCC sees three constructor declarations, none of which can accept Foo. This means only the second func overload is viable. On Clang, the ABSL_INTERNAL_ENABLE_FORMAT_CHECKER feature is on, and there are 6 constructor declarations, including one of the form FormatSpecTemplate(...) // NOLINT __attribute__((unavailable("Format string is not constexpr."))); This constructor accepts Foo but if it is actually called, then there will be a compilation error. But we don't get that far, because Clang thinks that both func overloads are viable and cannot choose one. The first overload involves a user-defined conversion in the first argument; the second overload involves a user-defined conversion in the second argument; neither is better than the other. I'm not sure why this particular constructor exists, considering the potential to cause issues like the one you're experiencing. It seems to me that it ought to be constrained, maybe like this, so that it can't possibly take Foo as an argument: template <class T> FormatSpecTemplate(T&&) requires std::convertible_to<T, const char*> || std::convertible_to<T, string_view> __attribute__((unavailable("Format string is not constexpr."))); But I'm sure there's some reason why they didn't do this.
71,243,880
71,244,241
std::unique not working as expected with struct
I'm currently working on a 2D game where the level is defined by edges: struct Edge { vec2int start; vec2int end; } The struct vec2int is a vector with x, y coordinates and has all needed operators (in this particular case operator==) overloaded. Because of a data structure that stores the edges inside of a grid, there can be duplicate edges in different cells inside the grid. When combining them back into a single std::vector<Edge> I tried to get rid of them like this: auto it = std::unique( edges.begin(), edges.end(), [&](const Edge& e1, const Edge& e2) { return e1.start == e2.start && e1.end == e2.end; }); edges.resize(std::distance(edges.begin(), it)); For whatever reason this deletes only a few (or none) of the duplicate edges. I have no idea why. Is there something I am missing about std::unique? The code: #include <algorithm> #include <iostream> #include <vector> template<class T> struct v2d_generic { T x = 0; T y = 0; bool operator==(const v2d_generic& rhs) const { return (this->x == rhs.x && this->y == rhs.y); } bool operator!=(const v2d_generic& rhs) const { return (this->x != rhs.x || this->y != rhs.y); } }; typedef v2d_generic<int> vec2i; struct Edge { vec2i start; vec2i end; }; int main(void) { std::vector<Edge> edges; edges.push_back(Edge{vec2i{1, 1}, vec2i{1, 1}}); edges.push_back(Edge{vec2i{1, 1}, vec2i{1, 2}}); edges.push_back(Edge{vec2i{1, 1}, vec2i{1, 1}}); edges.push_back(Edge{vec2i{1, 1}, vec2i{1, 2}}); std::cout << edges.size() << std::endl; auto it = std::unique( edges.begin(), edges.end(), [&](const Edge& e1, const Edge& e2) { return e1.start == e2.start && e1.end == e2.end; }); edges.resize(std::distance(edges.begin(), it)); std::cout << edges.size() << std::endl; } This outputs 4 both times.
std::unique removes consecutive equivalent elements. In your example, you do not have consecutive equal elements, so it should not remove anything. If you do not care about the order of the elements in your range, you can sort it before calling std::unique.
71,243,906
71,249,619
GLFW Window poll events lag
I have a problem handling GLFW poll events. As far as I know, all user input events are handled via callbacks or via constantly checking keyboard / mouse states. The latter is not so efficient an can even result in missing some input (e. g. when button pressed and then released between checking state). What is more, some events like window resizing cannot be handled without callbacks. So, the problem is that whenever user starts resizing window (presses mouse button but doesn't move mouse), the app seems to freeze. This is, assuming resize callback is enabled and defined validly (even when copied right from GLFW API). And the problem is not that window doesn't redraw. Redraw on callback can be done with creating and calling own render() function in callback function. The actual problem is that even when I handle resize event properly and redraw on callback, there is still some lag. This lag is after mouse press on decorated window border and when mouse is not moving. Here's a demonstration (button click is highlighted green): Sorry for messed up GIF. All callbacks listed in GLFW API are enabled and handled (window-, input-, joystick- and monitor-callbacks) and redraw is called in each one. It seems that I'm missing some of the callbacks or GLFW just works like that. According to this answer, this can't be done without threading: That only works when the user moves the mouse while holding - just holding left-click on the resize window part still stalls. To fix that, you need to render in a separate thread in addition to this. (No, you can't do that without threading. Sorry, this is how GLFW works, no one except them can change it.) So, the questions are: How can I fix this issue without threading? If I can't, I guess I can emulate resizing with different cursors shapes and resizing zones or smth like that... If this is still impossible to solve in GLFW, do other GLFW alternatives have this issue? Are there any problems with GLFW similar to this one?
GLFW is not at fault here. It's how the operating system handles certain user input events like mouse down on the decorator resize handles of a window or moving the whole window. See this answer for a more elaborate detail: Win32: My Application freezes while the user resizes the window GLFW uses the standard Windows PeekMessage -> TranslateMessage/DispatchMessage loop which you will find in any GUI Windows application. This will get invoked when you call glfwPollEvents() and it processes all Window event messages that the OS has accumulated so far for all windows in this process. After all messages so far have been processed, the call to glfwPollEvents() will return and will allow your own window/game loop to continue. What happens is that once the user clicks down the window decoration's resize handles, effectively the call to glfwPollEvents() will block within the OS itself in order for the OS / window-manager to intercept the mouse and keyboard messages to do its window resizing/reshaping thing. I'm afraid that even though Windows will inform the process about the start of a window resize or move action (after which the OS will have control of the window message processing) and GLFW already handling these events internally, right now GLFW will not notify the client application about this. It would be possible though for GLFW to provide an appropriate event callback to the application, so that the application can start a timer or thread only for as long as the window resize/move action happens (as is also mentioned in the linked other Stackoverflow answer). So, the only thing that you can do in order to keep rendering while the user holds onto the resize handles or while the user moves the window around, is to render in a separate thread.
71,243,910
73,235,853
What is the name of tool that gives you the declaration of a function in C/C++
Just a simple question about definitions in C/C++ toolchains and IDE's: What is the name of tool/mechanism/software that direction you to the declaration of the function like when, for example: You are in a Eclipse based IDE and press "CTRL + Left Mouse Button" on a function name and you are directioned to the function declaration. Is that the Linker? Or the Intellisense? Or maybe another thing? EDIT: PS: Not just a function, but also a define, a typedef, a class and so on.
In summary, like said in comments the name of this tool depends of each IDE. But it could be described in general words as " 'go to definition' feature"
71,243,987
71,272,749
debug error: stack around the variable 's' was corrupted
edit(fixed): so the error seems to appear because writing a 20 character array will add \0 as a character and become a 21 character array. I'm trying to detect a char c and remove it from a string char[20] s, but if I wrote a string s of 20 characters exactly, the debug error pops but the code works fine. why does it happen? #pragma once #include<iostream> #include<cstring> using namespace std; #pragma warning(disable:4996) void resultt(char c, char s[]) { while (*s != '\0') { if (*s == c) { strcpy(s,(s+1)); continue; } s++; } } void mainn() { char c; char s[20]; cout << "enter a string : "; cin >> s; cout << "enter the character : "; cin >> c; resultt(c, s); cout << s; } I call that function like this resultt(c,s) and cout<<s at last.
the error seems to appear because writing a 20 character array will add \0 as a character and become a 21 character array. by writing for example qwertyuiopqwertyuiop which is 20 characters, there won't be enough space in the array for the \0 character, so you should write a 19 character word (or less) or increase the array to 21
71,244,005
71,244,198
Euler function in C++
Can someone explain me, what is mean this Euler function: int phi (int n) { int result = n; for (int i=2; i*i<=n; ++i) if (n % i == 0) { while (n % i == 0) n /= i; result -= result / i; } if (n > 1) result -= result / n; return result; } I tried to make a standart path to solve this task, but it is over time limit. I found this interpretation of Euler function, but I can't understand it. Why we're iterating i*i<n not i<n, what's happening in while loop and so on. I know that we can write Euler function as f(n) = n * (1-1/p1)(1-1/p2)...(1-1/pk), where pi is a prime number, but I don't understand how this code is working.
We are iterating like this for the time performance because all prime factors of a number are equal or less with the square root of that number (if a number has not on of this, then it is a prime number). Then when we find a prime factor of the number we divide our number n by that factor until we can no longer divide it so we are extracting the prime factor from the number.
71,244,483
71,324,488
ARM 7 Assembly - ADC with immediate 0
I have written a little c++ function on godbolt.org and I am curious about a certain line inside the assembly. Here is the function: unsigned long long foo(uint64_t a, uint8_t b){ // unsigned long long fifteen = 15 * b; // unsigned long long result = a + fifteen; // unsigned long long resultfinal = result / 2; // return resultfinal; return (a+(15*b)) / 2; } The generated assembly: rsb r2, r2, r2, lsl #4 adds r0, r2, r0 adc r1, r1, #0 lsrs r1, r1, #1 rrx r0, r0 Now I dont understand why the line with the ADC instruction happens. It adds 0 to the high of the 64 bit number. Why does it do that? Here is the link if you want to play yourself: Link to assembly
The arm32 is only 32 bits. The value 'a' is 64bits. The instructions that you are seeing are to allow computations of sizes larger than 32bits. rsb r2, r2, r2, lsl #4 # 15*b -> b*16-b adds r0, r2, r0 # a+(15*b) !LOW 32 bits! could carry. adc r1, r1, #0 # add a carry bit to the high portion lsrs r1, r1, #1 # divide high part by 2; (a+(15*b))/2 rrx r0, r0 # The opposite of add with carry flowing down. Note: if you are confused by the adc instruction, then the rrx will also be confusing? It is a 'dual' of the addition/multiplication. For division you need to take care of underflow in the higher part and put it in the next lower value. I think the important point is that you can 'carry' this logic to arbitrarily large values. It has applications in cryptography, large value finance and other high accuracy science and engineering applications. See: Gnu Multi-precision library, libtommath, etc.
71,244,634
71,244,680
Calling getters inside a setter function vs direct access to data members
The question is simple: Is it unnecessary to call getters inside setters to have access to an object's member variables? Suppose that all the getters are inlined and return const references to members. As an example: class Foo { public: inline const std::uint32_t& getValue( ) const noexcept { return m_value; } inline const std::uint32_t& getBar( ) const noexcept { return m_bar; } void setValue( const std::uint32_t value ) { m_value = value * getBar() * 3; // vs m_value = value * m_bar * 3; } private: std::uint32_t m_value; std::uint32_t m_bar; }; Which one is more idiomatic? I think there should be no difference in the generated code by the compiler. But in terms of readability, they're a bit different. What could be the benefits of using getters instead of directly typing e.g. m_bar?
Code in the class always has full acess to the internal data members (and member functions too). So it is not necessary. My thoughts on if you should do it if the getters and particularly setters have side effects (imagine you keep a count of how many times a particular value is changed, or validate a value) then you should call them the overhead when compiled for release will disappear since the compiler can see that you are just reading or writing the value (if they are simple read and write get/set) you might get into the habit of always calling them just in case you later want them to have side effects note I dont say whats 'best', just things to take into account
71,244,656
71,245,667
What define's Boost's svg_mapper scaling and translation?
This code: #include <fstream> #include <boost/geometry.hpp> #include <boost/geometry/geometries/point_xy.hpp> #include <boost/geometry/geometries/polygon.hpp> namespace bg = boost::geometry; int main() { std::ofstream svg ( "test.svg" ); boost::geometry::svg_mapper<bg::model::d2::point_xy<double>, true, double> mapper ( svg, 6000, 3000 ); bg::model::polygon<bg::model::d2::point_xy<double>> square{ {{0, 0}, {0, 1000}, {1000, 1000}, {1000, 0}, {0, 0}}}; const std::string style{"fill-opacity:1.0;fill:rgb(128,128,128);stroke:rgb(0,0,0);stroke-width:5"}; mapper.add ( square ); mapper.map ( square, style, 1.0 ); } Produces this svg: <?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <g fill-rule="evenodd"><path d="M 1500,3000 L 1500,0 L 4500,0 L 4500,3000 L 1500,3000 z " style="fill-opacity:1.0;fill:rgb(128,128,128);stroke:rgb(0,0,0);stroke-width:5"/></g> </svg> The following conversions happen from the input polygon to the mapped svg geometries: (0, 0) -> (1500,3000) (0, 1000) -> (1500,0) (1000, 1000) -> (4500,0) (1000, 0) -> (4500,3000) (0, 0) -> (1500,3000) Staring at it a bit you see there is some transformation applied, something like this: +1500 in x +3000 in y 3x scale in x -3x scale in y My question is - What drives that transformation and can I prevent it? And if I can't prevent it, can I retrieve it or calculate it myself? Reason being is I'm producing many complex SVG's and would like them to all be in the same frame. So if there is a circle at pixels (10,10) in one, I would like all the images to be of the same size with the circle in the exact same location. I tried to accomplish this with viewBox but the scaling and translation was too hard to predict to keep the images consistent.
svg_mapper calculates a bounding box from all add-ed geometries. Then, a map_transformer is used to scale down to the desired width/height. Contrary to what you might expect, add doesn't do anything besides expanding the bounding box. Likewise, after the first map call, no other add has any effect on the bounding-box used for the transformations. In other words, you can use some kind of fixed bounding box, add only that, and then map your geometries into that "canvas": Demo #include <fstream> #include <iostream> #include <boost/geometry.hpp> #include <boost/geometry/geometries/point_xy.hpp> #include <boost/geometry/geometries/polygon.hpp> namespace bg = boost::geometry; using V = /*long*/ double; using P = bg::model::d2::point_xy<V>; using B = bg::model::box<P>; int main() { auto verify = [](auto& g) { if (std::string r; !bg::is_valid(g, r)) { std::cout << "Correcting " << r << "\n"; bg::correct(g); } }; V side = 1000; bg::model::polygon<P> square{ {{0, 0}, {0, side}, {side, side}, {side, 0}, {0, 0}}, }; verify(square); std::array steps {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,}; for (unsigned i = 0; i < steps.size(); ++i) { { std::ofstream svg("test" + std::to_string(i) + ".svg"); bg::svg_mapper<P, true, V> mapper(svg, 400, 400); auto clone = square; V ofs = (steps[i] / 5. - 1.0) * side; for (auto& p : boost::make_iterator_range(bg::points_begin(clone), bg::points_end(clone))) bg::add_point(p, P{ofs, ofs}); std::cout << i << ": " << bg::wkt(square) << " " << bg::wkt(clone) << "\n"; mapper.add(B{{-side, -side}, {2 * side, 2 * side}}); //mapper.add(square); // no effect, already within bounding box //mapper.add(clone); // no effect, already within bounding box mapper.map(square, "fill-opacity:0.1;fill:rgb(128,0,0)", 1.0); mapper.map(clone, "fill-opacity:0.1;fill:rgb(0,0,128)", 1.0); } } } Which creates a series of svgs that I can show as a poor man's animation to show that the positioning of the square is constant:
71,244,738
71,245,097
Why does Forward List's methods have "after" version, instead of using List's interface?
insert, emplace, erase and splice from List, are replaced by insert_after, emplace_after, erase_after and splice_after in Forward List. Why is that? *I understand the difference between the methods, I'm asking why do we need a different method to do those operations
insert is defined as "insert before" for most containers, because end() iterator is defined as "one past the end". With insert() as "insert before", you can call it on whole range [begin(), end()], inclusive. If you defined insert() as "insert after", calling it on end() iterator would be Undefined Behaviour. This however requires that container supports biderectional iterators, i.e. iterators that can be decremented. std::forward_list, to limit memory usage only supports forward iterators. With only forward iterator you cannot go back one element to insert before, so the only available operation is "insert after". It has the limitation that it cannot be called on end() iterator, but it's better than nothing.
71,244,903
71,244,957
Is there any benefit at all for explicitly discarding a value via (void) in C
One of the uses of the void keyword in C/C++ is to discard the value of an expression: (void) expr; Is there any benefit at all of the above construct except to avoid "unused parameter" warnings like the below? void foo(int x, int y) { (void) x; //.. }
C++ Because void is not a reference to object type, the result of this cast is a prvalue even if the input was an lvalue. In C++ this is stated in [expr.cast]. Based on that fact, it should force an lvalue-to-rvalue conversion on the expression. For ordinary variables, such a conversion with discarded result has no side effects and can and will be removed by the optimizer, however for volatile lvalues, that conversion is a volatile side-effect and cannot be discarded. However, there's a detail in [expr.static_cast] that throws a fly into the ointment: Any expression can be explicitly converted to type cv void, in which case it becomes a discarded-value expression ([expr.prop]). Thus the result prvalue didn't come from converting the expression, it is simply a void prvalue created out of thin air. The expression still isn't forced to undergo lvalue-to-rvalue conversion (but it might, according to the rules of discarded-value expressions). So in the end there is no effect at all from a cast to void, except possibly changing your compiler's warning heuristics.
71,244,923
71,244,977
Can't use classes not defined yet in c++
So I am coding a program in c++, I got a version of the program that returns the same error: #include <iostream> class A { public: B foo() { return B(); } }; class B { public: A bar() { return A(); } }; int main(int argc, char const *argv[]) { A x = A(); B y = x.foo(); return 0; } But whenever I compile it, it gives me two errors: main.cpp:6:5: error: unknown type name 'B' B foo() ^ main.cpp:8:16: error: use of undeclared identifier 'B' return B(); However I can't just move B above A because I will just get a different error: main.cpp:6:5: error: unknown type name 'A' A bar() ^ main.cpp:8:16: error: use of undeclared identifier 'A' return A(); I am completely stumped on how to solve this so any help would be appreciated!
You need to split declaration and definition. Also, you need to declare B as a class before A uses it. #include <iostream> class B; class A { public: B foo(); }; class B { public: A bar(); }; B A::foo() { return B(); } A B::bar() { return A(); } int main(int argc, char const *argv[]) { A x = A(); B y = x.foo(); return 0; }
71,244,933
71,244,934
Does POSIX require comparison operators for `pthread_key_t`, `pthread_once_t` and `pthread_t`?
The standards document for sys/types.h (https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_types.h.html), says "There are no defined comparison or assignment operators for the following types:", then lists a bunch of types. However, some of the non-arithmetic (or rather not-necessarily arithmetic) types are missing from that list. Notably, pthread_key_t, pthread_once_t and pthread_t are missing. It seems odd to say "these types don't have assignment and comparison operators" when that's already implied for non-arithmetic types. Does this mean that conforming implementations must provide comparison and assignment operators for those 3 types?
TL;DR: Comparison or assignment of pthread_key_t and such may or may not be valid, depending on the particular pthreads implementation. Comparison or assignment of pthread_mutex_t and such must never be valid. No, it doesn't mean that conforming implementations have to provide comparison or assignment operators for those types. In fact, if the implementation defines one of those types as a struct, a comparison operator would be impossible to provide. POSIX builds on C not C++, and C doesn't allow comparison operations on structs. However, conforming implementations aren't required to use structs. If they chose to, they are free to use arithmetic types for example. If they did use an arithmetic type to define one of pthread_key_t, pthread_once_t or pthread_t, then comparison and assignment operations on that type would likely be valid. (However, an application shouldn't rely on them if it wants to be portable). This is not the case with pthread_mutex_t for example. The standard doesn't specify how pthread_mutex_t should be defined, so an implementation could theoretically use an arithmetic type to define pthread_mutex_t. However, the standard is saying here that comparison and assignment operations between instances of pthread_mutex_t must be forbidden. Presumably the reasoning for this is similar to why the C++ standard goes out of it's way to forbid copying instances of std::mutex. Copying a mutex is a nonsensical operation. The same is true for most/all of the other types the standard forbids comparison or assignment of.
71,245,006
71,245,345
What is the most accurate way to measure the time to perform a function, and what is its accuracy?
I'm working on a project that involves recording the time that a certain function takes to run one hundred times. I'm using a solution using the library but I seem to remember that there is a more accurate way that uses the processor's internal timing system for very accurate timing. Is there a better solution, and what's the uncertainty on the result?
Using the chrono library will be your most accurate option likely. There is no way to know the resolution and accuracy of the clock without knowing exactly your setup, but you can assume it's small enough for all practical uses.
71,245,140
71,301,162
How to define a key value pair with values having a max size in c++
I would like to make a dictionary (may be similar to std::multimap) with several values for the same key. The main thing here is that I want the values to have a maximum size(n) and if an (n+1)th value comes, then the 1st value should be removed (like boost::circular_buffer or something). More specifically, I have a struct Struct A{ double id; // key double x, y, z; // value } Then I define std::vector<A> a{}; while (condition) { a = getFromSomeWhere(); //////////// // I DONT KNOW HOW TO STORE THE VALUES in `a` // // THIS IS WHAT I AM LOOKING FOR // //////////// } When calling getFromSomeWhere, assume a gets the following values before the condition becomes false { a1, a2, a3, a4 a1, a3, a4, a5 a2, a4, a6 } The answer I am looking for should be something like { a1.id : a1, a1 // can go to a maximum size of n before removing the 1st a2.id : a2, a2 // can go to a maximum size of n before removing the 1st a3.id : a3, a3 // can go to a maximum size of n before removing the 1st a4.id : a4, a4, a4 // can go to a maximum size of n before removing the 1st a5.id : a5 // can go to a maximum size of n before removing the 1st a6.id : a6 // can go to a maximum size of n before removing the 1st }
Thanks everyone for the replies. I got it solved with help from fCaponetto. #include<iostream> #include <boost/circular_buffer.hpp> #include <map> #include <vector> struct Vis { double x; double y; double z; bool seen; uint id; }; typedef boost::circular_buffer<Vis> VisBuffer; typedef std::shared_ptr<VisBuffer> VisBufferPtr; void makeVisMap(const std::vector<Vis> &b, std::map<uint, VisBufferPtr> &visMap) { unsigned int const max = 500; for (const auto &v : b) { if (!visMap[v.id]) visMap[v.id] = std::make_shared<VisBuffer>(max); visMap[v.id]->push_back(v); } } int main () { Vis s1{}, s2{}, s3{}, s4{}, s5{}; s1.id = 1; s2.id = 2; s3.id = 3; s4.id = 4; s5.id = 5; s1.x = s1.y = s1.z = 1; s2.x = s2.y = s2.z = 2; s3.x = s3.y = s3.z = 3; s4.x = s4.y = s4.z = 4; s5.x = s5.y = s5.z = 5; std::vector<Vis> sv {s1, s2, s3, s4, s5, s2, s3, s4, s4, s4, s4}; std::map<uint, VisBufferPtr> visMap{}; makeVisMap(sv, visMap); return 0; }
71,245,181
71,248,238
How to create a 2d grid in OpenGl windows?
I am trying to print a 2d grid on my entire window. code: float slices(15); std::vector<glm::vec3> vert; std::vector<glm::uvec3> ind; for (int j = 0; j <= slices; j++) { for (int i = 0; i <= slices; i++) { GLfloat x = (float)i / (float)slices; GLfloat y = (float)j / (float)slices; GLfloat z = 0; vert.push_back(glm::vec3(x, y, z)); } } for (int j = 0; j < slices; j++) { for (int i = 0; i < slices; i++) { int row1 = j * (slices + 1); int row2 = (j + 1) * (slices + 1); ind.push_back(glm::uvec3(row1 + i, row1 + i + 1, row2 + i)); ind.push_back(glm::uvec3(row1 + i, row2 + i + 1, row2 + i)); } } {//generate vao and bind bufffer objects} GLuint lenght = (GLuint)ind.size() * 3; glBindVertexArray(vao); glDrawElements(GL_LINES, lenght, GL_UNSIGNED_INT, NULL); This only prints a grid on a fourth of my window (the postivive x,y plane). when I put a negative in front of the i or j in the for loop like so: (GLfloat x = (float)-i/(float)slices; I get a grid in one of the other quadrants of my window. I've tried rendering the gird multiple times by erasing the vector and repopulating it with coordinates for each quadrant but this doesn't seem to work and seems highly inefficient.
Normalized device coordinates are in range [-1.0, 1.0]. Map the coordinates from [0.0,1.0] to [-1.0, 1.0]: vert.push_back(glm::vec3(x, y, z)); vert.push_back(glm::vec3(x * 2.0f - 1.0f, y * 2.0f - 1.0f, z));
71,245,195
71,245,290
How to bubblesort a pointers in the array without changing order of the array
So say I have two arrays intdataArray[10] = {61 34 46 114 73 29 13 93} and int *pointerDataArray[10] which has the pointers of the dataArray in the same respective index. How would I be able to sort the array through pointers and get the sorted array but also while still being able to print the original array. My bubble sort is working but it is also changing dataArray as well. This is the wanted output(correct) dataArray before sort: 61 34 46 114 73 29 13 93 pointerArray before sort: 61 34 46 114 73 29 13 93 dataArray after sort: 61 34 46 114 73 29 13 93 pointerArray after sort: 13 29 34 46 61 73 93 114 This is the output I am getting(wrong) dataArray before sort: 61 34 46 114 73 29 13 93 pointerArray before sort: 61 34 46 114 73 29 13 93 dataArray after sort: 13 29 34 46 61 73 93 114 pointerArray after sort: 13 29 34 46 61 73 93 114 Here is my code #include <iostream> #include <fstream> using namespace std; int readFile(string filename, int dataArray[10], int *pointerDataArray[10]); void pointerSort(int dataArray[],int *pointerDataArray[] , int length); void swapIntPtr(int *p1, int *p2); void displayDataArray(int dataArray[], int length); void displayPointerArray(int *pointerDataArray[], int length); int main() { int dataArray[10] = {}; int *pointerDataArray[10]; int length = readFile("arrayData.txt", dataArray, pointerDataArray); cout << "dataArray before sort: "; displayDataArray(dataArray, length); cout << "pointerArray before sort: "; displayPointerArray(pointerDataArray, length); cout << endl; pointerSort(dataArray, pointerDataArray, length); cout << "dataArray after sort: "; displayDataArray(dataArray, length); cout << "pointerArray after sort: "; displayPointerArray(pointerDataArray, length); } int readFile(string filename, int dataArray[10], int *pointerDataArray[10]) { ifstream inputFile(filename); if (inputFile.is_open()) { int length; inputFile >> length; for (int i = 0; i < length; i++) { inputFile >> dataArray[i]; pointerDataArray[i] = &dataArray[i]; } return length; } return -1; } void pointerSort(int dataArray[],int *pointerDataArray[] , int length){ int i, j; for (i = 0; i < length-1; i++) for (j = 0; j < length-i-1; j++) if (dataArray[j] > dataArray[j+1]) { swapIntPtr(&dataArray[j], &dataArray[j + 1]); } } void swapIntPtr(int *pointer1, int *pointer2) { int pSwap = *pointer1; *pointer1 = *pointer2; *pointer2 = pSwap; } void displayDataArray(int dataArray[], int length){ for (int i = 0; i < length; i++) { cout << dataArray[i] << " "; } cout << endl; } void displayPointerArray(int *pointerDataArray[], int length){ for (int i = 0; i < length; i++) { cout << *pointerDataArray[i] << " "; } }
In your pointerSort function, you're calling the swapIntPtr function in the addresses of both integers. It actually changes the content behind the pointers, i.e., it swaps the integers. Instead, you want to call swapIntPtr with the address of the pointers and the function needs to change the pointers. void swapIntPtr(int **pointer1, int **pointer2) { int* pSwap = *pointer1; *pointer1 = *pointer2; *pointer2 = pSwap; } Aso, make sure to change the declaration on top. Then, you need to change your sort function to run on the pointerDataArray void pointerSort(int dataArray[],int *pointerDataArray[] , int length){ int i, j; for (i = 0; i < length-1; i++) for (j = 0; j < length-i-1; j++) if (*pointerDataArray[j] > *pointerDataArray[j+1]) { swapIntPtr(&pointerDataArray[j], &pointerDataArray[j + 1]); } } The complete code would look like this: #include <iostream> #include <fstream> using namespace std; int readFile(string filename, int dataArray[10], int *pointerDataArray[10]); void pointerSort(int dataArray[],int *pointerDataArray[] , int length); void swapIntPtr(int **p1, int **p2); void displayDataArray(int dataArray[], int length); void displayPointerArray(int *pointerDataArray[], int length); int main() { int dataArray[10] = {}; int *pointerDataArray[10]; int length = readFile("arrayData.txt", dataArray, pointerDataArray); cout << "dataArray before sort: "; displayDataArray(dataArray, length); cout << "pointerArray before sort: "; displayPointerArray(pointerDataArray, length); cout << endl; pointerSort(dataArray, pointerDataArray, length); cout << "dataArray after sort: "; displayDataArray(dataArray, length); cout << "pointerArray after sort: "; displayPointerArray(pointerDataArray, length); } int readFile(string filename, int dataArray[10], int *pointerDataArray[10]) { ifstream inputFile(filename); if (inputFile.is_open()) { int length; inputFile >> length; for (int i = 0; i < length; i++) { inputFile >> dataArray[i]; pointerDataArray[i] = &dataArray[i]; } return length; } return -1; } void pointerSort(int dataArray[],int *pointerDataArray[] , int length){ int i, j; for (i = 0; i < length-1; i++) for (j = 0; j < length-i-1; j++) if (*pointerDataArray[j] > *pointerDataArray[j+1]) { swapIntPtr(&pointerDataArray[j], &pointerDataArray[j + 1]); } } void swapIntPtr(int **pointer1, int **pointer2) { int* pSwap = *pointer1; *pointer1 = *pointer2; *pointer2 = pSwap; } void displayDataArray(int dataArray[], int length){ for (int i = 0; i < length; i++) { cout << dataArray[i] << " "; } cout << endl; } void displayPointerArray(int *pointerDataArray[], int length){ for (int i = 0; i < length; i++) { cout << *pointerDataArray[i] << " "; } }
71,245,261
71,868,328
How can I save a Window form in QTableWidget as it was a matrix?
I'm trying to save a Window form inside a QTableWidget table. int rows = 0; int columns = 0; QTableWidget cellTable; What I'm doing is that I first set the rows and columns cellTable.setRowCount(++rows); cellTable.setRowCount(++columns); For every time I increase the rows, I call this code for(int i = 0; i < rows; i++) cellTable.setCellWidget(rows-1, i, new DatabaseMeasurementType()); For every time I increase the columns, I call this code for(int i = 0; i < rows; i++) cellTable.setCellWidget(i, columns-1, new DatabaseMeasurementType()); It works if I replace the new DatabaseMeasurementType() with new QPushButton(). But then all the fields will be buttons. For the moment, I just want to store a window form inside the setCellWidget. Yes, new DatabaseMeasurementType() is a widget form. Problem: When I call this code (dynamic cast) DatabaseMeasurementType *databaseMeasurementType = static_cast<DatabaseMeasurementType*>(cellTable.cellWidget(row, column)); databaseMeasurementType->show(); Or this code (static cast) DatabaseMeasurementType *databaseMeasurementType = dynamic_cast<DatabaseMeasurementType*>(cellTable.cellWidget(row, column)); databaseMeasurementType->show(); Then it crash. Why? My idea is to have a large 2D matrix where I can store windows forms. Then I only need to call x and y arguments for the 2D matrix to recieve the windows form.
Casting should work if you've inherited from QWidget properly. Casts return nullptr if failed. So, it's safier to check if it's failed or not: if(databaseMeasurementType != nullptr){ //some works with databaseMeasurementType } It's recommended to use qobject_cast if you've written Q_OBJECT macro inside your class. If you want to show your window outside of the table's cell Getting widget and removing it from the table. When you use setCellWidget method, QTableWidget change widget's parent because of memory management. Widgets are shown inside their parents. So, you should change it's parent after getting it and remove it from the table. But QTableWidget::removeCellWidget(int row, int column) removes the widget and deletes it. setCellWidget(row, col, nullptr) also deletes it. So one way to remove the widget without deleting it is wrapping it to another widget. Cloning a widget. You should do it manually. One traditional way is to implement custom QWidget* clone() method, and cloning member-by-member.
71,245,298
71,245,442
How can I store a uint32_t or uint64_t in a void pointer
I have a uint32_t (and in the future it might become uint64_t) variable. There is a function in one of the libraries that I use that allows passing a void pointer to it. How can I pass a uint32_t to this void pointer: uint32_t myEntity = 1242242; // not a pointer; so, error about invalid conversion actor->userData = static_cast<void *>(myEntity); I can't use a pointer to this primitive type because the value can be coming from an argument or similar and since it is a uint, I don't want to use references for it. Is there some way that I can set this value into a void pointer; so that, I can then retrieve it the same way without creating a value in the heap for it to work properly. Otherwise, I will need to manage the destruction of the objects in order to not cause memory leaks.
For what you are attempting, you need to use reinterpret_cast instead of static_cast, eg: uint32_t myEntity = 1242242; actor->userData = reinterpret_cast<void*>(myEntity); uint32_t myEntity = reinterpret_cast<uint32_t>(actor->userData); Since you mention that the value may be changed to a uint64_t in the future, just be aware that you will have to compile your code into a 64bit executable in that case (if you are not already), otherwise void* won't be large enough values that exceed the highest uint32_t value.
71,245,464
71,245,526
Conditional Incrementing Incorrectly
My function int numSteepSegments(const int heights[], int arrSize) { int mile = 0, steep_count = 0; while (mile <= arrSize) { int height = heights[mile]; int height_next = heights[mile + 1]; if ((height + 1000) < height_next) { ++steep_count; } else if ((height - 1000) > height_next) { ++steep_count; } cout << heights[mile] << endl; cout << steep_count << endl; ++mile; } return steep_count; } is spitting out twice as many steep_count than it is supposed to. With the array: 1200, 1650, 3450, 2800, 2900, 1650, 1140, 1650, 1200, and the arrSize = 9, what am I missing? the cout's are: 1200 0 1650 1 3450 1 2800 1 2900 2 1650 2 1140 2 1650 2 1200 3 1746942513 4 What is that last value? It's obviously not in the array, and I can't see it belonging anywhere near the numbers I'm dealing with. What am I not seeing in my conditionals that's causing the wrong increments to steep_count?
C/C++ arrays are zero-based. The indices for an array with arrSize elements range from 0 to arrSize-1. Your loop index mile ranges from 0 to arrSize (inclusive), so heights[mile] is walking off the end of the array. Also, you are indexing heights[mile+1] which would exceed the array limits even if your index were limited to arrSize-1. Try either: changing your loop to range from 0 to arrSize-2 (inclusive), or changing your loop to range from 1 to arrSize-1 and use mile-1 for the first index.
71,246,119
71,246,158
How should header file look like for C++ projects?
I`ve studied C, and now I decided to switch to C++. So, in C, I used #ifndef #endif in my header files. Should I use the same commands in C++? Or are there some alternatives?
Yes, the preprocessor works (mostly) the same way, so you should still use preprocessor directives to guard against including the same code more than once. Any differences in functionality between the preprocessor in C and C++ are likely to be edge cases that are unlikely to be relevant at your current learning level.
71,246,461
71,250,882
Calling function from v8 engine throws error
I am making an application that requires me to call a function within some Javascript code. The problem is, despite looking it up many times, I still get the same error. No matching function for call to 'v8::Object::Get(v8::Local<v8::Context>&, v8::MaybeLocal<v8::String>)' I have looked up on several different posts and even the documentation, yet I can't even start to run the function. Isolate::CreateParams create_params; create_params.array_buffer_allocator = ArrayBuffer::Allocator::NewDefaultAllocator(); Isolate* isolate = Isolate::New(create_params); { Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); Local<Context> context = Context::New(isolate); Context::Scope context_scope(context); std::string fileContent = f.getContents("./src/solutions/6t10.js");; Local<String> source = String::NewFromUtf8(isolate, cv.stringToChar(fileContent), NewStringType::kNormal).ToLocalChecked(); Local<Script> script = Script::Compile(context, source).ToLocalChecked(); MaybeLocal<Value> result = script->Run(context).ToLocalChecked(); Handle<Object> global = context->Global(); MaybeLocal<String> strValue = String::NewFromUtf8(isolate, cv.stringToChar("prob"+std::to_string(pi))); Local<Value> value = global->Get(context, strValue); Handle<Function> func = Handle<Function>::Cast(value); Handle<Value> args[1] = { global->Get(context, String::NewFromUtf8(isolate, ca)) }; MaybeLocal<Value> js_result = func->Call(context, global, 1, args); v8::String::Utf8Value answer(isolate, js_result.ToLocalChecked()); answers+=*answer; } isolate->Dispose(); delete create_params.array_buffer_allocator; If you can't find the problem I'll ask this, how can I turn a LocalString to LocalValue? Thank you :)
(V8 developer here.) @pm100's comment is spot on: Local and MaybeLocal are not interchangeable, a function that needs the former can't deal with the latter. The "Maybe" part of the name indicates that due to some error that may have happened (usually an exception), the value might be nonexistent. The required explicit conversion helps you to ensure that you don't forget to check for this. (Many years ago, V8's API didn't have this distinction, and it was an endless source of bugs in embedder code.) how can I turn a Local to Local? I guess you mean "how can I turn a MaybeLocal into a Local?". There are two options for different scenarios, and your code already contains an example for one of them: MaybeLocal::ToLocalChecked() checks if a value is present, crashes the process if not, and returns a Local otherwise. This is, unsurprisingly, appropriate when you can guarantee that no exception happened, e.g. for string allocations. MaybeLocal::ToLocal(Local* ...) is for cases where you can't guarantee that a value is present (i.e. no exception happened) and you don't want to crash the process. It checks whether a value is present, returns false if not (so you can gracefully handle that case), and populates the Local in the out-parameter otherwise (and returns true). This is typically used for any values returned from JavaScript. As a specific example in your code: js_result.ToLocalChecked() will crash the process if func->Call threw an exception.
71,246,966
71,247,025
How to constrain my template to only accept lambda with specific input & output type?
Inspired by other question to calculate taylor series of a function(Original question), I wrote a template without any constraint to successfully calculate the sum. Here is current code (Template body removed, as @Elliott says it's irrelevant to the point..): #include <iostream> #include <cmath> #include <limits> template<typename ftn> long double Taylor_sum(ftn terms_to_sum) { /* Summation calculation goes here... */ return result; }; int main(){ using namespace std; long double x; cin >> x ; long double series_sum = Taylor_sum([x](unsigned long long int i) -> long double { return /*Taylor term here*/; }); if (!isfinite(series_sum)) cout << "Series does not converge!" << endl; else { cout << "Series converged, its value is : " << series_sum << endl; cout << "Compared to sin : " << sinl(x) << endl; } } Although the code works enough, to study & practice the concept myself, I am trying to constrain the template to accept only lambda with unsigned long long int as a input, and long double as output. Here is my current attempt (which does not compile): template<typename T,integral ARG> concept my_lambda = requires(T t, ARG u) { { return t(u); }; } template<my_lambda ftn> long double Taylor_sum(ftn term) { //The rest is same... I googled various sources, but it seems to me that because the concept is relatively new feature in C++20, there seems less material available. Does anyone know how to constrain my template parameter properly?
I am trying to constrain the template to accept only lambda with unsigned long long int as a input, and long double as output. You can use compound requirements with return-type-requirement: template<typename F> concept my_lambda = requires(F f, unsigned long long int x) { { f(x) } -> std::same_as<long double>; }; template<my_lambda ftn> long double Taylor_sum(ftn term) { //The rest is same... Demo
71,247,107
71,249,174
mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')
I want to use C++ functions in Python program, so I compiled the dynamic library file with the command: cc -fPIC -shared -o encrypt_for_python.so encrypt_for_python.cpp -L/opt/homebrew/Cellar/openssl@1.1/1.1.1l/lib -I/opt/homebrew/Cellar/openssl@1.1/1.1.1l/include -lssl -lcrypto -std=c++11 But when I used it in python file, I got this error: Traceback (most recent call last): File "/Users/debris/Documents/Job/HA/encryption-cpp/test_encrypt.py", line 6, in <module> my_func = CDLL(so_file) File "/Users/debris/miniconda3/lib/python3.9/ctypes/__init__.py", line 382, in __init__ self._handle = _dlopen(self._name, mode) OSError: dlopen(/Users/debris/Documents/Job/HA/encryption-cpp/encrypt_for_python.so, 0x0006): tried: '/Users/debris/Documents/Job/HA/encryption-cpp/encrypt_for_python.so' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/usr/local/lib/encrypt_for_python.so' (no such file), '/usr/lib/encrypt_for_python.so' (no such file) I found mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64'), how can I fix it?
I found this: file ~/miniconda3/bin/python /Users/debris/miniconda3/bin/python: Mach-O 64-bit executable x86_64 By installing python for amd64, I solved this problem.@Alan Birtles Thank you very much.
71,247,774
71,248,070
std::vector move assignment vs move construction: why is the state of 'other' not consistent?
For move construction: After the move, other is guaranteed to be empty(). 1 For move assignment, the oft-quoted: other is in a valid but unspecified state afterwards. 2 Why is the state of other different in these two cases?
There are 2 popular ways to implement move in containers like vector that internally hold a pointer to the data: you can empty this, then copy the pointer (and size and capacity) from other to this and then set other members to nullptr/zero you can swap the data members (the pointers, size and capacity). The standard wants to leave leeway to implementations to do either. These guarantees are the strongest guarantees it can make while allowing either methods of implementation: move constructor: 1st method: leaves other in empty state 2st method (swap): leaves other in empty state move assignment: 1st method: leaves other in empty state 2st method (swap): leaves other as a copy of initial this
71,247,792
71,247,997
Compiler generates call to memcpy from std::copy when pointers are of __restrict type?
The gcc compiler generates call to memcpy when i add __restrict to function parameters. How does compiler/standard library figure out that it can generate calls to memcpy when appropriate? void call_stdcpy_r(int *__restrict p, int *__restrict q, int sz) { std::copy(p, p+sz, q); // generates call to memcpy } void call_stdcpy(int *p, int *q, int sz) { std::copy(p, p+sz, q); // generates call to memmove } As per https://en.cppreference.com/w/cpp/algorithm/copy The behavior is undefined if the source and the destination ranges overlap. Shouldn't the compiler, in principle, generate calls to memcpy all the time? Link to godbolt: https://godbolt.org/z/aKj3Y5K8M
Your quote applies to std::copy_if, not to std::copy. The only requirement for std::copy is that q is not in the range [p,p+sz). The destination range is allowed to overlap and therefore memmove is the only option without additional assumptions, such as introduced by __restrict. __restrict guarantees the compiler that the ranges will not overlap.
71,248,187
71,248,485
Qt Application with layout's, QPushButton and QGraphicsItem
I am trying to draw various shapes like rectangle, ellipse, text etc uisng QGraphicsView and QGraphicsScene. For that I am trying to create an interface where there will be a vertical layout and besides that there will be few buttons. On clicking those buttons, I can show various QGraphicsItem's on screen. I want to create this interface programatically but not using ui. I tried and ended up this way. I wanted buttons on the right side and verticalLayout on the left side and both should filled up the whole screen. Here is my current implementation : Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); QGraphicsScene* scene = new QGraphicsScene(this); QGraphicsView* view = new QGraphicsView(this); view->setScene(scene); QWidget* mainWidget = new QWidget(this); QHBoxLayout *mainLayout = new QHBoxLayout(); QVBoxLayout *buttonLayout = new QVBoxLayout(); QVBoxLayout *vlayout2 = new QVBoxLayout(); vlayout2->addWidget(view); QPushButton *btn1 = new QPushButton("Rectangle"); btn1->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred ); QPushButton *btn2 = new QPushButton("Ellipse"); btn2->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred ); QPushButton *btn3 = new QPushButton("Text"); btn3->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred ); buttonLayout->addWidget(btn1); buttonLayout->addWidget(btn2); buttonLayout->addWidget(btn3); buttonLayout->addStretch(); mainLayout->addLayout(buttonLayout); mainLayout->addLayout(vlayout2); mainWidget->setLayout(mainLayout); } Can anyone guide me ?
Actually, it should work with the hints given in my comments. I made an MCVE to convince myself: #include <QtWidgets> int main(int argc, char **argv) { qDebug() << "Qt Version:" << QT_VERSION_STR; QApplication app(argc, argv); // setup GUI QWidget qMain; qMain.setWindowTitle("Test Box Layout"); qMain.resize(640, 320); QHBoxLayout qHBox; QVBoxLayout qVBoxBtns; QPushButton qBtnRect("Rectangle"); qVBoxBtns.addWidget(&qBtnRect); QPushButton qBtnCirc("Circle"); qVBoxBtns.addWidget(&qBtnCirc); QPushButton qBtnText("Text"); qVBoxBtns.addWidget(&qBtnText); qVBoxBtns.addStretch(); qHBox.addLayout(&qVBoxBtns); QVBoxLayout qVBoxView; QGraphicsView qView; qVBoxView.addWidget(&qView, 1); qHBox.addLayout(&qVBoxView, 1); qMain.setLayout(&qHBox); qMain.show(); // runtime loop return app.exec(); } Output: Thus, there must be something else in OP's code… Unfortunately, OP didn't expose an MCVE. Thus, it's not clear how OP's Widget is instanced. Is it the widget which becomes the main window? Is there another widget where the Widget's instance becomes child of? It's just guessing but the latter would explain what OP described. To confirm my guess, I modified the above code a bit: // setup GUI QWidget qMain0; // main window widget QWidget qMain(&qMain0); // child widget of main window widget ⋮ qMain.setLayout(&qHBox); qMain0.show(); // runtime loop return app.exec(); Please, note that qMain is now a child of qMain0 but there is no layout which adjusts the size of qMain when qMain0 is resized. Hence, the size of view stays the initial size while the window is resized.
71,248,543
71,248,600
How come std::distance() doesn't work for rvalues?
For example: std::list <int> list1 = {1, 2, 3, 4, 5}; auto first = list1.begin(); std::cout << std::distance(--first, ++first); The output is 0. Strange enough, if we change --first to first--, the output becomes 5 (although here it should be 0, as it returns first). What am I missing?
The order in which the arguments in a function call are evaluated is unspecified. --first may execute first or ++first may execute first. If the former is the case, the decrement has undefined behavior, because decrementing a .begin() iterator is not allowed. Since one of the allowed execution orders has undefined behavior, your whole program has undefined behavior. Using first-- instead doesn't change anything about this.
71,248,851
71,249,222
How could one delay a function without the use of sleep / suspending the code?
I need to delay a function by x amount of time. The problem is that I can't use sleep nor any function that suspends the function (that's because the function is a loop that contains more function, sleeping / suspending one will sleep / suspend all) Is there a way I could do it?
If you want to execute some specific code at a certain time interval and don't want to use threads (to be able to suspend), then you have to keep track of time and execute the specific code when the delay time was exceeded. Example (pseudo): timestamp = getTime(); while (true) { if (getTime() - timestamp > delay) { //main functionality //reset timer timestamp = getTime(); } //the other functionality you mentioned } With this approach, you invoke a specific fuction every time interval specified by delay. The other functions will be invoked at each iteration of the loop. In other words, it makes no difference if you delay a function or execute it at specific time intervals.
71,249,100
71,249,342
strange compiler error with friend function
The following code is rejected by GCC/Clang/MSVC though it seems to be able to compile. class B { }; class C : private B { friend B& to_B(C& c) { return static_cast<B&>(c); } }; class D : private C { friend C& to_C(D& d) { return static_cast<C&>(d); } friend B& to_B(D& d) { return to_B(to_C(d)); } }; Why the compilation fails? GCC error message: <source>:12:12: error: 'class B B::B' is private within this context 12 | friend B& to_B(D& d) { | ^ <source>:3:7: note: declared private here 3 | class C : private B { | ^
I can't find chapter and verse to back it up, but C's private inheritance makes B completely private if it's looked up from within the definition of D. (Essentially, B is first looked up in the inheritance chain, and since name lookup stops at the first match, it is private to C. The global definition is never considered.) You can make it compile by modifying the name lookup procedure with an explicit scope: friend ::B& to_B(D& d)
71,249,234
71,249,557
How to perform chmod recursively?
How can I change permissions to 0777, at runtime, of a folder and all its subfolders, recursively? The code is in c++, mac. I'm including <sys/stat.h> which has chmod, however there's no documentation on how to do it recursively.
The simplest and most portable way would be to use the std::filesystem library that was added in C++17. In there, you'll find a recursive_directory_iterator and many other handy classes and functions for dealing with filesystem specific things. Example: #include <iostream> #include <filesystem> // see notes about these two lines at the bottom namespace fs = std::filesystem; // -"- void chmodr(const fs::path& path, fs::perms perm) { fs::permissions(path, perm); // set permissions on the top directory for(auto& de : fs::recursive_directory_iterator(path)) { fs::permissions(de, perm); // set permissions std::cout << de << '\n'; // debug print } } int main() { chmodr("your_top_directory", fs::perms::all); // perms::all = 0777 } However, recursive_directory_iterator has an issue when there are too many directories involved. It may run out of file descriptors because it needs to keep many directories open. For that reason, I prefer to use a directory_iterator instead - and collect the subdirectories to examine for later. Example: #include <iostream> #include <stack> #include <utility> #include <filesystem> // see notes about these two lines at the bottom namespace fs = std::filesystem; // -"- void chmodr(const fs::path& path, fs::perms perm) { std::stack<fs::path> dirs; dirs.push(path); fs::permissions(path, perm); do { auto pa = std::move(dirs.top()); // extract the top dir from the stack dirs.pop(); // and remove it for(auto& de : fs::directory_iterator(pa)) { // save subdirectories for later: if(fs::is_directory(de)) dirs.push(de); else fs::permissions(de, perm); } } while(!dirs.empty()); // loop until there are no dirs left } int main() { chmodr("your_top_directory", fs::perms::all); } You can read about the std::filesystem:: (fs:: in the code above) functions, classes and permission enums used in the example in the link I provided at the top. In some implementations, with only partial C++17 support, you may find filesystem in experimental/filesystem instead. If that's the case, you can replace the above #include <filesystem> namespace fs = std::filesystem; with the #ifdef jungle I've provided in this answer.
71,249,356
71,249,400
Is it possible to enumerate functions in C++?
Suppose I have some functions which have the same parameters and datatype, and I want to push them into a std::vector and enumerate them. Is it possible to do this? Pseudocode: typedef int func(int, int); int add(int a, int b) { return a + b; } int minus(int a, int b) { return a - b; } vector<func> operations = {add, minus}; for (auto operation : operations) { // do something }
What you are missing in your code is a * in std::vector<func> because you want to store pointers to the function: #include <vector> #include <functional> #include <iostream> typedef int func(int, int); int add(int a, int b) { return a + b; } int minus(int a, int b) { return a - b; } int main() { std::vector<func*> operations = {add, minus}; for (auto operation : operations) { } } You could also use std::function for that purpose: #include <vector> #include <functional> int add(int a, int b) { return a + b; } int minus(int a, int b) { return a - b; } int main() { std::vector<std::function<int(int,int)>> operations = {add, minus}; for (auto operation : operations) { // do something } } Related question: How can I store function pointer in vector?
71,249,522
71,249,566
Virtual destructor needed for class which is both derived and base?
Say we have the following: #include <iostream> struct A { virtual ~A() { std::cout << "destr A\n"; } }; struct B : A { // no need to be virtual? ~B() { std::cout << "destr B\n"; } }; struct C : B { ~C() { std::cout << "destr C\n"; } }; Now, I create an instance of C and assign it to a pointer of its base class B. int main() { B* b = new C{}; delete b; return 0; } The output is: destr C destr B destr A What surprised me a little is that the object gets destroyed correctly (all three destructors are called). According to the output, I would say ~B() is a virtual destructor: ~B() dispatches to ~C(), then ~B() finishes and finally, ~A() is called. Is this statement correct? I know that, if some function of a base class is virtual, the function in the derived class which overrides the one in the base class is virtual as well. I did not know that was true for destructors as well. Is ~B() virtual because I declared ~A() with the virtual function specifier?
Is ~B() virtual because I declared ~A() with the virtual function specifier? Yes. Per https://timsong-cpp.github.io/cppwp/n4659/class.dtor#10: If a class has a base class with a virtual destructor, its destructor (whether user- or implicitly-declared) is virtual.
71,249,538
71,249,604
Why i++ uses less memory than ++i while retaining same speed?
I was solving George And Accommodation and submitted two accepted versions of code with slight difference. Compiler used: GNU C++14 Version A (Time: 15ms, Memory: 4kb) #include <iostream> using namespace std; int main(){ int n = 0, p = 0, q = 0, a = 0; cin >> n; while(n--){ cin >> p >> q; if(q - p >= 2) a++; } cout << a; return 0; } Version B (Time: 15ms, Memory: 8kb) #include <iostream> using namespace std; int main(){ int n = 0, p = 0, q = 0, a = 0; cin >> n; while(n--){ cin >> p >> q; if(q - p >= 2) ++a; } cout << a; return 0; } I always thought ++a is faster and always use it in my loops. However, why does it require more memory while time being exactly the same? I know the general difference being one increments earlier, and one increments after.
This is just a random effect. It has no meaning. The memory used is probably measured in pages, so the stack just happened to cross a page boundary in the second case. A page is typically 4kb. Whether you use a++; or ++a; is completely irrelevant if a is a built-in type. The compiler will compile it to exactly the same machine instructions. It doesn't matter which of these you use in a loop increment either. Neither is faster than the other or uses more memory than the other. (Of course this is assuming you enable optimizations. Without optimizations enabled, there might be some weird effects, but measuring speed or memory without enabled optimizations is pointless.)
71,249,944
71,495,190
How to link libs in CLion?
I'm using CLion as my IDE for C++ development and I'm trying to get Eigen included. How do I do this? I've downloaded and unzipped Eigen and placed it in C:/ (Which I've read online is the path where CMake looks for libs when you use find_library()) In the CMakeLists.txt I've added find_library(Eigen3 3.4 REQUIRED NO_MODULE) add_executable(Lecture03 main.cpp) target_link_libraries (Lecture03 Eigen3::Eigen) But then it can't find Eigen, I get the following error when reloading my CMakeLists: CMake Error at CMakeLists.txt:6 (find_library): Could not find Eigen3 using the following names: 3.4 My question is, what did I do wrong? Did I place the Eigen folder in the wrong directory? Can I change where CMake looks for libs in CLion?
The solution ended up being to use include_directories(C:/CPP_Libs/Eigen3) in my CMakeLists.txt, and #include <Eigen/Dense> in whichever file needs it
71,250,007
71,250,138
Why can my constant not be used to create my array?
I want to make an array that holds a number of tile objects (called Tile) but it's saying that my constant int, numTiles, cannot be used as a... constant int... what? The code I'm having issues with is here (error on line 5): // Variables - Tilemap const int tileSize = 32; const int screenWidth = GetScreenWidth(); const int numTiles = screenWidth / tileSize; Tile tilemap[numTiles]; The error I get is as follows: expression must have a constant value the value of variable "numTiles" (declared at line 14) cannot be used a constant I'm not sure why I'm getting this issue as it looks like numTiles is definitely a constant int... Can someone explain what the problem is here?
Thanks to the people in the comments of the post for explaining this to me: The variables are calculated at runtime when they need to be calculated at compile time (this was due to my usage of GetScreenWidth(), which obviously cannot run during compilation).
71,250,043
71,250,397
How to store qt containers inside qt containers
Do I understand right that it does not make real sense to have QVector<QSharedPointer<QVariantHash>> and that I can stick just to: QVector<QVariantHash> due to implicit sharing? Honestly, using STL, I would never do like this and would have std::vector<std::shared_ptr<std::unordered_map<...>>>. UPDATE: My question is about performance. I understand that it's different ways of storing objects.
No, those have different behaviour. The QVector<QVariantHash> is still copy-on-write, so copies of the vector only share elements up to the first modification, whereas so long as you leave the pointers alone, the QVariantHashs pointed-to by the elements of QVector<QSharedPointer<QVariantHash>> will still be the same objects. As an aside, I would avoid relying on implicit sharing, because it is really easy to fall into undefined behaviour, with pointers or references being invalidated from underneath you. I would also caution against overuse of shared pointers. Almost always you can have one thing with unique ownership which hands out references.
71,250,053
71,257,322
How to get value by field name in MYSQL xdevapi 8.0 connector c++
For connector c++ 1.1, in this example, it's quite easy to get values by specifying the column name (or alias name). But when I upgraded to version 8.0 xdevapi, I found this feature is no longer supported. #include <mysqlx/xdevapi.h> using namespace std; using namespace mysqlx; Session sess(<server_url>); auto result = sess.sql("SELECT * FROM student").execute(); Row row = result.fetchOne(); cout << row[0] << endl; // <- ok cout << row["ID"] << endl; // <- can compile but garbage output cout << row.get("ID") << endl; // <- cannot compile I know the column names can be retrieved from result.getColumn(n).getColumnLabel(), but IMO it's useless. A "field" -> "index" mapping can really help the developers. I'm new to C++, so the following sentenses maybe too naive. Here's the possible ways I guess: construct a STL map to record the mapping iterate through the result.getColumns(), then check the getColumnLabel() something like indexOf? But I find result.getColumns() does not support this method since it's a deque
There is no way, at the moment, to get the column value using name. A way is, as you suggest, a map with the name / index pair. Something like this would work: SqlResult sql_res = sess.sql("select * from table").execute(); std::map<std::string, size_t> columns; auto fill_columns = [&sql_res, &columns]() -> void { size_t idx = 0; for (auto &el : sql_res.getColumns()) { columns.emplace(std::make_pair(el.getColumnLabel(), idx++)); } }; fill_columns(); And then, using it: for(auto row : sql_res) { std::cout << "a:" << row[columns["a"]] << std::endl; std::cout << "b:" << row[columns["b"]] << std::endl; }
71,250,562
71,257,546
Why WinApi SendHttpRequest may be slow on VirtualBox machine
Testing my app on few machines show that WinApi HttpSendRequest performs slow sometimes. On non virtual machine it takes ~100-~300 ms, same results on virtual machine sending the same request through curl. But sending request with HttpSendRequest on virtual machine with Win10 takes ~5s and on Win7 - ~20s. Here is a sample code: ... auto success = OpenInternet(); if (success) { success = AssignHandles(request); } if (success) { success = SendHttpRequest(request); } ... bool OpenInternet(bool reset) { if (openHandle == NULL) { openHandle = InternetOpen(userAgent.c_str(), openAccessType, proxyConfigString, NULL, 0); if (openHandle != NULL) { if (IsWindowsVistaOrGreater()) { BOOL enable = TRUE; InternetSetOption(openHandle, INTERNET_OPTION_HTTP_DECODING, &enable, sizeof(enable)); } } } return (openHandle == NULL); } bool AssignHandles(Request& request) { bool success = AssignConnectHandle(request); if (success) { success = AssignRequestHandle(request); if (!success) { InternetCloseHandle(request.connectHandle); } } return success; } bool AssignConnectHandle(Request& request) { request.connectHandle = InternetConnect( openHandle, request.host.c_str(), (request.secure ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT), NULL, NULL, INTERNET_SERVICE_HTTP, 0, INTERNET_NO_CALLBACK); return (request.connectHandle == NULL); } bool AssignRequestHandle(Request& request) { LPCWSTR pszAcceptTypes[] = {acceptTypeHeader.c_str(), NULL}; request.requestHandle = HttpOpenRequest( request.connectHandle, GetRequestMethod(request.type).c_str(), request.path.c_str(), httpVersion.c_str(), NULL, pszAcceptTypes, GetRequestFlags(request.secure), NULL); return (request.connectHandle == NULL); } bool SendHttpRequest(Request& request) { std::wstring headers = PrepareHeaders(request); bool success = HttpSendRequest( request.requestHandle, headers.empty() ? NULL : headers.c_str(), (uint32_t)headers.size(), (request.data != NULL) ? (void*)request.data->c_str() : NULL, (request.data != NULL) ? (uint32_t)request.data->length() : 0) != 0; return success; }
Probably because VirtualBox has a network implementation that's a little bulky(ish). For me, it made a whole new network adapter (Virtual Ethernet, basically). What it does is, the VM thinks it's connected to Ethernet. Then the VirtualBox backend redirects it through my normal Wi-Fi. These kinds of things are very complicated, so it must be just the overhead of translating the virtual Ethernet to Wi-Fi. (If you are actually using Ethernet physically, replace all my "Wi-Fi" words with "physical Ethernet") EDIT: curl probably uses a different API for network calling that doesn't use WinAPI, so it could just be a WinAPI problem as well