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
72,306,706
72,307,118
How to use Intel C/C++ Classic Compiler in VSCode debugger?
I'm setting up a C environment on a Mac to implement some numerical codes for my phd. I'm using the Intel C/C++ Classic compiler instead of the default clang. So far, I manage to generate some debugging information evoking a command like icc -std=c17 -o code -g code.c When I call the Run and Debug option in VSCode it show 2 options to me: C++(GDB/LLDB) and C++ (Windows). When I click the first one it shows 2 more options: C/C++: clang build and debug active file or C/C++: gcc build and debug active file. It does not show anything related to the Intel Classic Compiler. How do I use this compiler to debug with Intel C/C++ Classic compiler inside the VSCode environment? Thanks in advance!
I think you are mixing compiling and debugging up, according to the documentation, choosing C/C++: gcc build and debug active file from the list of detected compilers on your system is just helping you to generate some configuration like this: { "version": "2.0.0", "tasks": [ { "type": "shell", "label": "C/C++: g++ build active file", "command": "/usr/bin/g++", "args": ["-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}"], "options": { "cwd": "/usr/bin" }, "problemMatcher": ["$gcc"], "group": { "kind": "build", "isDefault": true }, "detail": "Task generated by Debugger." } ] } If you want to debug in VSCode, what you need to do is simply adding this configuration to your launch.json: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "(gdb) Launch", "type": "cppdbg", "request": "launch", "program": "${workspaceFolder}/code", "args": [], "stopAtEntry": false, "cwd": "${fileDirname}", "environment": [], "externalConsole": false, "MIMode": "gdb", "setupCommands": [ { "description": "Enable pretty-printing for gdb", "text": "-enable-pretty-printing", "ignoreFailures": true }, { "description": "Set Disassembly Flavor to Intel", "text": "-gdb-set disassembly-flavor intel", "ignoreFailures": true } ] } ] }
72,306,739
72,306,854
bit manipulation to specific subset
Considering the following code snippet. for (int state = 1; state < 1 << n; state ++ ) if (state & 1) for (int t = state; t; t &= t - 1) The first for-loop is to enumerate all subsets of n elements, but what subset does the t represent.
for (int t = state; t; t &= t - 1) This loop is removing the least-significant 1 bits from t, one by one. So an initial value of state like 63 (binary 111111) would go to 62 (111110), then 60, (111100), 56 (111000), 48 (110000), 32, (100000), and finally 0.
72,306,753
72,307,070
g++ cannot change include path with -I
I'm on kubuntu using g++ 7.5.0 / GNU make for C++. My file structure: bin | .o files header |archiver.h source |main.cpp |archiver.cpp makefile I want my source files to be able to detect header files without having to do #include "../header/archiver.h". I've tried using: g++ -I/header but this does not work. I get the error: g++: fatal error: no input files. makefile that was requested CC = g++ CFLAGS = -c -Wall objects = bin/main.o bin/archiver.o all : $(objects) $(CC) -o build $(objects) bin/%.o : source/%.cpp $(CC) $(CFLAGS) $? mv *.o bin .PHONY : clean clean : rm -rf all $(objects)
The command g++ -I<header-dir> doesn't change any default settings for the g++ include search paths with subsequent calls, as you seem to assume. You'll need to pass that compiler flag for each individual c++ call, which are issued by make according the rules defined in your makefile. The latter is what you need to adapt, best using a pre-defined makefile variable like CXXFLAGS or CXXINCLUDES (check the GNU-make documentation for details). For your specific case CFLAGS = -c -Wall -I./header should work.
72,307,566
72,308,036
should a function return the pointer of a newly created object, or a unique_ptr of that object?
I remember watching Herb Sutter on conference talks, some years ago, trying to make a guideline along these lines: if a function creates a new object on the heap, then it should always return it as a unique_ptr. The idea was that it was safer, and intention-revealing. To my surprise, this guideline seems to be missing from the CPP core guidelines today. Has there been an issue with this guideline? Has it been abandoned? Should we write functions like: MyObject *create(Params p) { return new MyObject(p); } or unique_ptr<MyObject> create(Params p) { return make_unique<MyObject>(p); }
It is covered in the C++ Core guidelines under I11: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#i11-never-transfer-ownership-by-a-raw-pointer-t-or-reference-t What you should be doing is: MyObject create(Params p) { return MyObject(p); } Only when you absolutely need reference mechanics, i.e. when constructing a polymorphic object and returning a base class, should you do this: unique_ptr<MyObject> create(Params p) { return make_unique<MyObject>(p); }
72,307,679
72,308,749
Creating Your Own Matrix Class
I am creating my own Matrix class. I wrote a copy constructor, but it works correctly only for primitive classes (namely, memory allocation for data). How can the constructor be rewritten (it is possible to overload the new operator) so that it works correctly not only for primitive data types, but also for complex structures (for example, complex classes). Class fields: template <typename T> class Matrix { private: T *data = nullptr; size_t rows; size_t cols; Copy constructor: Matrix(const Matrix &other) : data(new T[other.rows * other.cols]), rows(other.rows), cols(other.cols) { for (int i = 0; i < rows * cols; i++) { data[i] = other.data[i]; } } It is forbidden to use STL containers, all memory management is manually Destructor ~Matrix() { rows = 0; cols = 0; delete[] data; }
You can simply make the memory management automatic: #include <cstddef> template <typename T, std::size_t rows, std::size_t cols> class Matrix { public: Matrix() { } T * operator[](std::size_t x) { return data[x]; } private: T data[rows][cols]{}; }; But if you must use dynamic memory allocations: #include <cstddef> #include <type_traits> #include <cstring> #include <initializer_list> #include <utility> template <typename T, std::size_t rows, std::size_t cols> class Matrix { private: T *data{new T[rows * cols]}; public: Matrix() { } ~Matrix() { delete[] data; data = nullptr; // crash on use after free } template<typename U> Matrix(std::initializer_list<std::initializer_list<U>> list) : data (static_cast<T*>(operator new[](sizeof(T) * rows * cols, static_cast<std::align_val_t>(alignof(T))))) { std::size_t i = 0; for (auto &lst : list) { std::size_t j = 0; for (auto &t : lst) { std::construct_at<T>(&(*this)[i][j], std::forward<const U>(t)); ++j; } ++i; } } Matrix(const Matrix &other) { *this = other; } Matrix(T &&other) : data(other.data) { other.data = nullptr; } Matrix & operator=(const Matrix &other) { if constexpr (std::is_aggregate_v<T>) { memcpy(data, other.data, sizeof(T) * rows * cols); } else { for (std::size_t i = 0; i < rows; ++i) { for (std::size_t j = 0; j < cols; ++j) { (*this)[i][j] = other[i][j]; } } } return *this; } Matrix operator=(Matrix &&other) { swap(data, other.data); return *this; } const T * operator[](std::size_t x) const { return &data[x * cols]; } T * operator[](std::size_t x) { return &data[x * cols]; } }; #include <iostream> int main() { Matrix<int, 2, 2> a{{{1, 2}, {3, 4}}}; Matrix<int, 2, 2> b{a}; std::cout << b[0][0] << " " << b[0][1] << std::endl; std::cout << b[1][0] << " " << b[1][1] << std::endl; } Note: This is a column Matrix. If you want a Row matrix you have to swap indexes around.
72,307,874
72,308,048
Why disabling copy elision for std::atomic doesn't work using C++17?
For std::atomic the copy constructor is deleted, and this should only compile with C++17 and higher due to copy elision: std::atomic<int> t_int = 1; I expected that it does not compile using -fno-elide-constructors flag, but it still compiles: https://godbolt.org/z/nMvG5vTrK Why is this?
C++17 doesn't simply say that the previously optional return value optimizations are now mandatory. The actual description of the language changed so that there is no creation of a temporary object anymore in the first place. So, since C++17, there is no constructor call that could be elided anymore. Hence it makes sense that -fno-elide-constructors doesn't add any temporary creation. That would be against the language rules. Before C++17 the language describes that a temporary object is created from which the variable is initialized and then adds that a compiler is allowed to elide this temporary. Therefore, whether -fno-elide-constructors is used or not, the compiler is behaving standard compliant by eliding or not eliding the temporary copy.
72,308,295
72,309,369
save IR signals(like 89KZ3H) into a variable(like string)
I want to start an IR remote controlled car, but since I'm not very good at programming with c++ in Visual studio code I wanted to know how to save a signal that is transmitted by the remote control to my arduino and save it into a string variable. I copied this code from internet to get the IR signals: #include <Arduino.h> #include <IRremote.h> int RECV_PIN = 11; IRrecv irrecv(RECV_PIN); decode_results results; void setup() { Serial.begin(9600); irrecv.enableIRIn(); // Start the receiver } void loop() { if (irrecv.decode(&results)) { Serial.println(results.value, HEX); irrecv.resume(); // Receive the next value } } Now, how do I save "results.value, HEX" like into a String?
String myString = String(results.value);
72,309,122
72,309,432
Is it okay to pass a temporary regex object to regex_match?
Most examples using boost::regex_match construct the boost::regex object before calling match; e.g. boost::regex pattern("(...)"); boost::smatch match; if (boost::regex_match(text, match, pattern)) { // use the match object here } (See https://github.com/boostorg/regex/tree/develop/example/snippets for other examples). However, suppose I instead pass a temporary regex object to regex_match, e.g. boost::smatch match; if (boost::regex_match(text, match, boost::regex("(...)"))) { // use the match object here } Is this code valid? That is, does the boost::regex object need to live as long as the boost::smatch object, or does that lifetime requirement only apply to the matched string? The code appears to work fine, but I'm worried that I may run into trouble if the smatch object internally keeps a reference to the regular expression used for matching. I couldn't find this explicitly documented at https://www.boost.org/doc/libs/1_79_0/libs/regex/doc/html/index.html, but it's possible I have missed it.
Firstly, from a design perspective it wouldn't make sense to store a reference to boost::regex in boost::smatch. Having a look at the implementation confirms that: template <class BidiIterator, class Allocator> class match_results { // ... vector_type m_subs; // subexpressions BidiIterator m_base; // where the search started from sub_match<BidiIterator> m_null; // a null match boost::shared_ptr<named_sub_type> m_named_subs; // Shared copy of named subs in the regex object int m_last_closed_paren; // Last ) to be seen - used for formatting bool m_is_singular; // True if our stored iterators are singular };
72,309,221
72,311,285
This assignment is designed to explore linked lists so you will implement a singly linked-list to hold a collection of bids loaded from a CSV file
I need help please It keeps giving me the same number and not a different one. Bid LinkedList::Search(string bidId) { // FIXME (6): Implement search logic // special case if matching node is the head // make head point to the next node in the list //decrease size count //return // start at the head of the list // keep searching until end reached with while loop (next != nullptr // if the current node matches, return it // else current node is equal to next node //return bid Node* temp = head; Node* holder = new Node; holder->bid.bidId = ""; while (temp != nullptr) { cout << temp->bid.bidId << endl; if (temp->bid.bidId == bidId) { return temp->bid; } temp = temp->next; return holder->bid; } }
Just remove everything with a holder. And at the end throw an exception when nothing was found. Alternatively return std::optional<Bid>.
72,309,935
72,314,832
Zero sized array in struct managed by shared pointer
Consider the following structure: struct S { int a; int b; double arr[0]; } __attribute__((packed)); As you can see, this structure is packed and has Zero sized array at the end. I'd like to send this as binary data over the network (assume I took care of endianity). In C/C++ I could just use malloc to allocate as much space as I want and use free later. I'd like this memory to be handled by std::shared_ptr. Is there a straight forward way of doing so without special hacks?
I'd like this memory to be handled by std::shared_ptr. Is there a straight forward way of doing so without special hacks? Sure, there is: shared_ptr<S> make_buffer(size_t s) { auto buffer = malloc(s); // allocate as usual auto release = [](void* p) { free(p); }; // a deleter shared_ptr<void> sptr(buffer, release); // make it shared return { sptr, new(buffer) S }; // an aliased pointer } This works with any objects that are placed in a malloced buffer, not just when there are zero-sized arrays, provided that the destructor is trivial (performs no action) because it is never called. The usual caveats about zero-sized arrays and packed structures still apply as well, of course.
72,310,048
72,310,359
std::filesystem::last_write_time to FILETIME
I am attempting to send over the FILETIME of a file to my server, which is written in C#. From there, I can use the function DateTime.FromFileTime() to parse the file's time. I am aware there is a Win32 API called GetFileTime(), but in the interest of saving lines of code, I was wondering if it was possible to use std::filesystem and somehow convert it to FILETIME? I have tried casting like so: f.lastwrite = entry.last_write_time(); But this cast is not allowed, unfortunately. Is it possible to convert the last_write_time() to FILETIME so it can be sent over, or is that not possible?
You can convert the last_write_time() value to std::time_t via std::chrono::file_clock::to_sys() and std::chrono::system_clock::to_time_t(), and then convert time_t to FILETIME using simple arithmetic. For example: #include <windows.h> #include <filesystem> #include <chrono> void stdFileTimeType_to_FILETIME(const std::filesystem::file_time_type &ftime, FILETIME &ft) { std::time_t t = std::chrono::system_clock::to_time_t( std::chrono::file_clock::to_sys(ftime) ); ULARGE_INTEGER ul; ul.QuadPart = (t * 10000000LL) + 116444736000000000LL; ft.dwLowDateTime = ul.LowPart; ft.dwHighDateTime = ul.HighPart; } FILETIME lastwrite; stdFileTimeType_to_FILETIME(entry.last_write_time(), lastwrite); UPDATE: Alternatively, have a look at GetFileAttributesEx(), which can retrieve FILETIME ftLastWriteTime (amongst other things) given a file path string instead of an open file HANDLE, as with GetFileTime(): #include <windows.h> #include <filesystem> #include <chrono> void getLastWriteTime_as_FILETIME(const std::filesystem::path &filePath, FILETIME &ft) { WIN32_FILE_ATTRIBUTE_DATA fad; if (GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &fad)) ft = fad.ftLastWriteTime; else ft.dwLowDateTime = ft.dwHighDateTime = 0; } FILETIME lastwrite; getLastWriteTime_as_FILETIME(entry.path(), lastwrite);
72,310,464
72,310,747
Is there a more idiomatic way to specialise behaviour using flags passed via template?
Apologises for the ambiguous title. Here is my code: struct LowHigh { }; struct HighLow { }; template < class LookupScheme> struct ladder_base { using value_type = price_depth; using ladder_type = std::vector< value_type >; template < class T > struct lookup; template <> struct lookup< LowHigh > { static constexpr auto func = std::upper_bound< ladder_type::iterator, value_type >; }; template <> struct lookup< HighLow > { static constexpr auto func = std::lower_bound< ladder_type::iterator, value_type >; }; void insert(value_type v) { auto iter = lookup< LookupScheme >::func(std::begin(data_), std::end(data_), v); data_.insert(iter, std::move(v)); } protected: std::vector< value_type > data_; }; } // namespace detail struct bid_ladder : detail::ladder_base< detail::HighLow > { }; struct offer_ladder : detail::ladder_base< detail::LowHigh > { }; I'm specialising lookup::func depending on the scheme passed as a template type. There are currently only two possible schemes: LowHigh & HighLow. This has the effect of determining how the underlying vector is sorted. Is there a more idiomatic/cleaner way to express this logic?
These algorithms take a comparison object as their last parameter - so you can use that to your advantage. template < class Compare > struct ladder_base { using value_type = price_depth; using ladder_type = std::vector< value_type >; void insert(value_type v) { auto iter = std::upper_bound(data_.begin(), data_.end(), v, Compare{} ); data_.insert(iter, std::move(v)); } protected: std::vector< value_type > data_; }; And then use ladder_base<std::less<>> or ladder_base<std::greater<>>, depending on which sort order you want. Note that std::lower_bound and std::upper_bound are not antonyms, so your original wasn't really correct. lower_bound gives you the first element >= x and upper_bound gives you the first element > x. So changing from one to the other doesn't change your sort order (both require increasing order), only the comparison object affects that. For instance: std::vector<int> v = {1, 3, 5, 7}; auto i = std::lower_bound(v.begin(), v.end(), 3); // this is the 3 auto j = std::upper_bound(v.begin(), v.end(), 3); // this is the 5 Note that the vector is sorted in increasing order, but both calls are perfectly well-formed. If you wanted a reverse sort, you'd have to pass std::greater{} in as the comparison object (as I'm showing). But either way, you want to use std::upper_bound - regardless of sort order.
72,310,617
72,310,756
template argument deduction for a allocating Matrix
I have this Matrix class that allocates the data on the heap and a helper class M that is a Matrix with the data as C-style array, no allocation. Template argument deduction works for the helper class automatically. But not for the Matrix class. I can construct a Matrix from that with template argument deduction: M m{{{1, 2}, {3, 4}}}; Matrix a{M{{{1, 2}, {3, 4}}}}; What I'm looking for is to get rid of the helper class so the following works: Matrix a{{{1, 2}, {3, 4}}}; Here is a working example with the helper class: https://godbolt.org/z/46vEqbvax #include <cstddef> #include <type_traits> #include <cstring> #include <initializer_list> #include <utility> #include <memory> #include <cassert> #include <algorithm> template <typename T, std::size_t rows, std::size_t cols> class M { public: const T * operator[](std::size_t x) const { return data[x]; } T * operator[](std::size_t x) { return data[x]; } T data[rows][cols]{}; }; template <typename T, std::size_t rows, std::size_t cols> class Matrix { private: T *data{new T[rows * cols]}; public: Matrix() { } ~Matrix() { delete[] data; data = nullptr; // crash on use after free } Matrix(const Matrix &other) { *this = other; } Matrix(T &&other) : data(other.data) { other.data = nullptr; } Matrix & operator=(const Matrix &other) { if constexpr (std::is_aggregate_v<T>) { memcpy(data, other.data, sizeof(T) * rows * cols); } else { for (std::size_t i = 0; i < rows; ++i) { for (std::size_t j = 0; j < cols; ++j) { (*this)[i][j] = other[i][j]; } } } return *this; } Matrix operator=(Matrix &&other) { swap(data, other.data); return *this; } const T * operator[](std::size_t x) const { return &data[x * cols]; } T * operator[](std::size_t x) { return &data[x * cols]; } Matrix(const M<T, rows, cols>& other) { if constexpr (std::is_aggregate_v<T>) { memcpy(data, other.data, sizeof(T) * rows * cols); } else { for (std::size_t i = 0; i < rows; ++i) { for (std::size_t j = 0; j < cols; ++j) { (*this)[i][j] = other[i][j]; } } } } Matrix(M<T, rows, cols>&& other) { if constexpr (std::is_aggregate_v<T>) { memcpy(data, other.data, sizeof(T) * rows * cols); } else { for (std::size_t i = 0; i < rows; ++i) { for (std::size_t j = 0; j < cols; ++j) { std::swap((*this)[i][j], other[i][j]); } } } } }; //template <typename T, std::size_t rows, std::size_t cols> //Matrix(M<T, rows, cols>) -> Matrix<T, rows, cols>; #include <iostream> int main() { Matrix a{M{{{1, 2}, {3, 4}}}}; Matrix b{a}; std::cout << b[0][0] << " " << b[0][1] << std::endl; std::cout << b[1][0] << " " << b[1][1] << std::endl; }
You can get rid of helper class M and have your Matrix template parameters automatically deduced by changing the type of your constructor parameters to (l- and r-value references to) C-style arrays: //Matrix(const M<T, rows, cols>& other) { Matrix(const T (&other)[rows][cols]) { // ... same implementation ... } //Matrix(M<T, rows, cols>&& other) { Matrix(T (&&other)[rows][cols]) { // ... same implementation ... } Demo
72,311,314
72,311,361
C++ variadic template: typeid of it, way to optimize
So, I learn variadic templates and usage of it. Now I made that code below. The question is does some other methode exist for getting type of "Params" without any arrays or inilialized_list? template<class Type, class... Params> void InsertInVector(std::vector<Type>& v, const Params&... params) { const auto variadic = {typeid(Params).name()...}; if (typeid(Type).name() != *variadic.begin()) { throw std::runtime_error("TYPES ARE NOT THE SAME!"); return; } v.insert(v.end(), {params...}); }
In C++17 and later, you can do something like this: template<class Type, class... Params> void InsertInVector(std::vector<Type>& v, const Params&... params) { static_assert((std::is_convertible_v<Params, Type> && ...)); v.insert(v.end(), {params}); }
72,311,585
72,311,744
Variables in Google Test Fixtures
Why TEST_F can access the member variable in a class without using any scopes? e.g., class ABC : public ::testing::Test { protected: int a; int b; void SetUp() { a = 1; b = 1; } virtual void TearDown() { } }; TEST_F(ABC, Test123) { ASSERT_TRUE(a == b); } why it can directly access a and b, instead of using ABC::a or ABC::b? Does the fixture create a variable for class ABC? if so, should it be ASSERT_TRUE(abc.a == abc.b); instead of ASSERT_TRUE(a == b);?
TEST_F is a macro which defines a new class publicly inheriting from the first argument (in this case, 'ABC'). So it has access to all public and protected members of the test fixture class. You can inspect the source for this macro in the header file to get a better idea of what it's doing. TEST_F macro, which if you follow the macro path leads you to... GTEST_TEST_ macro
72,311,819
72,315,649
Doxygen generates a strange error for base class function about nonexisting function in the derived class
Here is the code: namespace Test { /// Base class class Base { public: /// Method foo /// @param a ParamA /// @param b ParamB virtual void foo(char a, int b); /// Method foo /// @param a ParamA /// @param b ParamB /// @param c ParamC virtual void foo(char a, int b, char c); /// Method foo /// @param m ParamM template<typename T> void foo(std::vector<T> m) { } }; /// Derived class class Derived : public Base { public: using Base::foo; /// Method foo /// @param a ParamA /// @param b ParamB void foo(char a, int b) override; }; } If this code will be processed with Doxygen. We get the strange error: Error: argument 'm' of command @param is not found in the argument list of Test::Derived::foo(typename T) (warning treated as error, aborting now) If commenting line using Base::foo; the Doxygen correctly processing this file. Looks like a bug in Doxygen, but is anybody know a workaround for that?
With the doxygen versions till doxygen 1.9.1 (inclusive) I was able to reproduce the problem. The problem is gone with the versions 1.9.2 and higher. The current doxygen version is 1.9.4 (5d15657a55555e6181a7830a5c723af75e7577e2) The solution for this problem is to update your doxygen version to the current doxygen version.
72,311,949
72,311,987
Visual Studio keeps using wWinMain() as the entry point instead of the main() function I want it to
I started my Visual Studio project as a windows application, however I've come to realize that if I want to use GLFW then I'm supposed to open a GLFW window instead of a standard wWinMain window. I have a wWinMain function but since it kept running every time I ran the program instead of my int main() function with the GLFW window test code inside, I changed the name of the wWinMain function in the hopes that when building the program it would defer to the main() function I wrote. However it hasn't worked and instead I keep getting the same error: error LNK2019: unresolved external symbol WinMain referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ) How do I get it to stop looking for the wWinMain function and just run the main() one instead? The only solution that has worked so far is to rename my main() function to wWinMain and have it accept all the variables but do nothing with them and just run my code as normal inside, however this doesn't seem optimal. I've also tried the answer suggested here but that always opens a command window with the GLFW window whereas with the wWinMain function by default would run without one except when I specifically used AllocConsole(), so I suspect the answer suggested there isn't actually the correct solution for my issue. Ive also tried the solution shown here but that just doesn't work for me? idk maybe I'm implementing it wrong
Windows knows two types of program that are relevant to you: Console and graphical. Console programs automatically get a console (and you can get their output in a command line, for example) and their entry point is main or wmain. Graphical programs don't get a console automatically, which is what you want. They don't automatically create any windows either; you'll have to do that manually (i.e. with GLFW like you want to). Their entry point is always WinMain or wWinMain. You'll have to choose one, you can't mix-and-match. Just put your GLFW code in wWinMain. main is meaningless in a graphical Windows program, you should remove it. There's nothing wrong with not using the parameters passed to wWinMain - if you don't need them, that's fine. main also takes parameters that you don't currently use (but main is a little special since you can omit the unused parameters).
72,312,246
72,312,468
C++ - Undefined reference to octomap::OcTree::OcTree(double)'
I'm trying to use the library octomap and have installed according to the instructions in their GitHub. However, when I try to build and run this simple code with VSCode build task (with g++) I get the error: undefined reference to `octomap::OcTree::OcTree(double)' and other undefined references to Octomap related code. VSCode recognizes that the library is installed (it suggests it when I type #include <...> ) and gives me more information about the octomap functions when I hover over them. #include <iostream> #include <octomap/octomap.h> #include <octomap/OcTree.h> using namespace std; int main() { octomap::OcTree tree(0.1); cout << "Hello, World!! \n"; return 0; } Octomap header files are in /usr/local/lib/octomap/octomap/include/octomap from what I can tell. I haven't coded with C++ a lot, so this might be just a newbie mistake that I'm missing. I've tried several approaches but still can't get it to work. What am I missing here? Thanks in advance.
your problem is the program wasn't linked with octomap library use cmake and include some lines like: find_package(octomap REQUIRED) include_directories(${OCTOMAP_INCLUDE_DIRS}) target_link_libraries(${OCTOMAP_LIBRARIES}) or from command line with g++ <source files> -loctomap -loctomath refer : http://wiki.ros.org/octomap
72,313,352
72,313,480
Timing a class function in C++
A previous post, Timing in an elegant way in C, showed a neat method for profiling using a wrapper function. I am trying to use one of the profiler to profile my class functions. #include <cmath> #include <string> #include <chrono> #include <algorithm> #include <iostream> template<typename Duration = std::chrono::microseconds, typename F, typename ... Args> typename Duration::rep profile(F&& fun, Args&&... args) { const auto beg = std::chrono::high_resolution_clock::now(); std::forward<F>(fun)(std::forward<Args>(args)...); const auto end = std::chrono::high_resolution_clock::now(); return std::chrono::duration_cast<Duration>(end - beg).count(); } The profiler works for a normal function, but I am struggling to pass a class function to the profiler. #include "Profiler.h" int main() { Config projConfig = Config(projConfigDir); std::string imagePath = projConfig.GetTIFF(); ImageVector images_vec = Image::LoadImagesVec(imagePath); Detector detector = Detector(&projConfig); auto time = profile<std::chrono::seconds>(&Detector::DetectImages, detector, images_vec); //detector.DetectImages(images_vec); // if ran without profiler std::string _detectTime("DetectImages time elapsed: " + std::to_string(time)); Logger::Info(_detectTime.c_str()); } I am unable to compile the code. I got the following error message. term does not evaluate to a function taking 2 arguments Because I cannot pass pointer to a bounded function to the profiler, I tried passing in the function, the object instance to call the function and the function's arguments (not sure if this is the correct way). But I suspect that the profiler is not implemented to handle class methods. If so, how should I modify the profiler so that it can accept class functions?
You can use std::bind to create a callable object for invoking a class method on a class object. Then you can pass this callable to your profile function as you would pass any function/lambda. Note that using std::bind supports also fixing one or more of the method parameters. Using std::placeholders (as you can see below) allows to specify them only when invoking the binded callable object. See the example below: #include <chrono> #include <iostream> #include <functional> #include <thread> #include <string> template<typename Duration = std::chrono::microseconds, typename F, typename ... Args> typename Duration::rep profile(F&& fun, Args&&... args) { const auto beg = std::chrono::high_resolution_clock::now(); std::forward<F>(fun)(std::forward<Args>(args)...); const auto end = std::chrono::high_resolution_clock::now(); return std::chrono::duration_cast<Duration>(end - beg).count(); } struct MyClass { void Run(std::string const & s, double d) { std::cout << "My id: " << id << ", MyClass::Run(" << s << ", " << d << ")" << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(100)); } int id{ 333 }; }; int main() { MyClass c; // Run without profiling: c.Run("without", 2.3); // Run with profiling: auto f = std::bind(&MyClass::Run, &c, std::placeholders::_1, std::placeholders::_2); auto time = profile<std::chrono::milliseconds>(f, "with", 23); std::cout << "time: " << time << std::endl; return 0; } Output: My id: 333, MyClass::Run(without, 2.3) My id: 333, MyClass::Run(with, 23) time: 109
72,313,410
72,321,334
Why do I need multiple mutexes?
I am currently looking at a code example below (also can be found here). #include <iostream> #include <thread> #include <vector> #include <mutex> std::mutex m_a, m_b, m_c; int a, b, c = 1; void update() { { // Note: std::lock_guard or atomic<int> can be used instead std::unique_lock<std::mutex> lk(m_a); a++; } { // Note: see std::lock and std::scoped_lock for details and alternatives std::unique_lock<std::mutex> lk_b(m_b, std::defer_lock); std::unique_lock<std::mutex> lk_c(m_c, std::defer_lock); std::lock(lk_b, lk_c); b = std::exchange(c, b+c); } } int main() { std::vector<std::thread> threads; for (unsigned i = 0; i < 12; ++i) threads.emplace_back(update); for (auto& i: threads) i.join(); std::cout << a << "'th and " << a+1 << "'th Fibonacci numbers: " << b << " and " << c << '\n'; } Here, I am wondering why this example uses multiple mutexes m_a, m_b, m_c. For instance, Can I only use m_a, m_b and do the following? { std::unique_lock<std::mutex> lk(m_a); a++; } { std::unique_lock<std::mutex> lk(m_b); b = std::exchange(c, b+c); } Or, can I only use m_a and do the following? { std::unique_lock<std::mutex> lk(m_a); a++; } { std::unique_lock<std::mutex> lk(m_a); b = std::exchange(c, b+c); } What is the advantage of using multiple mutexes? I found that all three works identically on my computer. Thank you in advance!
Assume you have more code, code that modifies only b and code that only reads only c. Now both of those can run in parallel. If you only have one mutex protecting b and c as a pair then they would block each other. Overall this looks like an example how to acquire multiple locks and other code that shows why multiple locks would be a good thing are simply missing for simplicity sake.
72,313,808
72,381,654
cannot convert 'ListNode*' to 'ListNode**' C++
#include <bits/stdc++.h> using namespace std; struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; void printList(ListNode *head) { ListNode *curr = head; while (curr != NULL) { cout << curr->val; curr = curr->next; } } int main() { ListNode *head[5]; ListNode *node; head[0] = new ListNode(1,NULL); for (int i = 1; i < 5; i++) { head[i] = new ListNode(i + 1, head[i - 1]); } node = head[5]; //cannot convert 'ListNode*' to 'ListNode**' printList(node); return 0; } How should i pass last node as single pointer to function ? i am not able to convert node in double pointer to single pointer variable.
Like Armin pointed out in the comments, you are referencing the array beyond the range. if you replace node = head[5]; with node = head[4]; //this is the 5th element of the array. you would probably get the output you were expecting.
72,314,094
72,315,521
What is the Difference between accessing a Pointer whose value is Null and accessing what it points to?
I've heard that accessing a pointer whose value is null is safe since you are not setting any data to it or from it, you are just accessing it. But I also heard that accessing what it points to (when it's null) isn't safe, why is that? If you are accessing to what it points to (when it's null) aren't you accessing nothing? I think that there shouldn't be any issues with that unless you are setting values to something from it. I've heard that from many people tho I never experienced any crashes or bugs related to that (when reading data from inside a pointer that is null), when I catch an exception I just let it be since I'm not setting any data from it to something. Is that ok? int x; int* px = &x; int* pn = nullptr; if (px==px) { do something;}
The sample code (as it's exposed by OP in this moment) got a bit confusing. Thus, I would like to add some examples to the accepted answer what's allowed and what not: #include <iostream> int main() { int x = 0; // make some storage int* px = &x; // px initalized with address of x -> OK. int* pn = nullptr; // pn initialized with nullptr -> OK. if (px == px) { /* ... */ } // senseless but -> OK. if (px == pn) { /* ... */ } // -> OK. std::cout << *px; // dereference a valid pointer -> OK. std::cout << *pn; // dereference a null pointer -> UNDEFINED BEHAVIOR! px = pn; // assign a (null) pointer -> OK. std::cout << *px; // dereference a null pointer -> UNDEFINED BEHAVIOR! // ...and finally a common bug... int* py = nullptr; // -> OK. { int y = 1; // storage with limited life-time -> OK. py = &y; // assign address of storage -> OK. } // scope end -> life-time of y ends -> OK. // Attention! This makes py dangling (pointing to released storage). if (py /* != nullptr*/) { // This doesn't help. py is not a null pointer. std::cout << *py; // access after end of life-time -> UNDEFINED BEHAVIOR! } } Output of Compiler (g++ 11.2): g++ -std=c++17 -O2 -Wall -pedantic -pthread main.cpp # && ./a.out # Compile but don't exec. It contains UNDEFINED BEHAVIOR! main.cpp: In function 'int main()': main.cpp:8:10: warning: self-comparison always evaluates to true [-Wtautological-compare] 8 | if (px == px) { /* ... */ } // senseless but -> OK. | ~~ ^~ ~~ Demo on coliru
72,314,253
72,314,789
How COVERITY cov-build coverage mechanism works?
I am new to a c/c++ and I have recently came across coverity static analysis tool and at the build end I can see that it says number of files that got emitted and it will also have a percentage of files emitted. I just want to know how it concluded that this is the percentage. Because if we can calculate the total files they are way more Please help me if somebody has any Idea on this.
When cov-build reports its final status, something like: 933 C/C++ compilation units (62%) are ready for analysis (example taken from this random build-log.txt), it means that the Coverity compiler (cov-emit) successfully compiled 933 files. The percentage 62% means there was a larger number of compilation attempts (in this case, approximately 1504), but 1504-933=511 of them failed to compile, and hence will not be analyzed. To deal with failed compilation, look in build-log.txt for "[ERROR]". You will see lines like: [ERROR] 5 errors detected in the compilation of "../src/tests/common_check.c". with specific errors listed above that line. You might be able to figure out a workaround on your own based on the errors; otherwise, you could ask Coverity Support for help. If the total number of files (here, ~1504) seems too small, then probably you are missing a compiler configuration, and therefore cov-build is failing to recognize invocations of your normal compiler. In build-log.txt, look for lines that say "EXECUTING:", and if you see a command line for the normal compiler, and it is not followed by "COMPILING:", then that's the problem. Use cov-configure to add compiler configurations; see the Command Reference for usage details. For some more information about cov-build, see the Synopsys article Coverity "cov-build" finishes with "No files emitted" for C/C++ code. For a mostly tool-agnostic overview of why static analysis tools do "build capture" at all, see the SO question When using a SAST tool, why do we have to use a "build wrapper" for compiled languages (e.g. C/C++)?.
72,314,747
72,315,075
What can be done to prevent misleading assigment to returned value?
After many years of using C++ I realized a quirk in the syntax when using custom classes. Despite being the correct language behavior it allows to create very misleading interfaces. Example here: class complex_arg { double r_; double phi_; public: std::complex<double> value() const {return r_*exp(phi_*std::complex<double>{0, 1});} }; int main() { complex_arg ca; ca.value() = std::complex<double>(1000., 0.); // accepted by the compiler !? assert( ca.value() != std::complex<double>(1000., 0.) ); // what !? } https://godbolt.org/z/Y5Pcjsc8d What can be done to the class definition to prevent this behavior? (Or at the least flag the user of the clas that the 3rd line is not really doing any assignment.) I see only one way out, but it requires modifying the class and it doesn't scale well (to large classes that can be moved). const std::complex<double> value() const; I also tried [[nodiscard]] value() but it didn't help. As a last resort, maybe something can be done to the returned type std::complex<double> ? (that is, assuming one is in control of that class) Note that I understand that sometimes one might need to do (optimized) assign to a newly obtained value and passe it to yet another function f( ca.value() = bla ). I am not questioning this usage per se (although it is quite confusing as well); I have the problem mostly with ca.value() = bla; as a standalone statement that doesn't do what it looks.
Ordinarily we can call a member function on an object regardless of whether that object's value category is an lvalue or rvalue. What can be done to the class definition to prevent this behavior? Prior to modern C++ there was no way prevent this usage. But since C++11 we can ref-qualify a member function to do what you ask as shown below. From member functions: During overload resolution, non-static member function with a cv-qualifier sequence of class X is treated as follows: no ref-qualifier: the implicit object parameter has type lvalue reference to cv-qualified X and is additionally allowed to bind rvalue implied object argument lvalue ref-qualifier: the implicit object parameter has type lvalue reference to cv-qualified X rvalue ref-qualifier: the implicit object parameter has type rvalue reference to cv-qualified X This allows us to do what you ask for a custom managed class. In particular, we can & qualify the copy assignment operator. struct C { C(int) { std::cout<<"converting ctor called"<<std::endl; } C(){ std::cout<<"default ctor called"<<std::endl; } C(const C&) { std::cout<<"copy ctor called"<<std::endl; } //-------------------------v------>added this ref-qualifier C& operator=(const C&) & { std::cout<<"copy assignment operator called"<<std::endl;; return *this; } }; C func() { C temp; return temp; } int main() { //---------v---------> won't work because assignment operator is & qualified func() = 4; }
72,314,918
72,315,205
Does future in c++ corresponding to promise in javascript?
I am a c++ programmer and tried to study std::future and std::promise these days. When I randomly search some information about future/promise, I found some discussion about future/promise in javascript and promise in javascript has then function. In c++, even though std::future don't have then function now, but some proposal have mentioned it. So, there are two question: does std::future in c++ corresponding to promise in javascript? if 1 is true, why they confused future and promise?
Yes. std::future<T> stands for a future result of T, i.e. the object will at some point in the future hold a T. std::promise<T> is an object promising to provide a T at some point in the future. Which language got the naming right is debatable.
72,315,517
72,315,543
How to write a function which returns complex in C++?
I am trying to do numerical calculations with C++. Here is the sample code #include <complex> using namespace std; complex<double> complexDo(float a, float b){ return (a+b,a-b); } int main(){ cout << "complexDo="<<complexDo(3,2) <<'\n'; return 0; } The terminal will show after compiling complexDo=(1,0) But I expect to appear like (5, 1), and what is the problem here? Or this way of writing is not valid in C++?
The expression (a+b,a-b) is equivalent to (a-b) because it's just a parenthesized use of the common comma expression. To create an object you must use curly-braces {} as in return {a+b,a-b};
72,316,273
72,316,459
Call constructor inside a call to another constructor
Suppose I have classes A, B: class A { int a; public: A(int a) : a(a) { } }; class B { A a; public: B(A a) : a(a) { } }; And I want to create an instance of B as: int i = 1; B b(A(i)); But when I actually try to use b, I get the problem described here. That is, b is not an instance of B, it's a function that returns an object of type B. However, it's a different case from the linked question, and I can't figure out why it's happening here. I could create B as: int i = 1; A a(i); B b(a); Or even as: B b(A(1)); And it'll work. However, in the real case the first option requires too many lines, and the second option requires very long line (because instead of int I have an object which needs to be constructed, and I have a chain of some objects). How can I create the int in his own line, and then create A and B in the same line?
The problem is that B b(A(i)); is a function declaration and not a declaration for a variable named b of type B. This is due to what is called most vexing parse. In particular, the statement: B b(A(i)); //this is a declaration for a function named `b` that takes parameter of type A and has no return type the above is a declaration for a function named b that takes one parameter of type A and with return type of B. To solve this, you can either use curly braces {} or double () to solve this: Method 1 Use {} around A(i). //----v----v------->declares a variable of type B and is not a function declaration B b{A(i)}; Method 2 Use double parenthesis (()). //-v--------v------>declares a variable of type B and is not a function declaration B b( (A(i)) );
72,316,393
72,316,460
(Windows)Can I get the program to be changed or be stopped while it is running?
I am now writing a win32 program in C++. I want to show my running process on the window, just like time is flowing. For example, this code int a=0; for(int i=0;i<10;i++) { a++;//The change in "a" can be seen on the window. Sleep(1*1000); } But I've found that if I want to show this process, like clicking a button and a changing number appears on the screen, then the program needs to be running all the time. At this point, I don't have a way to do anything else, like clicking on another button. So I realized I needed an operation that could interrupt the current process. But I went through a lot of information and found that only the fork() function of the Linux system can meet my needs. But I'm using Windows now, so what other ways can I achieve this? Sincerely look forward to your reply.
You want to create a timer with SetTimer. Then watch for the WM_TIMER messages and update the screen then. This is the standard way of achieving what you described.
72,317,263
72,317,339
Output of map of set custom objects c++
So I have a map that has user defined keys and the values in it are sets of objects too. So I'm trying to write some print function but I have no idea how to do that. (I'm kind of new to maps and sets). My problem function: void print() const { for (auto& itr : my_mmap) { std::cout << "Key for this set:" << itr.first << "\n\n"; for (int i = 0; i< itr.second.size(); i++) { std::cout << itr.second[i] << std::endl; } } } Here's my class: #include <iostream> #include <map> #include <string> #include <tuple> #include <utility> #include <set> class Enclosing { private: class Key { int m_number; std::string m_name; public: Key(int num, std::string name) :m_number(num), m_name(std::move(name)) {}; bool operator<(const Key& rhs) const { return std::tie(m_number, m_name) < std::tie(rhs.m_number, rhs.m_name); } friend std::ostream& operator<<(std::ostream& os, const Key& k) { return os << '{' << k.m_number << ',' << k.m_name << '}'; } }; class Nested { std::string m_str; double m_dbl; bool m_boolean; public: Nested(std::string str, double dbl, bool boolean) :m_str(std::move(str)), m_dbl(dbl), m_boolean(boolean) {}; friend std::ostream& operator<<(std::ostream& os, const Nested& n) { return os << '{' << n.m_str << ',' << n.m_dbl << ',' << n.m_boolean << '}'; } }; std::multimap<Key, std::set<Nested>> my_mmap; public: template <class... Args> void add_new_object_to_mmap(Args&&... args) { my_mmap.emplace(std::piecewise_construct, std::forward<Args>(args)...); } /* THAT PROBLEM FUNCTION */ void print() const { for (auto& itr : my_mmap) { std::cout << "Key for this set:" << itr.first << "\n\n"; for (int i = 0; i< itr.second.size(); i++) { std::cout << itr.second[i] << std::endl; } } } static Enclosing& get_singleton() { static Enclosing instance; return instance; } }; } So the problem is that I am getting an error "no operator "[]" match these operands". How can I output my map and set in the best way?
The problem is that we cannot use indexing on a std::set. Thus itr.second[i] is not valid because itr.second is an std::set. To solve this you can use a range-based for loop as shown below: for (const auto&elem:itr.second) { std::cout << elem << std::endl; }
72,317,296
72,317,347
how to deal with a function pointer problem?
i'm implementing a normal function pointer. so this is the function that i want to call: WndDyn* Punkt2d::pEditPunkt(WndInfo& wi, Int32 AnzSichtChar, Bool WithUnit, const DecimalsConf& DecConf) { WynDyn_callback Dyncallback; Dyncallback.AnzSichtChar = AnzSichtChar; Dyncallback.WithUnit = WithUnit; Dyncallback.DecConf = DecConf; return &(DlgZeile(wi) + pEditAll(Dyncallback, &pEditFeldX)//pEditFeldX(AnzSichtChar, WithUnit, DecConf) + FntXUnit(2) + pEditFeldY(AnzSichtChar, WithUnit, DecConf) ); } After defining the function that needs to be called i defined my callee as follow: WndDyn* pEditAll(WynDyn_callback& Dyncallback, WndDyn* (func_Call) (WynDyn_callback)) { return func_Call(Dyncallback); } And last of all this is the function that needs to be called using the callee function: WndDyn* Punkt2d::pEditFeldX(WynDyn_callback Dyncallback) { return &Edit(pNewStrDataLink(m_x, DLUC_Length, Dyncallback.DecConf), Dyncallback.AnzSichtChar) .WithSelAllOnFocus(True); } My actuall problem is that my compiler is underlining the function pEditFeldX in this line pEditAll(Dyncallback, pEditFeldX) in the function pEditpunkt and showing me this Error: Severity Code Description Project File Line Suppression State Error C3867 'Punkt2d::pEditFeldX': non-standard syntax; use '&' to create a pointer to member Severity Code Description Project File Line Suppression State Error (active) E0167 argument of type "WndDyn (Punkt2d::)(WynDyn_callback Dyncallback)" is incompatible with parameter of type "WndDyn ()(WynDyn_callback)"
Because pEditFeldX is a member function you can't just call pEditFeldX(Dyncallback). You must call the function on some Punkt2d object, using e.g. meinPunkt2d.pEditFeldX(Dyncallback). If you write pEditFeldX(Dyncallback) inside the Punkt2d class then it means (*this).pEditFeldX(Dyncallback). The compiler adds (*this). to save some typing. A function pointer only points to a function. It doesn't point to a function and an object. It points to pEditFeldX, not meinPunkt2d.pEditFeldX. You must specify the Punkt2d object when you call it. To remember that a Punkt2d must be specified, a function pointer which points to a member function is declared as this: WndDyn* (Punkt2d::*func_Call)(WynDyn_callback) and called as this: meinPunkt2d.*func_Call(Dyncallback); If the function pointer is &pEditFeldX then meinPunkt2d.*func_Call(Dyncallback) is the same as meinPunkt2d.pEditFeldX(Dyncallback) This doesn't apply to static member functions. Static member functions can be used with normal function pointers since no object is required. It is not quite clear what you are trying to do, but if I understand it right, I think that std::function would be able to solve your problem std::function is able to store anything which can be called, including "half of a function call" like you seem to want. std::bind can make these "half function calls". You could use them like this: // in pEditPunkt pEditAll(Dyncallback, std::bind(&CPunkt2d::pEditFeldX, this, std::placeholders::_1)) // in pEditAll WndDyn* pEditAll(WynDyn_callback& Dyncallback, std::function<WndDyn* (WynDyn_callback)> (func_Call) (WynDyn_callback)) { return func_Call(Dyncallback); }
72,317,757
72,318,013
How to properly use >> to get columns of an input file in cpp?
I'm pretty new to cpp and I've been struggling on this for hours, none of my research attempts were lucky. I have a few .txt files with the following structure: 07.07.2021 23:11:23 01 08.07.2021 00:45.44 02 ... I want to create two arrays, one containing the dates and one containing the times. However all I've accomplished so far are arrays containing the last element of each column and the rest is empty (Example see below). The Code looks like this: std::vector<string> txt_to_time(std::ifstream raw, int num, int what){ std::vector<string> date(num); std::vector<string> time(num); std::vector<string> irrelevant(num); string str; for (int i=0; i<num; i++) { while (std::getline(raw,str)) { raw >> date[i] >> time[i] >> irrelevant[i]; } } if (what == 0) { return time; } return date; } I think I am messing something up in the while-loop but I don't really know how to fix it. When I try to print every element of the vector the output I get is 10:45:22 (int) 0 Thanks for spending time to read my question, every answer is appreciated!
Your issue is that you use while and std::getline for no reason. Combining std::getline and << leads to issues, and you also try to read whole file into first elements of your vectors because of the while loop. Since unsuccessful read will return empty string (which are already in your vectors), you can skip any checks if read was successful and just do: for (int i=0; i<num; i++) { raw >> date[i] >> time[i] >> irrelevant[i]; }
72,318,794
72,319,491
How to use clock_cast?
I would like to convert time points from different clocks. Currently I follow the suggestion from here. static auto ref_sys_clk = std::chrono::system_clock::now(); static auto ref_std_clk = std::chrono::high_resolution_clock::now(); auto to_sys_clk(std::chrono::high_resolution_clock::time_point tp) { //return std::chrono::clock_cast<std::chrono::system_clock::time_point>(tp); return ref_sys_clk + std::chrono::duration_cast<std::chrono::system_clock::duration>(tp - ref_std_clk); } How can I utilize clock_cast for this purpose. Currently I use Visual Studio 2019.
std::chrono::high_resolution_clock does not participate in the std::chrono::clock_cast facility. The reason for this is that high_resolution_clock, has no portable relationship to any human calendar. It might have one on some platforms, notably if it is a type alias for system_clock. But it definitely does not on all platforms. Here is a list of clocks that participate in the clock_cast infrastructure: std::chrono::system_clock std::chrono::utc_clock std::chrono::tai_clock std::chrono::gps_clock std::chrono::file_clock Any user-written clock that supplies the static member functions to_sys/from_sys, or to_utc/from_utc. See the Update for C++20 section of this answer for an example of how to add these functions for your custom clock. Any clock that does not have the static member functions to_sys/from_sys, or to_utc/from_utc will fail to compile when used in a clock_cast as either the source or destination. Here is an example use of clock_cast being used to convert from a system_clock-based time_point to a utc_clock-based time_point at a precision of milliseconds. auto t = sys_days{July/1/2015} - 500ms; auto u = clock_cast<utc_clock>(t);
72,319,088
72,322,687
C++ prioritize data synchronization between threads
I have a scenario, where I have a shared data model between several threads. Some threads are going to write to that data model cyclically and other threads are reading from that data model cyclically. But it is guaranteed that writer threads are only writing and reader threads are only reading. Now the scenario is, that reading data shall have higher priority than writing data due to real time constraints on the reader side. So it is not acceptable that e.g. a writer is locking the data for a too long time. But a lock with a guaranteed locking time would be acceptable (e.g. it would be acceptable for the reader to wait max 1 ms until the data is synchronized and available). So I'm wondering how this is achievable, because the "traditional" locking mechanisms (e.g. std::lock) wouldn't give those real time guarantees.
The way I would approach this is to have two identical copies of the dataset; call them copy A and copy B. Readers always read from copy B, being careful to lock a reader/writer lock in read-only mode before accessing it. When a writer-thread wants to update the dataset, it locks copy A (using a regular mutex) and updates it. The writer-thread can take as long as it likes to do this, because no readers are using copy A. When the writer-thread is done updating copy A, it locks the reader/writer lock (in exclusive/writer-lock mode) and swaps dataset A with dataset B. (This swap should be done by exchanging pointers, and is therefore O(1) fast). The writer-thread then unlocks the reader/writer-lock (so that any waiting reader-threads can now access the updated data-set), and then updates the other data-set the same way it updated the first data-set. This can also take as long as the writer-thread likes, since no reader-threads are waiting on this dataset anymore. Finally the writer-thread unlocks the regular mutex, and we're done.
72,319,906
72,321,752
How to use an argument as return value in gmock
I have the following call: EXPECT_CALL(myMock, myFunction(someSpecifiedParameter, _, _)) .WillOnce(DoAll(SaveArg<2>(&bufferSize), Return(make_pair(Success, bufferSize)))); I'm trying to return whatever value that is passed as the second _ as my second element in the pair. Is it the best (or at least right) way to do it? This bufferSize variable was declared in the test class. EDIT: Putting in other words: Suppose I have the following: class object{ pair<int, int> f(int x); } object obj; constexpr int fixedValue = 5; EXPECT_CALL(obj, f(_)).WillOnce( Return(make_pair(fixedValue, <PARAMETER PASSED TO F>));
Your way is right, you deanonymize the value in the third parameter. In my opinion using a lambda or a custom actions is the more preferable way. A stored lambda or an action can be reused in other expectations. EXPECT_CALL(myMock, myFunction(someSpecifiedParameter, _, _)) .WillOnce(WithArgs<0, 2>([](Type1 Success, Type2 bufferSize) { return make_pair(Success, bufferSize); })); or ACTION_P2(ReturnPair, Success, bufferSize) { return make_pair(Success, bufferSize); } EXPECT_CALL(myMock, myFunction(someSpecifiedParameter, _, _)) .WillOnce(WithArgs<0, 2>(ReturnPair)); More specialized thus less preferable EXPECT_CALL(myMock, myFunction(someSpecifiedParameter, _, _)) .WillOnce(WithArg<2>([](Type2 bufferSize) { return make_pair(someSpecifiedParameter, bufferSize); })); or ACTION_P(ReturnPair, bufferSize) { return make_pair(someSpecifiedParameter, bufferSize); } EXPECT_CALL(myMock, myFunction(someSpecifiedParameter, _, _)) .WillOnce(WithArg<2>(ReturnPair));
72,319,915
72,364,662
Why can't `std::experimental::make_array` use `std::reference_wrapper`?
template <class D, class...> struct return_type_helper { using type = D; }; template <class... Types> struct return_type_helper<void, Types...> : std::common_type<Types...> { static_assert( // why can't I use reference wrappers? std::conjunction_v<not_ref_wrapper<Types>...>, "Types cannot contain reference_wrappers when D is void" ); }; template <class D = void, class... Types> constexpr std::array<typename return_type_helper<D, Types...>::type, sizeof...(Types)> make_array(Types&&... t) { return {std::forward<Types>(t)...}; } void foo() { int x = 7355608; auto arr = make_array(std::ref(x)); // does not compile } Why does std::experimental::make_array() have a static_assert() that disallows use of std::reference_wrapper when the type of the array is automatically deduced? Creating an array of reference wrappers is otherwise perfectly legal, that is the compiler has no problem with auto arr2 = std::array<decltype(std::ref(x)),1>{std::ref(x)};
Checking the proposal N3824 confirms my initial suspicion. Namely, the static_assert check was added to explicitly disallow type deduction of a std::array<std::reference_wrapper<T>, N> from make_array, because the proposal’s author has deemed this usage error-prone.1 That is, with the following code: auto x = 42; auto a = make_array(std::ref(x)); users could reasonably expect the type of a to be std::array<int&, 1>, because std::ref behaves similarly in other contexts. In reality std::array<int&, 1> does not name a valid type and cannot be constructed, so the danger of this confusion is minimal. Still, the author found it worth erring on the side of caution here, and making the API maximally defensive. Consequently, if the user wants to create an array of reference wrappers, they need to explicitly request that type: auto a = make_array<std::reference_wrapper<int>>(std::ref(x)); 1 Here’s the proposal’s wording: Ban reference_wrapper in the make_tuple-like interface. make_tuple and make_pair have special handling of reference_wrapper, then user might expect that the expression make_array(ref(a), ref(b)) also results in a tuple-like object storing T&.
72,320,584
72,320,686
binary search tree by smart pointers
I used row pointers to implement the binary search tree data structure and it worked perfectly, but when I replaced the row pointers with shared_ptr it compiles successfully but the program crashes due to unknown run-time error. Could you please help in this? #include<iostream> #include<memory> class node{ public: int data; std::shared_ptr<node>left = std::make_shared<node>(); std::shared_ptr<node>right = std::make_shared<node>(); }; std::shared_ptr<node>CreateNode(int x); void print_tree(const std::shared_ptr<node>&x); int main(){ auto root = std::make_shared<node>(); root = CreateNode(12); root->left = CreateNode(9); root->right = CreateNode(14); root->left->right = CreateNode(10); root->left->right = CreateNode(11); print_tree(root); return 0; } std::shared_ptr<node>CreateNode(int x){ std::shared_ptr<node>NewNode = std::make_shared<node>(); NewNode->data = x; NewNode->left = NewNode->right = nullptr; return NewNode; } void print_tree(const std::shared_ptr<node>&x){ if(x==nullptr) return; std::cout<<x->data<<std::endl; print_tree(x->left); print_tree(x->right); }
#include<iostream> #include<memory> class node { public: int data; std::shared_ptr<node>left; std::shared_ptr<node>right; }; std::shared_ptr<node>CreateNode(int x); void print_tree(const std::shared_ptr<node>&x); int main() { auto root = CreateNode(12); root->left = CreateNode(9); root->right = CreateNode(14); root->left->right = CreateNode(10); root->left->right = CreateNode(11); print_tree(root); return 0; } std::shared_ptr<node>CreateNode(int x) { std::shared_ptr<node>NewNode = std::make_shared<node>(); NewNode->data = x; NewNode->left = NewNode->right = nullptr; return NewNode; } void print_tree(const std::shared_ptr<node>&x) { if(x==nullptr) return; std::cout<<x->data<<std::endl; print_tree(x->left); print_tree(x->right); } This works on my machine. I made left and right pointers in node class initially equal to nullptr, instead of creating new node because you can't know is it going to be used. And root to be initialized by result of CreateNode function.
72,320,649
72,320,849
Assigning general classes as null in C++
I am having kind of a trouble adapting a program from C# to C++. It's very commom given a class to assign it the null value. But C++ is not accepting the equivalent form 'nullptr' class Point{ public: int x,y; } //... Point p = nullptr; There is some way of solving it?
You cannot assign nullptr to a class because a class is a type and not a variable. What you're doing by typing Point p = nullptr; is that you're asking the compiler to find a constructor of Point which accepts a nullptr. You can either create an object of Point as an automatic variable by doing this: Point p = Point{1, 2}; // sets x = 2 and y = 3 or simply like this: Point p; for which however you will need to define a constructor which initializes x and y because you haven't provided the member variables with default values. Depending on the context in which this statement resides, p will either be allocated on the heap or on the stack. In case you're instantiating p in the main function, it will be the latter. You can create a pointer to an object of Point by doing this: Point* p = nullptr; However, you will only have created a pointer. You will need to further take care of allocation, which you can do like this: Point* p = new Point{1, 2}; in which case you should also free the allocated memory before your program ends like so: delete p;
72,321,144
72,321,261
Error: Binding reference of type .. to const
I'm trying to overload operator<<. When trying I got an error saying Error: Passing const as this argument discards qualifiers So I added const to my functions but now I'm getting this error: Binding reference of type .. to const. Main.cpp ostream& operator<<(ostream& ostr, const Student& stud){ float mo = 0; int quantity = stud.get_grade().size();\ . . . Get_grade Function vector<pair<Subject *, float>>& Student::get_grade() const{ return grade; } Error binding reference of type ‘std::vector<std::pair<Subject*, float> >&’ to ‘const std::vector<std::pair<Subject*, float> >’ discards qualifiers | return grade; Grade is a vector
get_grade is a const member function meaning that the type of this pointer inside it is const Student* which in turn means that the data member grade is treated as if it were itself const. But the problem is that the return type of your function is an lvalue reference to non-const std::vector meaning it cannot be bound to a const std::vector. To solve this just add a low-level const in the return type of the function as shown below: vvvvv------------------------------------------------------------->low-level const added const vector<pair<Subject *, float>>& Student::get_grade() const{ return grade; }
72,321,166
72,381,292
C++ multithreaded program work fine in windows, throws "resource temporarily unavailable" in Linux
Edit: Based on Jonathan's comment, I tried to create a standalone program to reproduce this issue. I was unable to recreate the issue. Then I switched to Jeremy's comment to make sure I really am calling this only once. Turns out, there was a bug in the upstream code which was calling this in a loop when a specific condition was met. My first instinct was to have a flag before the thread create to check if it has been already created for the given dayIndex. Like if (threadSpawnedForEachDay[dayIndex]) { return; } Which took care of the "resource temporarily unavailable", but the output was still buggy. It took me a full 2 days to debug because I could only reproduce the behavior in Linux release build after 30 minutes. (it has recursive logic and the bug shows up something like 100 calls deep). My original post I have a simple 2 threaded logic implemented in C++ A thread which sleeps for a limited time, and then flips a switch A main thread that does everything. It checks the switch periodically, and when it's flipped it knows to wrap up and exit gracefully The program runs fine in Windows, but in Linux (Ubuntu 20.04) it eventually throws a system error: "Resource temporarily unavailable". I tried htop on Linux, and it appears that the program is creating threads uncontrollably. What could be causing this? Here's my header: struct TimeHelper { std::atomic_bool *timerForEachDay; std::vector<std::chrono::seconds> startTimeVector; bool isTimeUp(int dayIndex); void setStartTime(int dayIndex); void timerThread(int dayIndex); TimeHelper(); ~TimeHelper(); void TimeHelperInitializer(); }; extern TimeHelper timer; Here's the code: some values hard coded here for brevity - my actual code uses a configuration file TimeHelper timer; TimeHelper::TimeHelper() { timerForEachDay = NULL; } TimeHelper::~TimeHelper() { delete[] timerForEachDay; } //Separate initializer because the constructor is run before main //This is only called once void TimeHelper::TimeHelperInitializer() { timerForEachDay= new std::atomic_bool[2]; for (int i = 0; i < 2; i++) { timerForEachDay[i]=false; } setStartTime(0); //setStartTime for other days is called elsewhere. It is only called once for each dayIndex at an appropriate time. return; } bool TimeHelper::isTimeUp(int dayIndex) { if (timerForEachDay[dayIndex] == true) return true; return false; } void TimeHelper::timerThread(int dayIndex) { std::this_thread::sleep_for(std::chrono::seconds(20)); timerForEachDay[dayIndex] = true; } void TimeHelper::setStartTime(int dayIndex) { std::thread th(&TimeHelper::timerThread, this, dayIndex); th.detach(); return; }
Turns out there was a bug in the upstream code which was making repeated calls to setStartTime. The reason why the issue showed up only in Linux is because it is a much faster OS. Windows would probably have the same experience if I let the code run for a few days. (in case anyone's curious, the program tries to find the "best fit" for a given amount of time but if not available then switches to look for "a good enough fit"). Thank you to everyone who commented on my question. Your comments steered me in the right direction.
72,321,576
73,762,419
using `[[gnu::noinline]]` in header-only library
Functions in a header-only library should be declared as inline to prevent multiple definitions in the different translation units. That is, for example, I wrote a header-only library mylib.hpp: void do_something(int) {} And I used this header in two different cpp file: // a.cpp # include "mylib.hpp" void func1() {do_something(1);} // b.cpp # include "mylib.hpp" void func2() {do_something(2);} Build them with g++ -o main a.cpp b.cpp, GCC will complain with "multiple definition of do_something(int)". To prevent this, define the function like static void do_something(int) {} to make it have a copy in each translation unit (that is, have two copies in the last output), or define the function like inline void do_something(int) {} to have exactly a single copy in the last output, which is what we want. However, if I want to force do_something not to be inlined by the compiler (for example, I want to use backtrace library to dynamically find out which function called do_something), I should write it like: [[gnu::noinline]] inline void do_something(int) {} However, GCC complains: Warning: inline declaration of ‘do_something(int)’ follows declaration with attribute ‘noinline’ [-Wattributes] So, what is the proper way to do such things?
The 'proper' way to get rid of the warning is to split your code into a header (.h) and source (.cpp) file. // mylib.h [[gnu::noinline]] void do_something(int); // mylib.cpp void do_something(int) { // Implementation } // a.cpp #include "mylib.h" void func1() { do_something(1); } // b.cpp #include "mylib.h" void func2() { do_something(2); } Frankly, a library being 'header-only' is an overrated property. Splitting code into header and source files can improve compile times because the function body is parsed and compiled just once instead of being parsed and examined multiple times. (If you define a function in a header, the compiler may need to examine it multiple times to check that it hasn't changed between translation units.) If being 'header-only' is really that important to you the other options are: Using static. This will silence the warning, but runs the risk of producing multiple copies of the same function - one per translation unit. A link-time optimiser might be able to eliminate the duplicates, but it might not be a good idea to assume that will be the case. Making the function a template makes the function implicitly inline whilst still respecting the [[gnu::noinline]], but then you end up with a dummy template parameter and force people to specify that parameter when calling the function. You could make the function a static class member, which will make it implicitly inline without upsetting the attribute, and only requiring a bit of extra typing from the user (Class::do_something(1)). Another way that would work, but is really bad and should be avoided is: #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wattributes" [[gnu::noinline]] inline void do_something(int) { // Implementation } #pragma GCC diagnostic pop But this is a very hacky solution. Naturally it'll only work if GCC is the compiler and will break many other compilers. (Clang might be able to deal with it, but VC++ will choke on it.) Of course, you may not actually need to force the compiler to avoid inlining your function. Usually the compiler will make the right decision on its own. Personally the only times I've needed to use [[gnu::noinline]] are when a function used inline assembly that broke when the compiler inlined it and when measuring the overhead of a function call. (The latter is probably the intended use of the attribute.)
72,321,943
72,322,086
Is there a reason to use zero-initialization instead of simply not defining a variable when it is going to be updated before the value is used anyway?
I came across a code example learncpp.com where they zero-initialized a variable, then defined it with std::cin: #include <iostream> // for std::cout and std::cin int main() { std::cout << "Enter a number: "; // ask user for a number int x{ }; // define variable x to hold user input (and zero-initialize it) std::cin >> x; // get number from keyboard and store it in variable x std::cout << "You entered " << x << '\n'; return 0; } Is there any reason that on line 7 you wouldn't just not initialize x? It seems zero-initializing the variable is a waste of time because it's assigned a new value on the next line.
Is there any reason that on line 7 you wouldn't just not initialize x? In general, it is advised that local/block scope built in types should always be initialized. This is to prevent potential uses of uninitialized built in types which have indeterminate value and will lead to undefined behavior. In your particular example though since in the immediate next line we have std::cin >> x; so it is safe to omit the zero initialization in the previous line. Note also that in your example if reading input failed for some reason then prior to C++11, x still has indeterminate value but from C++11(&onwards) x will no longer has indeterminate value according to the below quoted statement. From basic_istream's documentation: If extraction fails (e.g. if a letter was entered where a digit is expected), zero is written to value and failbit is set. For signed integers, if extraction results in the value too large or too small to fit in value, std::numeric_limits<T>::max() or std::numeric_limits<T>::min() (respectively) is written and failbit flag is set. For unsigned integers, if extraction results in the value too large or too small to fit in value, std::numeric_limits<T>::max() is written and failbit flag is set. It seems zero-initializing the variable is a waste of time because it's redefined on the next line. As i said, in your example and assuming you're using C++11(& higher), you can safely leave off the zero-initialization. then defined it with std::cin No the use of std::cin does not "define" it(x). Definition happened only once when you wrote: int x{ }; //this is a definition Even if you leave the zero initialization, then also it will be a definition: int x; //this is also a definition but x is uninitialized here
72,322,122
72,322,800
Which libraries are available to link in cmake?
I was learning CMake for a project and feel confused when linking libraries. I find it easier to ask with an example, as using terms I am not familiar could be misleading. The questions are (also commented in the example codes) how can I know what are the library name I can link to my target? Can I tell that from the build file structure, or I need to look into CMakeLists.txt of the external libraries. (e.g. the gtest-main and libhermes in the example) How can I use a "grandchild" library that is part of the external library? (e.g. the jsi library in the example) Example Let's say I am writing some tests with dependency on the Hermes Library. I then write a CMakeList.txt file like cmake_minimum_required(VERSION 3.13) project(mytests_cxx) set(CMAKE_CXX_STANDARD 14) include(FetchContent) FetchContent_Declare( hermes URL https://github.com/facebook/hermes/archive/d63feeb46d26fe0ca7e789fc793f409e5158b27f.zip ) FetchContent_MakeAvailable(hermes) enable_testing() add_executable( hello_test ./test.cpp ) find_library ( LIB_HERMES hermes # <- how can I know what is the name? ) find_library ( LIB_JSI jsi # <- How could I use a "grandchild" dependency, it is defined here (https://github.com/facebook/hermes/tree/main/API/jsi/jsi) ) target_link_libraries( hello_test gtest_main <- Hermes seems to use gtest, how could make sure gtest_main is available? LIB_HERMES LIB_JSI ) include(GoogleTest) gtest_discover_tests(hello_test) Running cmake to build cmake -S . -B build -DHERMES_BUILD_SHARED_JSI=ON // I see an option defined in heremes'CMakeLists.txt but not sure if I am using it right. the directory in build tree ./build -L 2 ./build ├── CMakeCache.txt ├── CMakeFiles │ ├── 3.23.1 │ ├── CMakeDirectoryInformation.cmake │ ├── CMakeError.log │ ├── CMakeOutput.log │ ├── CMakeRuleHashes.txt │ ├── CMakeTmp │ ├── Makefile.cmake │ ├── Makefile2 │ ├── Progress │ ├── TargetDirectories.txt │ ├── cmake.check_cache │ ├── hello_test.dir │ └── progress.marks ├── CTestTestfile.cmake ├── ImportHermesc.cmake ├── Makefile ├── _deps │ ├── hermes-build │ ├── hermes-src │ └── hermes-subbuild ├── bin │ └── hermes-lit ├── cmake_install.cmake ├── compile_commands.json └── hello_test[1]_include.cmake then I run cmake --build build and see this error /.../test.cpp:8:10: fatal error: 'jsi/jsi.h' file not found #include <jsi/jsi.h>
Your question is too broad. Either ask a question about the list of libraries in cmake, or ask a question about how to compile and link with hermes, or ask a question about a specific problem with your build about including a third party. These should be 3 separate questions on this site. how can I know what are the library name I can link to my target? There are two things that you can target_link_libraries - you can link with libraries available on your system and link with targets defined in cmake. You can list libraries available on your system by traversing all paths outputted by ld --verbose and listing all lib*.so files in those directories. Or https://unix.stackexchange.com/questions/43187/how-do-i-get-a-list-of-shared-library-filenames-under-linux or similar. See man ld.so. You can list all targets defined in cmake. How do I list the defined make targets from the command line? . These lists combined consist of all possible libraries names that you can link with. Can I tell that from the build file structure I do not understand. No. I need to look into CMakeLists.txt of the external libraries Yes, usually you want to look into any external libraries CMakeLists.txt at least to check for malicious code. You usually look into documentation of external libraries. And, because source code is a form of documentation in open-source projects, you would look into the source code, yes. How can I use a "grandchild" library that is part of the external library? There are multiple ways for including external projects. Cases were outlined in Correct way to use third-party libraries in cmake project . That said, not all CMake projects work properly with add_subdirectory() (which is called by FetchContent_MakeAvailable) - there are many cases where the third-party projects CMakeLists.txt may not work with parent project. In such cases, I would go with compiling and installing the project into a subdirectory for example before running CMake or with ExternalProject_Add, and then only including the result of compilation with hand-crafted find_library and target_include_directories from the installation directory. Overall, including a third party is not always an easy task, and yes it requires you to become intimate with the specifics of a third party project and how it works and how it was written and decide how you want it to include in your project.
72,322,537
72,323,474
Any way to build an array of pointers from a tuple of different objects (but derived from the same base class)?
Good morning all! reading stack overflow for a long time, but this is my first post here. For some reasons I would like to do something like this: class Base{ ... } class A : public Base{ ... } class B : public Base{ ... } std::tuple<A, B> myTuple{A{}, B{}}; std::array<Base*, 2> myArray{...}; Briefly - I want to store dozens of objects in a tuple object, but at some point I need a container of pointers to all of those elements. All of them inherits from the same class which is my interface class. And I don't know how to extract elements from myTuple, take pointers to all its elements (in exact the same sequence as it is defined) and assign them to myArray. I have seen some solutions in different questions, but none of it fits to my specific case. I am just learning templates, so this is kinda difficult for me. Code taken from: https://stackoverflow.com/a/59561746/19163017 template <class Tuple> struct make_array; template <class V, template <V N> class C, V... Ns> struct make_array<std::tuple<C<Ns>... >> { static constexpr Tf::TaskFlow<3>::TaskArray value{&Ns... }; }; template <class Tuple> constexpr auto make_array_v = make_array<Tuple>::value; But maybe it could be modified for my needs?
It is possible to create an array of pointers to tuple members using various compile time programming techniques. Below is one implementation. There may be a less verbose way of doing this, but I am no expert on this kind of stuff: #include <iostream> #include <string> #include <array> #include <tuple> class Base { public: virtual std::string foo() = 0; }; class A : public Base { public: std::string foo() override { return "A"; } }; class B : public Base { public: std::string foo() override { return "B"; } }; template<size_t I, typename... Ts> void tuple_to_base_ptr_array_aux(std::tuple<Ts...>& tup, std::array<Base*, sizeof...(Ts)>& ary) { if constexpr (I < sizeof...(Ts)) { ary[I] = static_cast<Base*>( &(std::get<I>(tup)) ); tuple_to_base_ptr_array_aux<I + 1>(tup, ary); } } template<typename... Ts> std::array<Base*, sizeof...(Ts)> tuple_to_base_ptr_array( std::tuple<Ts...>& tup) { std::array<Base*, sizeof...(Ts)> ary; tuple_to_base_ptr_array_aux<0>(tup, ary); return ary; } int main() { std::tuple<A, B, A, A, B, A> foo; auto ary = tuple_to_base_ptr_array(foo); for (auto* ptr : ary) { std::cout << ptr->foo(); } std::cout << "\n"; return 0; }
72,322,612
72,322,954
Garbage when converting character to string using concatenation
I am converting a character to a string by concatenating it with an empty string (""). But it results in undefined behaviour or garbage characters in the resultant string. Why so? char c = 'a'; string s = ""+c; cout<<s<<" "<<s.size()<<"\n";
Let's look at your snippet, one statement or a line at a time. char c = 'a'; This is valid, assigning a character literal to a variable of type char. Note: since c is not changed after this statement, you may want to declare the definition as const. string s = ""+c; Let's refactor: std::string s = ("" + c); Let's add type casting to make the point more clear: std::string s = ((const char *) "" + (char) c); The order of operations is resolve all expressions on the right hand side (rhs) of the assignment operator before assigning to the string variable. There is no operator+() in C++ that takes a const char * and a single character. The compiler is looking for this function: operator+(const char *, char). This is the primary reason for the compilation errors. cout<<s<<" "<<s.size()<<"\n"; The string assignment and creation failed, thus s is empty and s.size() is zero.
72,322,958
72,765,708
cannot capture the struct value inside of the kernal function
It is so strange and I am struggling with this problem for the whole week. I just want to use the variable which is defined inside of the struct constructor, but fail to do that. The simple code is here: #include <CL/sycl.hpp> #include <fstream> #include <cstdlib> #include <stdio.h> #include <stdlib.h> #define ghost 3 using namespace cl::sycl; struct test { int ls[3]; queue Q{}; test() { ls[0] = ghost; ls[1] = ghost; ls[2] = ghost; } void calculate(); }; void test::calculate() { size_t lx = 10; size_t ly = 10; auto abc = Q.submit([&](handler &h) { sycl::stream out(1024, 256, h); h.parallel_for(range{lx, ly}, [=, lsq = this->ls](id<2> idx) { out << "this is id1" << lsq[1] << "\n"; }); }); } int main() { test t1; t1.calculate(); return 0; } Someone from the DPC++ community told me this method to capture this pointer, but I don't why it does not work well.
According to 4.12.4. Rules for parameter passing to kernels from SYCL 2020 Specification the array of scalar values can be passed as a kernel parameter. But the problem is in the capturing of struct member: [lsq = this->ls] is equivalent to auto lsq = this->ls; In this case, the type of lsq is int* and it will contain the address of test::ls in the host memory. The access to the elements of the array in the kernel will lead to the undefined behavior. There are two possible solutions here: Solution 1 Create a local references to the test::ls and pass it to the kernel by value: void test::calculate() { size_t lx = 10; size_t ly = 10; auto abc = Q.submit([&](handler &h) { sycl::stream out(1024, 256, h); auto& lsq = this->ls; h.parallel_for(range{lx, ly}, [=](id<2> idx) { out << "this is id1: " << lsq[1] << "\n"; }); }); } In this case, the captured variable (lsq) will have int[3] type and will be correctly initialized in the kernel. Solution 2 Use std::array or sycl::marray instead of C array: #define ghost 3 using namespace cl::sycl; struct test { marray<int, 3> ls; queue Q; test() { ls[0] = ls[1] = ls[2] = ghost; } void calculate() { size_t lx = 10; size_t ly = 10; auto abc = Q.submit([&](handler& h) { sycl::stream out(1024, 256, h); h.parallel_for(range{ lx, ly }, [=, lsq = this->ls](id<2> idx) { out << "this is id1: " << lsq[1] << "\n"; }); }); } };
72,323,050
72,323,801
How do I store the tmp object in a map, to acess the object outside of it's creation context
I am relatively new to C++. I tried to break down the problem. All code is also here: https://onlinegdb.com/wAmLAONkF (can be executed) Basically, I have a function where temp objects are created. The objects are pushed to a std::vector: vector<Student> GetStudents(int some_params) { vector<Student> students; //logic where students are returned Student s1 { "John", 42 }; Student s2 { "Bill", 12 }; students.push_back(s1); students.push_back(s2); return students; } To maintain the objects, they are stored outside in a std::map. The map stores each Student by pointer in a vector<Student*> (it has to be vector<Student*>!): map<int, vector<Student*>> m {}; { //start of new context, other class context in another file, map is passed by reference int some_params = 5; vector<Student> students = GetStudents(some_params); To store them in the map, I copy references into a new vector: vector<Student*> tmpV; for(auto & student : students) tmpV.push_back( &student); //store them in the map m.emplace(some_params, tmpV); }//leave context //data loss - Students are lost I do know, that the problem is because the pointers to the objects are stored in a local vector. After I leave the context, the pointers do not point somewhere valid. But how can I solve this?
The vector<Student> returned by GetStudents() needs to be stored in a variable that is in the same scope as (or in a higher scope than) the std::map that refers to its Students, eg: map<int, vector<Student*>> m; vector<Student> students; // <-- move it up here! { //start of new context int some_params = 5; students = GetStudents(some_params); vector<Student*> tmpV; for(auto & student : students) tmpV.push_back( &student); //store them in the map m.emplace(some_params, tmpV); } //leave context // no data loss - Students are valid! Otherwise, GetStudents() will have to return a vector<Student*> instead, where each Student has been created dynamic via new, and then destroyed via delete after the map is done using them: vector<Student*> GetStudents(int some_params) { vector<Student*> students; //logic where students are returned students.push_back(new Student{ "John", 42 }); students.push_back(new Student{ "Bill", 12 }); return students; } ... map<int, vector<Student*>> m; { //start of new context int some_params = 5; vector<Student*> students = GetStudents(some_params); //store them in the map m.emplace(some_params, students); } //leave context // no data loss - Students are valid! ... for(auto &entry : m) { for (auto *student : entry.second) { delete student; } } Ideally, your map should store either vector<Student> or vector<unique_ptr<Student>>, but your requirement of "it has to be vector<Student*>!" prevents that.
72,323,481
72,323,705
Struct template and constructor with initializer list
I'm trying to better understand templates and for this purpose I made an educational struct: template<typename T, size_t N> struct SVectorN { SVectorN(const T(&another)[N]); private: T components[N]; }; Constructor that I made allows me to make an instance, like this: double input[4] = { 0.1, 0.2, 0.3, 0.4 }; SVectorN<double, 4> t(input); But I can't figure out how to support initializating like this: SVectorN<double, 4> c = { 1.3, 1.4, 1.5, 1.6 }; Or even better something like this: SVectorN c(1.3, 1.4, 1.5, 1.6 ); // SVectorN<double, 4> Is it possible or am I missing something comepletely? Thanks
Both approaches are possible, initialization in C++ is tricky simply because of how many ways there are and their subtle differences. I would recommend something like this: #include <cstdint> #include <utility> template <typename T, std::size_t N> struct SVectorN { SVectorN(const T (&another)[N]); template <typename First, typename Second, typename... Tail> SVectorN(First &&f, Second &&s, Tail &&...t) : components{std::forward<First>(f), std::forward<Second>(s), std::forward<Tail>(t)...} {} private: T components[N]; }; int main() { double input[4] = {0.1, 0.2, 0.3, 0.4}; SVectorN<double, 4> t(input); SVectorN<double, 4> c = {1.3, 1.4, 1.5, 1.6}; SVectorN<double, 4> d{1.3, 1.4, 1.5, 1.6}; SVectorN<double, 4> e(1.3, 1.4, 1.5, 1.6); } I had to explicitly enforce presence of at least two arguments in the variadic ctor, otherwise it would be a better overload match for t's construction and that would fail. c,d,e are practically the same initialization if there is not ctor with std::initializer_list. Which there is not because initializing an array with one cannot be easily done. Now, if you want to automatically deduce the template parameters, that is possible thanks to CTAD. To simplify that link, you have to just specify to the compiler how to deduce class's template arguments from a constructor's arguments. For example the following: template <class T, std::size_t N> explicit SVectorN(const T (&)[N]) -> SVectorN<T, N>; template <typename F, typename S, typename... Tail> SVectorN(F &&, S &&, Tail &&...) -> SVectorN<F, sizeof...(Tail) + 2>; will allow: SVectorN tx(input); SVectorN cx = {1.3, 1.4, 1.5, 1.6}; SVectorN dx{1.3, 1.4, 1.5, 1.6}; SVectorN ex(1.3, 1.4, 1.5, 1.6);
72,323,821
73,214,277
'QMainWindow' file not found
the program works, but I don't like these errors in mainwindow.h: #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> //'QMainWindow' file not found QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H because of this, errors also appear in the main file main.cpp: #include "mainwindow.h" //In included file: 'QMainWindow' file not found #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); } the program still works, but I would still like to know the solution to the problem
I have already found answer there: https://stackoverflow.com/a/58737644/18282426 so, select from above help -> About modules... and disable ClangCodeModel
72,324,033
72,325,297
C++ Unordered Set string hash time complexity?
Why the worst case complexity of insert into set is linear constant of size of container and not the size of element itself? I am specifically talking about string. If I have a string set of size m, then if I insert a new string of size x, I assume that the insert operation will need to read string of size x in order to calculate key? So why dont we consider that time? If there is another string that is of size 1000*x, then insertion will still take m size in worst case? Regardless of size of string, the time is 0(m)? How?
This is a great question and it hits at some nuances in the way we analyze the cost of operations on hash tables. There are actually several different ways to think about this. The first one is to think about the runtimes of the operations on a hash table measured with a runtime perspective that purely focuses on the size of the table. From that perspective, the cost of an insertion, lookup, or deletion does not scale as a function of the number of table elements. That is, the cost of looking something up does not depend on the number of elements in the table, the cost of inserting an element doesn't depend on the number of elements in the table, etc. From that vantage point, if we let n denote the number of elements in the table, then the cost of an insertion, deletion, or lookup is O(1), because there is no dependency on n. In this sense, the big-O notation here is meant to be interpreted as "if the only variable is n, the number of elements in the table, how will things scale?" But that leaves a lot to be desired, since it completely ignores the cost of comparing strings for equality, the cost of evaluating the hash function, etc. If you factor those details in, then yes, you're correct - the cost of looking up, inserting, or deleting a string of length m from a hash table with n elements is O(m), not O(1). The perspective I've always found most helpful is the following. When a hash table says that all operations run in time O(1), what it really means is that each operation requires only O(1) total hash evaluations and comparisons. In that sense, it means "the cost of looking something up, or inserting something, or deleting something is some constant number of hash evaluations and comparisons." To then work out the total cost, you then multiply O(1) by the cost of a hash or comparison, which in the case of strings of length m would be O(m). That gives you the overall runtime of O(m), which matches your intuition.
72,324,668
72,325,774
Define type alias between template and class declaration in order to inherent from it
I have a class template which uses some type alias through its implementation, and also inherits from the same type: template<typename TLongTypename, typename TAnotherLongTypename, typename THeyLookAnotherTypename> class A : SomeLongClassName<TLongTypename, TAnotherLongTypename, THeyLookAnotherTypename> { using Meow = SomeLongClassName<TLongTypename, TAnotherLongTypename, THeyLookAnotherTypename>; // ... (using Meow a lot) }; Naturally I want to inherit from the type alias Meow and not from the long name. Is there any nice way to do that, hopefully such that Meow will be defined inside the template scope but before the class scope?
You could declare the type alias Meow as a default template parameter, directly in the template parameter list, which means you only have to spell it out once: template<typename TLongTypename, typename TAnotherLongTypename, typename THeyLookAnotherTypename, // declare Meow once here typename Meow = SomeLongClassName<TLongTypename, TAnotherLongTypename, THeyLookAnotherTypename>> class A : Meow // inherit { Meow X; // use };
72,325,015
72,325,034
I am using ifstream and I need to read in two words as one string instead of splitting them
I need to read in a line from a file, but I need to save two strings as one. For example, if the file's line had someone's name like Bernie Sanders, I would want to save the entire name into a string variable instead of just the first name.
I assume you are doing std::string nameString; fs >> nameString; this will read to the end of a word. do this instead std::string nameString; std::getline(fs, nameString); this will read the whole line
72,325,434
72,325,460
How to use if commands with sentances
I am currently learning c++ and creating an assistant for myself. I need to make sure the if command checks for a sentence, not a word in a string how do I do that. #include <iostream> #include <string> #include <windows.h> using namespace std; const string YES = "yes"; const string NO = "no"; //ignore this int main () { std::string Question; std::string check; std::cout << ("Hi sir how may i assist you?\n"); //user asks the question and then a if command checks the question from a list of questions and if the line is the same as in the database it gives a output getline (cin, Question); if (Question == "whats the weather?") { std::cout << ("Well it is...\n"); //then it pulls data from the web and puts it in here } } Output Hi sir how may I assist you? whats the weather (nothing) else happens
In this: if (Question == whats the weather?) Add quotes around the sentence. You want to write if (Question == "whats the weather?") Also, since you're using namespace std, you don't need std:: before anything.
72,325,472
72,325,491
Define a different function for each instance of a class
Say I have this class: class Object { public: int x; int y; void update(SDL_Event); void start(); }; I want to be able to make start and update change behavior from instance to instance. I have tried using function pointers, like so: class Object { public: int x; int y; void (*update)(SDL_Event); void (*start)(void); }; void teststart() { x++; return; } And in my main(), I do: testlevel.objs[1].start = teststart; But then, I cannot reference variables from inside the class. I am sure there is something obvious I am overlooking, but searching online yields no results for when the pointer is in the class. Maybe function pointers are not the right answer?
You would need to pass your functions a pointer/reference to the Object instance, eg: class Object { public: int x; int y; void (*doupdate)(Object*, SDL_Event); void (*dostart)(Object*); void update(SDL_Event event) { if (doupdate) doupdate(this, event); } void start() { if (dostart) dostart(this); } }; void teststart(Object* obj) { obj->x++; } void testupdate(Object* obj, SDL_Event event) { // update obj as needed... } Object &obj = testlevel.objs[1]; obj.dostart = teststart; obj.doupdate = testupdate; Otherwise, use std::function with capturing lambdas instead: #include <functional> class Object { public: int x; int y; std::function<void(SDL_Event)> update; std::function<void()> start; }; Object *obj = &(testlevel.objs[1]); obj->start = [obj](){ obj->x++; }; obj->update = [obj](SDL_Event event){ // update obj as needed... };
72,325,515
72,325,533
Why is the std::vector not giving any outputs in c++
I don't understand why but the std::vector is not giving anything after i put a class pointer in the array. // runs at start void States::AssignState(GameState* state) { _nextVacentState++; _states.push_back(state); } // executes in a loop void States::ExecuteCurrentState() { // protection incase there is nothing in the array or the current state is not grater than the size of the array (not the problem after i nerrowed the problem down) if (_nextVacentState == 0) std::cout << "Error: There is no states, setup some states then try again" << std::endl; return; // there is no states if (_currentState >= _states.size() - 1) std::cout << "Error: Current State is grater than all possable states" << std::endl; return; // The program just freezes at this and i can figure out why _states[0]->tick(); std::printf("S"); }
This is one of the reasons I'd suggest getting in the habit of using curly braces for all if statements, even ones that live on a single line. A problem line: if (_nextVacentState == 0) std::cout << "Error: There is no states, setup some states then try again" << std::endl; return; Let's add some newlines to make it clearer what's happening if (_nextVacentState == 0) std::cout << "Error: There is no states, setup some states then try again" << std::endl; return; That return statement is getting executed unconditionally, because only the first statement after if(_nextVacentState==0) is actually part of the if. So the compiler executes it as if it had been written like this: if (_nextVacentState == 0) { std::cout << "Error: There is no states, setup some states then try again" << std::endl; } return; But, what you want needs to be written like this instead: if (_nextVacentState == 0) { std::cout << "Error: There is no states, setup some states then try again" << std::endl; return; } You have same problem in the next if check for _currentState, as well.
72,325,783
72,325,795
What is the `(... && TraitsOf())` mean in C++
I am trying to understand this C++ syntax: constexpr auto all_deps_type_set = (... | TraitsOf(types::type_c<HaversackTs>).all_deps); What does the (...| part mean? Example: https://github.com/google/hotels-template-library/blob/master/haversack/haversack_test_util.h
HaversackTs is a parameter pack, which means it contains some variable number of types given to the template. ... expands a template parameter pack, using a given binary operator (in our case, the bitwise |) to fold over it. So if, in a particular instantiation of this template, HaversackTs happened to be int, std::string, then that line would mean constexpr auto all_deps_type_set = (TraitsOf(types::type_c<int>).all_deps | TraitsOf(types::type_c<std::string>).all_deps); The right-hand side is expanded separately for each type in the parameter pack, and the results are combined using |. This generalizes naturally to more than two arguments by simply applying | between each one.
72,325,907
72,326,806
Is there a way to create an array of combined functions compile-time in c++?
I'm working on an NES emulator in c++ and figured that the most efficient way to run opcodes would be to call a function pointer in an array of functions that do exactly what the opcode does. The problem is that each opcode has a specific operation and memory address. While searching for a solution, I stumbled upon lambda expressions. This is definitely good enough for a NES emulator on modern hardware. However, I can't find a solution such that each function in the array contains the machine code for both the operation and the addressing without defining 256 separate functions. This is along what I had in mind for a similar function that combines f and g: int addone(int x) { return x + 1; } int multtwo(int x) { return 2 * x; } something combine(function<int(int)> f, function <int(int)> g) { /* code here */ } /* combine(addone, multtwo) creates a function h that has the same machine code as int h(x) { return 2 * x + 1; } */ Any ideas? If I had to take a guess, it would have something to do with templates. Thanks!
I'd say that when you want to write generics for functions that it's kind of a "design pattern" to switch to functors: Compilers are desigined to handle types easily, but handling function pointers for stuff you want to mis-match and keep optimised at compile-time gets ugly! So we either write our functions as functors, or we wrap them as functors: struct A { static constexpr int Func (int x) { return -3*x + 1; } }; struct B { static constexpr int Func (int x) { return -2*x - 5; } }; // etc... If we have nice symmetry in how we'll use them, then we can manage them systematically. Eg. if we always want to combine them like f(g(h(...y(z())...))), then we can solve as follows: template <class T, class ... Ts> struct Combine { static constexpr int Get () { int x = Combine<Ts...>::Get(); return T::Func(x); } }; template <class T> struct Combine <T> // The base case: the last function in the list { static constexpr int Get () { return T::Func(); } }; demo Or if we're in no such luck, we'll have to resort to more old-fashioned inputs like you suggested: template <class Funcs, class Data> constexpr int Combine (const Data & d) { Funcs F; // Some use without much symmetry: return F.f(F.g(d)) - F.h(d); } int main () { struct FuncArgs { A f; B g; C h; }; return Combine<FuncArgs>(5); } demo Note that in the second example I've changed from static methods to non-static. This doesn't really matter - the compiler should optimise these fully regardless, but I think in this case it makes the syntax slightly nicer (and shows an alternative style).
72,326,082
72,326,125
Question about the thread-safety of using shared_ptr
As it's well known that shared_ptr only guarantees access to underlying control block is thread safe and no guarantee made for accesses to owned object. Then why there is a race condition in the code snippet below: std::shared_ptr<int> g_s = std::make_shared<int>(1); void f1() { std::shared_ptr<int>l_s1 = g_s; // read g_s } void f2() { std::shared_ptr<int> l_s2 = std::make_shared<int>(3); std::thread th(f1); th.detach(); g_s = l_s2; // write g_s } In the code snippet above, the owned object of the shared pointer named g_s are not accessed indeed. I am really confused now. Could somebody shed some light on this matter?
std::shared_ptr<T> guarantees that access to its control block is thread-safe, but not access to the std::shared_ptr<T> instance itself, which is generally an object with two data members: the raw pointer (the one returned by get()) and the pointer to the control block. In your code, the same std::shared_ptr<int> instance may be concurrently accessed by the two threads; f1 reads, and f2 writes. If the two threads were accessing two different shared_ptr instances that shared ownership of the same object, there would be no data race. The two instances would have the same control block, but accesses to the control block would be appropriately synchronized by the library implementation. If you need concurrent, race-free access to a single std::shared_ptr<T> instance from multiple threads, you can use std::atomic<std::shared_ptr<T>>. (There is also an older interface that can be used prior to C++20, which is deprecated in C++20.)
72,326,940
72,327,235
Sum of the two lowest positive numbers in a vector
I made a function sumOfTwoSmallestNumbers() that takes an integer vector (containing only positive values) and it returns the sum of the two lowest positive numbers stored in that vector. Unfortunately, my function fails for a few test cases (I do not have access to the inputs of those test cases). Please help me find the error in my code. NOTE: Vector always consists of a minimum of 4 positive values #include <iostream> #include <vector> using namespace std; long sumOfTwoSmallestNumbers (vector<int> numbers) { long int sum = 0; long int min1 = numbers[0]; int position; for (unsigned long int i = 0; i < numbers.size(); i++){ if (numbers[i] < min1){ min1 = numbers[i]; position = i; } } numbers.erase(numbers.begin() + position - 1); long int min2 = numbers[0]; for (unsigned long int i = 0; i < numbers.size(); i++){ if (numbers[i] < min2){ min2 = numbers[i]; } } sum = min1 + min2; return sum; } Logic: I have tried to first find the smallest value and store it in a variable and then remove that value from the vector. After that, I again searched for the smallest value in the vector and stored it in a variable. In end, I have added the two values and returned the sum.
Your code has a couple of issues: If the smallest number in the vector is the first, position will be uninitialized and cause UB (Undefined Behavior). If you'll initiazlie position to 0 as required, then again if the smallest number in the vector is the first, this line numbers.erase(numbers.begin() + position - 1) will attempt to use an iterator to before numbers.begin(). This is invalid. My solution below only keeps track of smallest and secondSmallest without having to modify the vector at all (and thus I can pass it by const&). It also requires only one traverse of the vector (and the complexity is O(n)). #include <iostream> #include <vector> #include <assert.h> long sumOfTwoSmallestNumbers(std::vector<int> const & numbers) { assert(numbers.size() >= 4); // The OP specified that in the question. int smallest = (numbers[0] < numbers[1]) ? numbers[0] : numbers[1]; int secondSmallest = (numbers[0] < numbers[1]) ? numbers[1] : numbers[0]; for (size_t i = 2; i < numbers.size(); ++i) { if (numbers[i] < smallest) { // Need to update both: secondSmallest = smallest; smallest = numbers[i]; } else if (numbers[i] < secondSmallest) { // Need to update only second: secondSmallest = numbers[i]; } } return (smallest + secondSmallest); } int main() { std::vector<int> v = { 1,4,7,2 }; auto s = sumOfTwoSmallestNumbers(v); std::cout << "sumOfTwoSmallestNumbers: " << s << std::endl; return 0; } Output: sumOfTwoSmallestNumbers: 3 A side note: it's better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.
72,327,344
72,327,376
How to check that they belong to the same class in c++ test Visual Studio?
I want to check if the constructor is initialized correctly, but I don't know which assert method to use TEST_METHOD(testInitNavigator) { Room room; INavigator navigator(room); Assert::AreSame(room, navigator.getLocalRoom()); }
I think it is correct so TEST_METHOD(testInitNavigator) { Room room; INavigator navigator(room); Assert::IsTrue(typeid(room).name() == typeid(navigator.getLocalRoom()).name()); }
72,327,932
72,327,992
Random Characters being stored in a file
I have created an Admins class with three data members (adminID, adminName, adminPhone) and an array of objects for that same class. The data of each object is to be stored in a .txt file. There is no run-time error and the program works as expected but upon opening the file in notepad, I found that there are random characters in the file. Here's the class declaration: class Admins { private: int adminID; char adminName[100]; char adminPhone[11]; public: Admins() { adminID = 0; strcpy(adminName, "NULL"); strcpy(adminPhone, "NULL"); } void addAdminData(); void writeAdminData(); void readAdminData(); }; This is the snippet for writing the data: void Admins::writeAdminData() { if(adminID == 0) cout<<"Admin Data not initialized"; else { ofstream fout; fout.open("AdminData.txt", ios::app); fout.write((char*)this, sizeof(*this)); fout.close(); } } This is what the file looked like: Aryan Soni šÐo ÿÿÿÿ šÐo ÿÿÿÿ @@ € ¶@ ØNr 583963728
Concept Those are not random character, instead they are the raw bytes of your class stored on stack-memory for a single instance and will be completely random in another instance of your application. In short, those "random" characters are garbage bytes beyond null terminating ('\0') character in your string. FIX fout.write((char*)this, sizeof(*this)); Change the above line to the below line: fout << this->adminID << this->adminName << this->adminPhone; You can format the data in order to read it again and parse it.
72,328,292
72,328,812
cmake, scribus - List all required libraries
I'm trying to build Scribus (1.5.8 and 1.7) from source in Ubuntu 20.04. It uses cmake as its build system. I have no experience with cmake. Is there a way to get a list of all the required and/or optional libraries from cmake or any command line tool? Right now, my "workflow" is the following: Run cmake . in source directory. If it fails, go to 3. Else, go to 7. Search error messages for mentions of missing libraries. Run apt search to find (hopefully) right library. Run apt install to install (hopefully) right library. Goto 1. Proceed. This is very tedious. My hope is to have something that just generates a list of libraries that cmake will look for. Ideally, this list could simply be given to apt install to pull in all the libraries. Although the scribus developers provide lists of required libraries in their wiki, these lists do not seem to be exhaustive or up to date. I tried using cmake --graphviz=foo.dot, but it only generates any output after I got cmake . to run successfully.
Is there a way to get a list of all the required and/or optional libraries from cmake or any command line tool? Not in an automated way. Generally that is not possible. There may be dependencies not managed by CMake, outside of CMake code, there may be dependencies of dependencies, and many corner cases. Also, there is no clear mapping between "library name" and "project name" (I mean, between .so or .a or .h ile and the actual project where it comes from). Generally, compiling a library requires (manual) knowledge about that library and the library dependencies. This is exactly the work that package maintainers in distributions do - they compile the libraries and list all library dependencies for package managers. While there come ever smarter "build systems", this is not a silver bullet, and C++ ecosystem is way too diverse. But sure - you google scribus, find the sources https://github.com/scribusproject/scribus , check the documentation, and find the dependencies of a project https://github.com/scribusproject/scribus/blob/master/BUILDING , all listed: Requirements: Qt >= 6.2 Freetype >= 2.1.7 (2.3.x strongly recommended) cairo >= 1.14.x harfbuzz = > 0.9.42 libicu libjpeg (depending on how Qt is packaged) libpng >= 1.6.0 libtiff >= 3.6.0 libxml2 >= 2.6.0 LittleCMS (liblcms) >= 2.0 (2.1+ recommended) poppler and poppler-cpp >= 0.62.0 hunspell Python >= 3.6 Recommended: CUPS Fontconfig >= 2.0 GhostScript >= 8.0 (9.0+ or greater preferred) tkinter for the font sampler script python-imaging for the font sampler preview pkgconfig (to assist finding other libraries) podofo - 0.7.0+ for enhanced Illustrator AI/EPS import, svn versions boost and boost-devel Build systems are still a huge way forward - with cmake . the library maintainer can display a fancy error message for users "Och - install libpng, it was not found", which makes it all pleasant. It is still way better than getting -lpng: not found messages from the compiler or linker. You could for example write a CMake configuration that lists all such messages, and errors later, so that users see them all.
72,328,810
72,330,784
How to check for current CMake build type in C++?
A little background: I'm writing a game in SFML and I want certain lines of code to be ommitted in Release build. I want to check during compile time for build type, so that is doesn't impact game's performance. void Tile::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform *= getTransform(); target.draw(m_sprite, states); #if(DEBUG) target.draw(m_collision_shape, states); #endif } I'm relatively new to CMake world, so I don't even know if it's possible. EDIT: It's probably worth mentioning I use ninja as a build system.
That's how you might do it in general (working for any generator): add_executable(${PROJECT_NAME} main.cpp) target_compile_definitions(${PROJECT_NAME} PRIVATE "DEBUG=$<IF:$<CONFIG:Debug>,1,0>") If you need it for every target you can use the following in the top CMake file (in case you have multiple with add_subdirectory) and before (it is not required but it is less confusing) you created a target. Also as Alex Reinking rightfully corrected we can use a simpler condition, because $<CONFIG:Debug> already gives 1 or 0. So applying everything described above we get something like this: add_compile_definitions("DEBUG=$<CONFIG:Debug>") add_executable(${PROJECT_NAME} main.cpp)
72,329,326
72,330,028
How to pass a 2D array by Reference to a function in C++
How do i pass array b1 in the function dfs, b1 is a 2D integer array used to track whether the node was visited. Sorry for the poor code readability. i want to pass it by reference as it needs to be modified by the function called recursively.Currently getting this error. Line 33: Char 94: error: 'b1' declared as array of references of type 'int &' void dfs(int i,int j,vector<vector<char>>& board,string word,int k,bool& yellow,int& b1[][]){ ^ 1 error generated. class Solution { public: bool exist(vector<vector<char>>& board, string word) { int m = board.size(); int n = board[0].size(); int b1[m][n]; list<pair<int,int>> mp; bool yellow=false; for(int i=0;i<board.size();i++){ for(int j=0;j<board[0].size();j++){ if(board[i][j]==word[0]){ mp.push_front({i,j}); } } } for(auto itr=mp.begin();itr!=mp.end();itr++){ int i=itr->first; int j=itr->second; dfs(i,j,board,word,0,yellow,b1); if(yellow==true){ return yellow; } memset(b1,0,sizeof(b1)); } return yellow; } void dfs(int i,int j,vector<vector<char>>& board,string word,int k,bool& yellow,int& b1[][]){ int m = board.size()-1; int n = board[0].size()-1; b1[i][j]=1; if(k==word.size()-1){ yellow=true; } if(i+1<=m && board[i+1][j]==word[k+1] &&b1[i+1][j]==0){ dfs(i+1,j,board,word,k+1,yellow,b1); } if(i-1>=0 && board[i-1][j]==word[k+1] &&b1[i-1][j]==0){ dfs(i-1,j,board,word,k+1,yellow,b1); } if(j+1<=n && board[i][j+1]==word[k+1]&& b1[i][j+1]==0){ dfs(i,j+1,board,word,k+1,yellow,b1); } if(j-1>=0 && board[i][j-1]==word[k+1] && b1[i][j-1]==0){ dfs(i,j-1,board,word,k+1,yellow,b1); } } };
Since you already use vector<vector<char>>& board as one parameter, the simplest way to fix this error is to use vector<vector<int>> b1 instead of int b1[m][n]. Please take care of VLAs like int a[n][m], it's not easy to maintain and also not recommended. See more at Why aren't variable-length arrays part of the C++ standard?. Here is my example to replace your b1 with a 2D vector. class Solution { public: bool exist(vector<vector<char>> &board, string word) { int m = board.size(); int n = board[0].size(); // int b1[m][n]; vector<vector<int>> b1(m, vector<int>(n, 0)); list<pair<int, int>> mp; bool yellow = false; for (int i = 0; i < board.size(); i++) { for (int j = 0; j < board[0].size(); j++) { if (board[i][j] == word[0]) { mp.push_front({i, j}); } } } for (auto itr = mp.begin(); itr != mp.end(); itr++) { int i = itr->first; int j = itr->second; dfs(i, j, board, word, 0, yellow, b1); if (yellow == true) { return yellow; } // memset(b1, 0, sizeof(b1)); for (auto &row: b1) { std::fill(row.begin(), row.end(), 0); } } return yellow; } // void dfs(int i,int j,vector<vector<char>>& board,string word,int k,bool& yellow,int& b1[][]){ void dfs(int i, int j, vector<vector<char>> &board, string word, int k, bool &yellow, vector<vector<int>> &b1) { int m = board.size() - 1; int n = board[0].size() - 1; b1[i][j] = 1; if (k == word.size() - 1) { yellow = true; } if (i + 1 <= m && board[i + 1][j] == word[k + 1] && b1[i + 1][j] == 0) { dfs(i + 1, j, board, word, k + 1, yellow, b1); } if (i - 1 >= 0 && board[i - 1][j] == word[k + 1] && b1[i - 1][j] == 0) { dfs(i - 1, j, board, word, k + 1, yellow, b1); } if (j + 1 <= n && board[i][j + 1] == word[k + 1] && b1[i][j + 1] == 0) { dfs(i, j + 1, board, word, k + 1, yellow, b1); } if (j - 1 >= 0 && board[i][j - 1] == word[k + 1] && b1[i][j - 1] == 0) { dfs(i, j - 1, board, word, k + 1, yellow, b1); } } };
72,329,370
72,329,607
GLM linking in CMakeLists.txt
I cannot link glm library with my executable. I tried link via ${GLM_INCLUDE_DIRS}, ${GLM_LIBRARIES} and ${GLM_LIBRARY_DIRS} cmake variables but it does not work. How can I link libraries and inludes of glm with my executable? I am using find_package() method : find_package(glm REQUIRED PATHS "${GLM_BINARY_DIR}" NO_DEFAULT_PATH) And does not have any problem with find_package() but these status messages below displays nothing : message(STATUS "GLM includes ${GLM_INCLUDE_DIRS}") message(STATUS "GLM libraries ${GLM_LIBRARY_DIRS}")
Config script for GLM defines IMPORTED target glm::glm. So the correct way for use GLM in CMake code is to link with that target. This is explicitly written in the documentation: set(glm_DIR <installation prefix>/lib/cmake/glm) # if necessary find_package(glm REQUIRED) target_link_libraries(<your executable> glm::glm) Variables like GLM_LIBRARIES or GLM_INCLUDE_DIRS are usually defined by Find scripts (shipped with CMake or with the consumer project). Config scripts, shipped with the installed package, normally defines IMPORTED targets. GLM doesn't have a Find script (see FindGLM.cmake not in glm 0.9.7, is it a deprecated way to find libraries in CMAKE?), and PATHS option in find_package invocation explicitly requests Config script.
72,329,441
72,329,564
Not Displaying Spaces
I'm very new to c++ and everything in general. I dont understand why my code doesn't work: #include <cstdio> int main(){ int a; scanf("%d", &a); for(int i = 1; i < a; i++){ printf(" "); } printf("*"); } what I'm trying to do is make the number of spaces as the value inputted by the user minus and add a * at the end so if a = 10 : * but when I try it the spaces don't show. Ideally what I'm trying to do is get an output something like: * ** *** **** The length depends on user input if it was 10 then the spaces would be 9 and the * at the end would be the tenth.
You will have to use 3 for-loops (two of them nested inside one). The parent for loop for each row. And the nested two are for spaces and stars. #include <cstdio> int main() { int a; scanf("%d", &a); for(int i=1; i<a; i++) { for(int j=i; j<a; j++) printf(" "); for(int k=0; k<i; k++) printf("*"); printf("\n"); } return 0; } You will get your desired output if you put the value 5 for a, i.e., a=5. To learn more in detail, you can follow this link star patterns in c Your code may contain many errors. That's understandable, cause you are new to C/C++. Try problem-solving in beecrowd to improve your problem-solving capabilities and learn C/C++ in a better way. These errors will automatically go away day by day as you progress. But the secret is to practice and never give up. Good luck!
72,329,583
72,329,635
concept std::derived_from when the argument is a smart pointer
I have a few functions like so bool RegisterModel (std::shared_ptr<DerivedA> model) { } bool RegisterModel (std::shared_ptr<DerivedB> model) { } and i would like to make use of c++ 20 concepts and implement it like this: bool RegisterModel (std::derived_from<BaseClass> auto model) { } This does not work, because i'm passing in shared pointers. It is somehow possible to require a shared pointer that holds an object derived from BaseClass?
Deduce the T from a std::shared_ptr<T> and constrain that: template<std::derived_from<BaseClass> T> bool RegisterModel (std::shared_ptr<T> model) { }
72,329,682
72,329,806
How to define static method in a cpp file. (C++)
I wan to have my class in a separate .h file, and the implementation in a .cpp file. The problem I run into is "Multiple definition of methodname". If I put the content of both files in a .hpp file it works, but I'm not sure if I should use that. The .h File: #pragma once class Nincs; class Sugar { public: Sugar(){} }; class Nincs : public Sugar { private: static Nincs* ins; Nincs(): Sugar() {}; public: static Nincs* instance(); }; the .cpp File: #include "Sugar.h" Nincs* Nincs::ins = nullptr; Nincs* Nincs::instance() //the error is with this line { if (ins == nullptr) { ins = new Nincs(); } return ins; }; The main .cpp file: #include <iostream> #include "Sugar.cpp" using namespace std; int main() { Nincs* n = Nincs::instance(); return 0; } Basically, I am struggling with making a simple singleton class in C++.
The problem is that you're including the source file(Sugar.cpp) instead of the header file(Sugar.h). To solve this inside main.cpp, change #include "Sugar.cpp" to: #include "Sugar.h" Also it is recommended that we should never include source files. Working demo
72,329,739
72,329,812
Assigning std::minmax result to new variables
auto [x, y] = std::minmax(a, b) defines x and y as references to a and b (or b and a). How do I make x and y new variables initialized with min and max values respectively (as if minmax returned pair of values instead of pair of refs)?
You can use the overload of the std::initializer_list version, which returns pair<T, T>. auto [x, y] = std::minmax({a, b});
72,329,759
72,331,822
Constexpr function returning member of union: g++ vs. clang++: no diagnostics vs. error
Consider this code: typedef union { float v; unsigned u; } T; constexpr T x = { .u = 0 }; constexpr float f(void) { return x.v; } Is this code valid? Invocations: $ g++ t506a.cpp -c -std=c++20 -pedantic -Wall -Wextra <nothing> $ clang++ t506a.cpp -c -std=c++20 -pedantic -Wall -Wextra t506a.cpp:3:17: error: constexpr function never produces a constant expression [-Winvalid-constexpr] constexpr float f(void) ^ t506a.cpp:5:9: note: read of member 'v' of union with active member 'u' is not allowed in a constant expression return x.v; ^ 1 error generated. Which compiler is correct?
Both compilers are correct, even though the code is ill-formed, because no diagnostic is required in the program you've shown. It's true that f can never be evaluated as a core constant expression, but in that case dcl.constexpr#6 applies: For a constexpr function or constexpr constructor that is neither defaulted nor a template, if no argument values exist such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression, or, for a constructor, an evaluated subexpression of the initialization full-expression of some constant-initialized object ([basic.start.static]), the program is ill-formed, no diagnostic required. (emphasis mine) Since no diagnostic is required, GCC is allowed to not diagnose this. On the other hand, if you do attempt to evaluate f as a constant, e.g. constexpr float a = f(); then it violates expr.const#5.10: An expression E is a core constant expression unless the evaluation of E, following the rules of the abstract machine ([intro.execution]), would evaluate one of the following: an lvalue-to-rvalue conversion that is applied to a glvalue that refers to a non-active member of a union or a subobject thereof; and indeed, both GCC and Clang diagnose this error, as required during constant evaluation.
72,329,888
72,330,013
Linker error: /usr/bin/ld: cannot find -lcudart_static while trying to compile CUDA code with clang
I tried to compile a axpy.cu file as specified in the official docs here: clang++ axpy.cu -o exec --cuda-gpu-arch=sm_60 -L/usr/local/cuda -lcudart_static -ldl -lrt -pthread But that gave a linker error and warning: clang: warning: Unknown CUDA version. cuda.h: CUDA_VERSION=11060. Assuming the latest supported version 10.1 [-Wunknown-cuda-version] /usr/bin/ld: cannot find -lcudart_static clang: error: linker command failed with exit code 1 (use -v to see invocation) I have clang version 11 installed. On running: nvidia-smi I get: I read somewhere that I need to add a symbolic link to libcudart file or something if that helps. I get the following output on running: ld -lcudart_static --verbose attempt to open /usr/local/lib/x86_64-linux-gnu/libcudart_static.so failed attempt to open /usr/local/lib/x86_64-linux-gnu/libcudart_static.a failed attempt to open /lib/x86_64-linux-gnu/libcudart_static.so failed attempt to open /lib/x86_64-linux-gnu/libcudart_static.a failed attempt to open /usr/lib/x86_64-linux-gnu/libcudart_static.so failed attempt to open /usr/lib/x86_64-linux-gnu/libcudart_static.a failed attempt to open /usr/lib/x86_64-linux-gnu64/libcudart_static.so failed attempt to open /usr/lib/x86_64-linux-gnu64/libcudart_static.a failed attempt to open /usr/local/lib64/libcudart_static.so failed attempt to open /usr/local/lib64/libcudart_static.a failed attempt to open /lib64/libcudart_static.so failed attempt to open /lib64/libcudart_static.a failed attempt to open /usr/lib64/libcudart_static.so failed attempt to open /usr/lib64/libcudart_static.a failed attempt to open /usr/local/lib/libcudart_static.so failed attempt to open /usr/local/lib/libcudart_static.a failed attempt to open /lib/libcudart_static.so failed attempt to open /lib/libcudart_static.a failed attempt to open /usr/lib/libcudart_static.so failed attempt to open /usr/lib/libcudart_static.a failed attempt to open /usr/x86_64-linux-gnu/lib64/libcudart_static.so failed attempt to open /usr/x86_64-linux-gnu/lib64/libcudart_static.a failed attempt to open /usr/x86_64-linux-gnu/lib/libcudart_static.so failed attempt to open /usr/x86_64-linux-gnu/lib/libcudart_static.a failed ld: cannot find -lcudart_static attempt to open /usr/local/lib/x86_64-linux-gnu/libcudart_static.so failed attempt to open /usr/local/lib/x86_64-linux-gnu/cudart_static.a failed attempt to open /lib/x86_64-linux-gnu/libcudart_static.so failed attempt to open /lib/x86_64-linux-gnu/cudart_static.a failed attempt to open /usr/lib/x86_64-linux-gnu/libcudart_static.so failed attempt to open /usr/lib/x86_64-linux-gnu/cudart_static.a failed attempt to open /usr/lib/x86_64-linux-gnu64/libcudart_static.so failed attempt to open /usr/lib/x86_64-linux-gnu64/cudart_static.a failed attempt to open /usr/local/lib64/libcudart_static.so failed attempt to open /usr/local/lib64/cudart_static.a failed attempt to open /lib64/libcudart_static.so failed attempt to open /lib64/cudart_static.a failed attempt to open /usr/lib64/libcudart_static.so failed attempt to open /usr/lib64/cudart_static.a failed attempt to open /usr/local/lib/libcudart_static.so failed attempt to open /usr/local/lib/cudart_static.a failed attempt to open /lib/libcudart_static.so failed attempt to open /lib/cudart_static.a failed attempt to open /usr/lib/libcudart_static.so failed attempt to open /usr/lib/cudart_static.a failed attempt to open /usr/x86_64-linux-gnu/lib64/libcudart_static.so failed attempt to open /usr/x86_64-linux-gnu/lib64/cudart_static.a failed attempt to open /usr/x86_64-linux-gnu/lib/libcudart_static.so failed attempt to open /usr/x86_64-linux-gnu/lib/cudart_static.a failed Can someone help with this?
So I found a solution. Apparently the linker wasnt able to locate libcudart binary. So used find to get its location: find /usr/ -name libcudart_static* Got its path as: /usr/local/cuda-11.6/targets/x86_64-linux/lib/libcudart_static.a (might be different for you). Just linked this path by using -L flag in the compilation command. New command: clang++ axpy.cu -o exec --cuda-gpu-arch=sm_60 -L/usr/local/cuda -L/usr/local/cuda-11.6/targets/x86_64-linux/lib/ -lcudart_static -ldl -lrt -pthread
72,330,319
72,498,375
error: cannot open source file "winrt/WIndows.Foundation" showed up when I follow a microsoft's tutorial
I'm a complete beginner in Visual Studio and C++. And now, I'm trying to follow this tutorial by Microsoft. So I installed "c++/WinRT templates and visualizer" in my Visual Studio 2019 from the "Extension" menu above the visual studio and created a core app project. However, when I run the project, visual Studio shows up lots of errors like "cannot open source file "winrt/Windows.Foundation.h".(I tried to follow this section ) I suspect that these errors are environment variable issues. But I don't have any idea of where I should change. Currently, I install Visual Studio in D drive and create the project in D drive. But there's a possibility that other required software like windows SDK(?) are installed in C Drive. If there is other information required to solve these errors, I'm willing to add it to this post. I'm terribly stuck here(like a lost child). I'm not sure even asking this question here is acceptable. But if you help me, I would appreciate it a lot.
As @IInspectable said in the comment, I need to compile my codes at least once when I create C++/winRT project. After I compile my project, NuGet package generates C++/winRT headers automatically!
72,330,356
72,330,615
Converte int to char*
int num = 123; char num_charr[sizeof(char)]; std::sprintf(num_char, "%d", num); how to convert int the same way without using sprintf? I Only Need The Code To Convert Without print.
char num_charr[12]; // space for INT_MIN value -2147483648 itoa( num, num_charr, 10 ); Note: itoa is not supported on all compilers.
72,330,697
72,331,392
Opengl only binds buffers from function that created them
I'm trying to write a very barebones game engine to learn how they work internally and I've gotten to the point where I have a "client" app sending work to the engine. This works so far but the problem I am having is that my test triangle only renders when I bind the buffer from the "main" function (or wherever the buffers were created) This is even the case when the buffers are abstracted and have the same function with the same member values (validated using clion's debugger) but they still have to be bound in the function that created them for example I have this code to create the buffers and set their data ... Venlette::Graphics::Buffer vertexBuffer; Venlette::Graphics::Buffer indexBuffer; vertexBuffer.setTarget(GL_ARRAY_BUFFER); indexBuffer.setTarget(GL_ELEMENT_ARRAY_BUFFER); vertexBuffer.setData(vertices, sizeof(vertices)); indexBuffer.setData(indices, sizeof(indices)); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float)*2, nullptr); ... where vertices is a c array of 6 floats and indices being 3 unsigned int's the buffers are then passed to a "context" to be stored for rendering later using the following code ... context.addBuffer(vertexBuffer); context.addBuffer(indexBuffer); context.setNumVertices(3); context.setNumIndices(3); context. ... which calls: addBuffer Task& task = m_tasks.back(); task.buffers.push_back(std::move(buffer)); this again, works. The buffers are stored correctly, the buffers still exist when the code reaches here and nothing is wrong. then it gets to the drawing part where the buffers are: bound, drawn, then unbound, as shown ... for (auto& buffer : task.buffers) { buffer.upload(); buffer.bind(); } glDrawElements(GL_TRIANGLES, task.numIndices, GL_UNSIGNED_INT, nullptr); for (auto& buffer : task.buffers) { buffer.unbind(); } ... bind and unbind being these functions void Buffer::bind() const noexcept { if (m_id == -1) return; glBindBuffer(m_target, m_id); spdlog::info("bind() -{}-{}-", m_id, m_target); } void Buffer::unbind() const noexcept { if (m_id == -1) return; glBindBuffer(m_target, 0); spdlog::info("unbind() -{}-{}-", m_id, m_target); } but this is where nothing works. If I call buffer.bind() from the "doWork" function where the buffers are drawn, nothing renders, but if I call buffer.bind() from the main function I get a white triangle in the middle of the screen Even when I bound then unbound the buffers from the main buffer encase that was the issue it still doesn't draw. Only when the buffers are bound and remain bound from the main function, that is draws a pastebin of the full code (no headers) pastebin Does anyone know why this happens, even if you don't know how to fix it. is it something to do with buffer lifetime, or with moving the buffer into the vector? it is just buffer.bind() that doesn't work, uploading data works from the context, just not binding it
You seem to not bind the vertex buffer to the GL_ARRAY_BUFFER buffer binding point before calling glVertexAttribPointer. glVertexAttribPointer uses the buffer bound to GL_ARRAY_BUFFER in order to know which buffer is the vertex attribute source for that generic vertex attribute. So, you should bind the vertexBuffer before calling glVertexAttribPointer.
72,331,168
72,344,118
c++ windows application edit the main window
I'm trying to create a simple windows application in cpp. Opening Visual Studio 2019, I noticed that there is, in fact, a project like that, so I opened up a new one. This is the window I get when I run it. Completely normal, as expected from a brand new project. But... I can't figure out how to edit the main window? When I go into the project rc directory, there's options to edit everything else. Add new dialogue boxes, add proper gui to them, edit the top bar with new options, etc. Does anyone know where is the gui for editing the main window?
1.Right click on your project and Add resource -> Dialog. IDD_DIALOG1 is created by default. 2.Modify the code in InitInstance() : HWND hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), GetDesktopWindow(), (DLGPROC)WndProc); 3.There is a IDD_DIALOG1 in the Resource View and it can be edited by double click.
72,331,247
73,897,665
How to get all tags from a tiff file with libtiff?
I have a tiff file and would like to get a list of all tags used in that file. If I understand the TiffGetField() function correctly, it only gets the values of tags specified. But how do I know what tags the file uses? I would like to get all used tags in the file. Is there an easy way to get them with libtiff?
It seems to be a very manual process from my experience. I used the TIFF tag reference here https://www.awaresystems.be/imaging/tiff/tifftags.html to create a custom structure typedef struct { TIFF_TAGS_BASELINE Baseline; TIFF_TAGS_EXTENSION Extension; TIFF_TAGS_PRIVATE Private; } TIFF_TAGS; With each substructure custom defined. For example, typedef struct { TIFF_UINT32_T NewSubfileType; // TIFFTAG_SUBFILETYPE TIFF_UINT16_T SubfileType; // TIFFTAG_OSUBFILETYPE TIFF_UINT32_T ImageWidth; // TIFFTAG_IMAGEWIDTH TIFF_UINT32_T ImageLength; // TIFFTAG_IMAGELENGTH TIFF_UINT16_T BitsPerSample; // TIFFTAG_BITSPERSAMPLE ... char *Copyright; // TIFFTAG_COPYRIGHT } TIFF_TAGS_BASELINE; Then I have custom readers: TIFF_TAGS *read_tiff_tags(char *filename) { TIFF_TAGS *tags = NULL; TIFF *tif = TIFFOpen(filename, "r"); if (tif) { tags = calloc(1, sizeof(TIFF_TAGS)); read_tiff_tags_baseline(tif, tags); read_tiff_tags_extension(tif, tags); read_tiff_tags_private(tif, tags); TIFFClose(tif); } return tags; } Where you have to manually read each field. Depending on if it's an array, you'll have to check the return status. For simple fields, it's something like // The number of columns in the image, i.e., the number of pixels per row. TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &tags->Baseline.ImageWidth); but for array fields you'll need something like this // The scanner model name or number. status = TIFFGetField(tif, TIFFTAG_MODEL, &infobuf); if (status) { len = strlen(infobuf); tags->Baseline.Model = malloc(sizeof(char) * (len + 1)); _mysprintf(tags->Baseline.Model, (int)(len + 1), "%s", infobuf); tags->Baseline.Model[len] = 0; } else { tags->Baseline.Model = NULL; } // For each strip, the byte offset of that strip. status = TIFFGetField(tif, TIFFTAG_STRIPOFFSETS, &arraybuf); if (status) { tags->Baseline.NumberOfStrips = TIFFNumberOfStrips(tif); tags->Baseline.StripOffsets = calloc(tags->Baseline.NumberOfStrips, sizeof(TIFF_UINT32_T)); for (strip = 0; strip < tags->Baseline.NumberOfStrips; strip++) { tags->Baseline.StripOffsets[strip] = arraybuf[strip]; } } else { tags->Baseline.StripOffsets = NULL; } My suggestion is to only read the fields you want/need and ignore everything else. Hope that helps.
72,331,290
72,332,623
gcov produces different results on Clang and GCC
I'm trying to understand how to properly structure a C++ project by using CMake, googletest, and gcov for test coverage. I would like to build a general CMakeLists.txt that would work for any platform/compiler. This is my first attempt. However, if I try to build the project and then run lcov (to generate the report), I see that I have different results if I use CLang (right result) or GCC (wrong result). Note that I'm on MacOs and I installed gcc through brew (brew install gcc). Moreover I used the following flags in my main CMakeLists.txt: if(CODE_COVERAGE) SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-arcs -ftest-coverage" ) endif() Note: If you find something wrong/weird in my CMakeLists.txt files or lcov usage, I'm open to any kind of feedback! My library #include "library.h" #include <iostream> void foo(){ std::cout << "Foo!" << std::endl; } void bar(int n){ if (n > 0){ std::cout << "n is grater than 0!" << std::endl; } else if (n < 0){ std::cout << "n is less than 0!" << std::endl; } else{ std::cout << "n is exactly 0!" << std::endl; } } void baz(){ // LCOV_EXCL_START std::cout << "Baz!" << std::endl; } // LCOV_EXCL_STOP My tests #ifndef GCOV_TUTORIAL_TEST_LIBRARY_H #define GCOV_TUTORIAL_TEST_LIBRARY_H #include "../src/library.h" #include <gtest/gtest.h> namespace gcov_tutorial::tests { TEST(TestFooSuite,TestFoo){ foo(); } TEST(TestBarSuite,TestBarGreaterThanZero){ bar(100); } TEST(TestBarSuite,TestBarEqualToZero){ //bar(0); } TEST(TestBarSuite,TestBarLessThanZero){ bar(-100); } } #endif //GCOV_TUTORIAL_TEST_LIBRARY_H CLang Compilation #!/bin/bash # Rationale: https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/ set -euxo pipefail # BASE_DIR is the project's directory, containing the src/ and tests/ folders. BASE_DIR=$PWD COVERAGE_FILE=coverage.info GCOV_PATH=/usr/bin/gcov CLANG_PATH=/usr/bin/clang CLANGPP_PATH=/usr/bin/clang++ rm -rf build mkdir build && cd build # Configure cmake -DCMAKE_C_COMPILER=$CLANG_PATH -DCMAKE_CXX_COMPILER=$CLANGPP_PATH -DCODE_COVERAGE=ON -DCMAKE_BUILD_TYPE=Release .. # Build (for Make on Unix equivalent to `make -j $(nproc)`) cmake --build . --config Release # Clean-up for any previous run. rm -f $COVERAGE_FILE lcov --zerocounters --directory . # Run tests ./tests/RunTests # Create coverage report by taking into account only the files contained in src/ lcov --capture --directory tests/ -o $COVERAGE_FILE --include "$BASE_DIR/src/*" --gcov-tool $GCOV_PATH # Create HTML report in the out/ directory genhtml $COVERAGE_FILE --output-directory out # Show coverage report to the terminal lcov --list $COVERAGE_FILE # Open HTML open out/index.html GCC Compilation #!/bin/bash # Rationale: https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/ set -euxo pipefail # BASE_DIR is the project's directory, containing the src/ and tests/ folders. BASE_DIR=$PWD COVERAGE_FILE=coverage.info GCOV_PATH=/usr/local/bin/gcov-11 GCC_PATH=/usr/local/bin/gcc-11 GPP_PATH=/usr/local/bin/g++-11 rm -rf build mkdir build && cd build # Configure cmake -DCMAKE_C_COMPILER=$GCC_PATH -DCMAKE_CXX_COMPILER=$GPP_PATH -DCODE_COVERAGE=ON -DCMAKE_BUILD_TYPE=Release .. # Build (for Make on Unix equivalent to `make -j $(nproc)`) cmake --build . --config Release # Clean-up for any previous run. rm -f $COVERAGE_FILE lcov --zerocounters --directory . # Run tests ./tests/RunTests # Create coverage report by taking into account only the files contained in src/ lcov --capture --directory tests/ -o $COVERAGE_FILE --include "$BASE_DIR/src/*" --gcov-tool $GCOV_PATH # Create HTML report in the out/ directory genhtml $COVERAGE_FILE --output-directory out # Show coverage report to the terminal lcov --list $COVERAGE_FILE # Open HTML open out/index.html
You are actually asking two questions, here. Why do the coverage results differ between these two compilers? How do I structure a CMake project for code coverage? Answer 1: Coverage differences The simple answer here is that you are building in Release mode, rather than RelWithDebInfo mode. GCC does not put as much debugging information in by default as Clang does. On my system, adding -DCMAKE_CXX_FLAGS="-g" to your build-and-run-cov-gcc.sh script yields the same results as Clang, as does building in RelWithDebInfo. For whatever reason, it appears that Clang tracks more debug information either by default or when coverage is enabled. GCC does not have these same guardrails. The lesson to take away is this: collecting coverage information is a form of debugging; you must use a debugging-aware configuration for your compiler if you want accurate results. Answer 2: Build system structure It is generally a terrible idea to set CMAKE_CXX_FLAGS inside your build. That variable is intended to be a hook for your build's users to inject their own flags. As I detail in another answer on this site, the modern approach to storing such settings is in the presets I would get rid of the if (CODE_COVERAGE) section of your top-level CMakeLists.txt and then create the following CMakePresets.json file: { "version": 4, "cmakeMinimumRequired": { "major": 3, "minor": 23, "patch": 0 }, "configurePresets": [ { "name": "gcc-coverage", "displayName": "Code coverage (GCC)", "description": "Enable code coverage on GCC-compatible compilers", "binaryDir": "${sourceDir}/build", "cacheVariables": { "CMAKE_BUILD_TYPE": "RelWithDebInfo", "CMAKE_CXX_FLAGS": "-fprofile-arcs -ftest-coverage" } } ], "buildPresets": [ { "name": "gcc-coverage", "configurePreset": "gcc-coverage", "configuration": "RelWithDebInfo" } ] } Then your build script can be simplified considerably. #!/bin/bash # Rationale: https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/ set -euxo pipefail # Set up defaults for CC, CXX, GCOV_PATH export CC="${CC:-gcc-11}" export CXX="${CXX:-g++-11}" : "${GCOV_PATH:=gcov-11}" # Record the base directory BASE_DIR=$PWD # Clean up old build rm -rf build # Configure cmake --preset gcc-coverage # Build cmake --build --preset gcc-coverage # Enter build directory cd build # Clean-up counters for any previous run. lcov --zerocounters --directory . # Run tests ./tests/RunTests # Create coverage report by taking into account only the files contained in src/ lcov --capture --directory tests/ -o coverage.info --include "$BASE_DIR/src/*" --gcov-tool $GCOV_PATH # Create HTML report in the out/ directory genhtml coverage.info --output-directory out # Show coverage report to the terminal lcov --list coverage.info # Open HTML open out/index.html The key here is the following lines: # Configure cmake --preset gcc-coverage # Build cmake --build --preset gcc-coverage This script now lets you vary the compiler and coverage tool via environment variables and the CMakeLists.txt doesn't have to make any assumptions about what compiler is being used. On my (Linux) system, I can run the following commands successfully: $ CC=gcc-12 CXX=g++-12 GCOV=gcov-12 ./build-and-run-cov.sh $ CC=clang-13 CXX=clang++-13 GCOV=$PWD/llvm-cov-13.sh ./build-and-run-cov.sh Where llvm-cov-13.sh is a wrapper for llvm-cov-13 for compatibility with the --gcov-tool flag. See this answer for more detail. #!/bin/bash exec llvm-cov-13 gcov "$@" As you can see, the results are indistinguishable now that the correct flags are used.
72,331,313
72,331,344
C++ raw string with special char
I want to output a string like this: onclick="func()". So I wrote the following code: std::string s = R"( onclick="func()" )"; But here two )" let the compiler confused. Please forgive me if it's a silly question. I googled but found nothing (I don't know which keyword I should use when I googled).
Simply add a unique string outside the () std::string s = R"anystring( onclick="func()" )anystring";
72,331,773
72,331,819
Declaration of template specialization on a template function
I'm getting undefined reference to ´long long fromBigEndin<long long>(unsigned char*)´ for a template specialization. See code here: https://onlinegdb.com/AagKTQJ2B I have this structure: util.h template <class T> T fromBigEndin(uint8_t *buf); template <> int64_t fromBigEndin<int64_t>(uint8_t *buf); template <> long long fromBigEndin<long long>(unsigned char *buf); util.cpp template<class T> T fromBigEndin(uint8_t *buf) { T number = 0; uint8_t nBytes = sizeof(T); uint8_t i; for (i = 0; i < nBytes; i += 1) { number += buf[i] << (16 * (nBytes - i - 1)); } return number; } headerImpl.h #include "util.h" void handleOpenSession(uint8_t *data) { uint8_t *uid = (uint8_t *)malloc(8); memcpy(uid, data + 1, 8); int64_t uidNbr = fromBigEndin<int64_t>(uid); } From @AnoopRana response, putting the implementation in header file works, I would like to know if it is possible to put the implementation in a separate file. Any idea on how could I force the compilation of fromBigEndin<int64_t>()? I've also tried to move the specializations to util.cpp but doesn't work either. The code itself works when in a single file and with different declarations: https://www.mycompiler.io/view/9YRi89BnZa0 https://www.mycompiler.io/view/HvvI1H6RUWi
Method 1 You need to put the implementation of the function template into the header file itself. So it would look something like: util.h #pragma once //include guard added template <class T> T fromBigEndin(uint8_t *buf); //definition template <> int64_t fromBigEndin<int64_t>(uint8_t *buf) { return 53; } //definition template <> long long fromBigEndin<long long>(unsigned char *buf) { return 54; } //implementation in header file itself template<class T> T fromBigEndin(uint8_t *buf) { T number = 0; uint8_t nBytes = sizeof(T); uint8_t i; for (i = 0; i < nBytes; i += 1) { number += buf[i] << (16 * (nBytes - i - 1)); } return number; } headerImpl.h #pragma once #include "util.h" void handleOpenSession(uint8_t *data) { //add code here } main.cpp #include <iostream> #include "util.h" int main() { return 0; } Working demo Method 2 Here we make use of explicit template instantiations. util.h #pragma once #include <cstdint> template <class T> T fromBigEndin(uint8_t *buf); headerImpl.h #pragma once #include "util.h" void handleOpenSession(uint8_t *data) { uint8_t *uid = (uint8_t *)malloc(8); memcpy(uid, data + 1, 8); int64_t uidNbr = fromBigEndin<int64_t>(uid); } util.cpp #include "util.h" template<class T> T fromBigEndin(uint8_t *buf) { T number = 0; uint8_t nBytes = sizeof(T); uint8_t i; for (i = 0; i < nBytes; i += 1) { number += buf[i] << (16 * (nBytes - i - 1)); } return number; } //no angle brackets used here template int64_t fromBigEndin<int64_t>(uint8_t *buf); template long long fromBigEndin<long long>(unsigned char *buf); main.cpp #include <iostream> #include "util.h" int main() { return 0; } Working demo
72,331,799
72,331,836
Best way to implement fixed size array in C++
I am trying to implement a fixed size array of 32 bit integers, but the size is determined at runtime so it has to be heap allocated. Would it be more efficient to use a c++ std::vector and use vector.reserve() or should I use the conventional way of doing it using new int32_t[size]? Additionally, would it be worth using a unique_ptr with the conventional method using new?
You would just be re-implementing std::vector. Probably badly because it takes years to figure out all the little corner cases and implement them correctly.
72,332,210
72,332,272
Passing c++ map by reference and see changes after insert
Hey guys! I'm just getting into c++ and after learning stuff about reference and value pass I've come across a problem. So basically I'm trying to copy a map and I do so in my method. So far the size of the 2 maps are the same. The problem comes when I insert some new values into the original map because it doesn't change the copied map. So my question is how do I copy/pass a map, with the new map being a real copy and when the original changes, the copied version does so. I'll attach the code that I was working on. The code: #include <iostream> #include <map> using namespace std; map<string, int> passMapByReference(map<string, int>& temp_map){ return temp_map; } void printMap(map<string, int>& temp_map ){ cout << temp_map.size() << endl; } int main() { map<string, int> copyMap; map<string, int> map; map["asd"] = 1; map["dsa"] = 2; printMap(map); copyMap = passMapByReference(map); printMap(copyMap); map["ksdbj"] = 3; map["askdnijabsd"] = 4; printMap(map); //this should print 4 printMap(copyMap); return 0; } The output: 2 2 4 2
map and copyMap are separate objects and so changing one won't affect other. Moreover, you're returning the map by value from the function passMapByReference. Instead you could return the map by reference from passMapByReference as shown below: #include <iostream> #include <map> #include <string> //------------------------v------->return by reference std::map<std::string, int>& passMapByReference(std::map<std::string, int>& temp_map){ return temp_map; } void printMap(std::map<std::string, int>& temp_map ){ std::cout << temp_map.size() << std::endl; } int main() { std::map<std::string, int> map; map["asd"] = 1; map["dsa"] = 2; printMap(map); //copyMap is an lvalue reference to passMapByReference std::map<std::string, int>& copyMap = passMapByReference(map); printMap(copyMap); map["ksdbj"] = 3; map["askdnijabsd"] = 4; printMap(map); printMap(copyMap);//prints 4 } Working demo The output of the above program is: 2 2 4 4 Note I noticed that you have used using namespace std; and then created a map with the name map. This should be avoided as it creates confusion. For example, it becomes hard to see whether the map you're referring to is a std::map or the variable named map. I would recommend using std:: to qualify the standard contianers instead of using using namespace std;. Refer to Why is "using namespace std;" considered bad practice?
72,332,376
72,332,788
Debian, cmake, connot compile c++ program, missing config cmake file
Trying to compile dot11decrypt on debian, installed apt-get install libtins4.0 and apt-get install libtins-dev, but cmake .. can't find package libtins, heres the error: CMake Error at CMakeLists.txt:4 (FIND_PACKAGE): By not providing "Findlibtins.cmake" in CMAKE_MODULE_PATH this project has asked CMake to find a package configuration file provided by "libtins", but CMake did not find one. Could not find a package configuration file provided by "libtins" with any of the following names: libtinsConfig.cmake libtins-config.cmake Add the installation prefix of "libtins" to CMAKE_PREFIX_PATH or set "libtins_DIR" to a directory containing one of the above files. If "libtins" provides a separate development package or SDK, be sure it has been installed. -- Configuring incomplete, errors occurred! See also "/home/user/dot11decrypt/build/CMakeFiles/CMakeOutput.log". cat:dot11decrypt/CMakeLists.txt 1. CMAKE_MINIMUM_REQUIRED(VERSION 2.8.1) 2. PROJECT(dot11decrypt) 3. 4. FIND_PACKAGE(libtins REQUIRED) 5. 6. SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x") 7. 8. ADD_EXECUTABLE(dot11decrypt dot11decrypt.cpp) 9. TARGET_LINK_LIBRARIES(dot11decrypt ${LIBTINS_LIBRARIES} pthread) find / -name Findlibtins.cmake or libtinsConfig.cmake brings no result. I found those files on internet but still no success, i think i have to install something but don't know what.
You don't need to compile from source... find_package is a very flexible configuration point! You'll just need to provide your own find module that is sufficient for the build. Fortunately, this is very simple. Here's what I did: $ https://github.com/mfontanini/dot11decrypt $ cd dot11decrypt $ mkdir _patches $ vim _patches/Findlibtins.cmake $ cat _patches/Findlibtins.cmake find_package(PkgConfig REQUIRED) pkg_check_modules(LIBTINS REQUIRED libtins) $ cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_MODULE_PATH=$PWD/_patches CMake Deprecation Warning at CMakeLists.txt:1 (CMAKE_MINIMUM_REQUIRED): Compatibility with CMake < 2.8.12 will be removed from a future version of CMake. Update the VERSION argument <min> value or use a ...<max> suffix to tell CMake that the project does not need compatibility with older versions. -- The C compiler identification is GNU 9.4.0 -- The CXX compiler identification is GNU 9.4.0 -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Check for working C compiler: /usr/bin/cc - skipped -- Detecting C compile features -- Detecting C compile features - done -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Check for working CXX compiler: /usr/bin/c++ - skipped -- Detecting CXX compile features -- Detecting CXX compile features - done -- Found PkgConfig: /usr/bin/pkg-config (found version "0.29.1") -- Checking for module 'libtins' -- Found libtins, version 4.0 -- Configuring done -- Generating done -- Build files have been written to: /home/alex/test/dot11decrypt/build $ cmake --build build/ [ 50%] Building CXX object CMakeFiles/dot11decrypt.dir/dot11decrypt.cpp.o /home/alex/test/dot11decrypt/dot11decrypt.cpp: In function ‘void decrypt_traffic(unique_fd, const string&, decrypter_tuple)’: /home/alex/test/dot11decrypt/dot11decrypt.cpp:333:39: warning: ‘Tins::Sniffer::Sniffer(const string&, unsigned int, bool, const string&, bool)’ is deprecated [-Wdeprecated-declarations] 333 | Sniffer sniffer(iface, 2500, false); | ^ In file included from /usr/include/tins/dns.h:38, from /usr/include/tins/tins.h:33, from /home/alex/test/dot11decrypt/dot11decrypt.cpp:25: /usr/include/tins/sniffer.h:369:5: note: declared here 369 | TINS_DEPRECATED(Sniffer(const std::string& device, unsigned max_packet_size, | ^~~~~~~~~~~~~~~ [100%] Linking CXX executable dot11decrypt [100%] Built target dot11decrypt The key here is to create a minimal Find module. This is just two lines on my system since it isn't meant to be reusable... # _patches/Findlibtins.cmake find_package(PkgConfig REQUIRED) pkg_check_modules(LIBTINS REQUIRED libtins) This just delegates the responsibility of setting the LIBTINS_LIBRARIES to pkg-config. To connect this find module to the build, I just set -DCMAKE_MODULE_PATH=$PWD/_patches at the CMake configure command line. Also, you should definitely open a bug report with the dot11decrypt author about their broken and outdated build. Notice the strongly worded deprecation warning in the logs I posted.
72,332,387
72,332,550
Is this a correct implementation of ConvertsWithoutNarrowing
I am currently learning about concepts in C++20, and came across this example: template <typename From, typename To> concept is_convertible_without_narrowing = requires (From&& from) { { std::type_identity_t<To[]>{std::forward<From>(from)}} -> std::same_as<To[1]>; }; I am curious if the following can be considered a correct alternative implementation of the above: template <typename From, typename To> concept is_convertible_without_narrowing = requires (From&& from) { { To{std::forward<From>(from)} } -> std::same_as<To>; } or, even simpler: template <typename From, typename To> concept is_convertible_without_narrowing = requires (From&& from, To&& to) { to = {from}; }
I am curious if the following can be considered a correct alternative implementation of the above: The simple answer is no. In the second version, To{std::forward<From>(from)} can be regarded as constructing To through initializer_list, so is_convertible_without_narrowing<int, std::vector<int>> will be true. Similarly, the third version can be regarded as assigning To with initializer_list, so is_convertible_without_narrowing<int, std::vector<int>&> will also be true.
72,332,678
72,332,971
How to access the data member of one function into another function inside same class in c++
I wanted to declare the array of string to the limit provided by user. So I take limit in getData(), and declare the string inside getData function. As a whole I want to take students name and display it in the same class. Sorry for basic question and thank you in advance. class student { int limit; public: void getData() { cout<<"Enter the number of students: "; cin>>limit; string name[limit]; cout<<"Enter the names of students: \n"; for(int i=0; i<limit; i++) cin>>name[i]; } void showData() { cout<<"The list of students: \n"; for(int i=0; i<limit; i++) cout<<name[i]<<endl; } }; int main() { student s1; s1.getData(); s1.showData(); return 0; } Here in this function, error comes as "name was not declared in this scope". sorry in advance if it is nonsense. void showData() { cout<<"The list of students: \n"; for(int i=0; i<limit; i++) cout<<name[i]<<endl; }
One problem with your code is that string name is defined in getData() but not in showData(). What I would do is declare a member variable vector<string> name like you did with int limit. I would use a vector instead of an array because it's easier to code for me. #include <iostream> #include <vector> using namespace std; class student { int limit; vector<string> name; public: void getData() { cout<<"Enter the number of students: "; cin>>limit; cout<<"Enter the names of students: \n"; for(int i=0; i<limit; i++) { string temp; cin>>temp; name.push_back(temp); } } void showData() { cout<<"The list of students: \n"; for(int i=0; i<limit; i++) cout<<name[i]<<endl; } }; int main() { student s1; s1.getData(); s1.showData(); return 0; } Output: Enter the number of students: 3 Enter the names of students: andy max rose The list of students: andy max rose
72,332,949
72,333,039
How to make functions behave differently for different templates in C++?
A part of my C++ homework is to make the FooClass for this main: int main() { const int max = 10; int x[] = {10, 20, 7, 9, 21, 11, 54, 91, 0, 1}; FooClass<int> xl(x, max); int x2[] = {10, 20, 7, 9, 21, 11, 54, 91, 0, 1}; FooClass<int, std::greater<int> > xg( x2, max); xl.sort(); xg.sort(); xl.print(); xg.print(); } The goal is to make the first sort ascending and the second descending: 0 1 7 9 10 11 20 21 54 91 91 54 21 20 11 10 9 7 1 0 here is my code so far: template <typename T, typename F=std::greater<T>> class FooClass { private: T *mItems; int mItemsSize; bool mpermission; public: FooClass(T items[], int itemsSize) { this->mItemsSize = itemsSize; this->mItems = items; }; void print() const { for (int i = 0; i < mItemsSize; ++i) { std::cout << mItems[i] << " "; } std::cout << std::endl; } void sort() { std::sort(mItems, mItems + mItemsSize); } }; My code currently prints out: 0 1 7 9 10 11 20 21 54 91 0 1 7 9 10 11 20 21 54 91 And I am struggling to make my sort function behave differently depending on the input template parameters. Is there any way to make this work?
First of all, you are not using F. You need to pass an instance of F to std::sort: void sort() { std::sort(mItems, mItems + mItemsSize, F{}); } Secondly: Your default F would make both your instances in your example sort the array in the same way. To get the expected result, you should make the default F use std::less<T> instead. template <typename T, typename F=std::less<T>> class FooClass { //... };
72,333,232
72,333,262
how to round a number to N decimal places in C++?
I want to round a number to 10 decimal places , but it returns '6.75677', although it could returns '6.7567653457' #include <iostream> #include <cmath> using namespace std; double rounded(double number, int N) { return round(number * pow(10, N)) / pow(10, N); // i've chanched float to double } int main() { double value = 6.756765345678765; cout << rounded(value, 10) } I'd like to see a function returns rounded number Frankly speaking, I'd see an alternative of function 'round' in python print(round(6.756765345678765, 10))
cout << fixed << setprecision(10) << value << endl
72,333,353
72,333,731
Linux kernel function returns 1 instead of EINVAL
I'm trying to add a new system call to linux kernel: asmlinkage long sys_set_status(int status) { if ((status != 0) && (status != 1)) return -EINVAL; //-22 current->status = status; return 0; } in syscall_64.tbl it is declared: 334 common set_status sys_set_status in syscalls.h it is declared: asmlinkage long sys_set_status(int status); but when i test the return value: int set_status(int status) { long r = syscall(334, status); return (int)r; } int main() { int res = set_status(-1); //illegal status, should return -EINVAL whish is -22 cout << "return value is: " << res << endl; return 0; } i get: return value is: -1
long r = syscall(334, status); From man syscall: The return value is defined by the system call being invoked. In general, a 0 return value indicates success. A -1 return value indicates an error, and an error number is stored in errno. You are not calling the system call directly, you are calling it via the libc syscall wrapper, which performs approximately this: int syscall(num, ...) { /* architecture-specific code to put system call number and args into appropriate registers */ /* arch-specific code to execute the system call instruction */ int rc = /* arch-specific code to get the result of the system call */ ; if (rc < 0) { errno = -rc; return -1; } return 0; } If you don't want this translation to happen, you would have to perform the architecture-specific parts yourself (in assembly), and then you would have the actual system call return value.
72,333,443
72,333,469
Bitwise XOR on unsigned char is terminating program without error
I'm trying to create a 64 bit integer as class in C++, I know this already exists in the C header stdint.h but I thought it could be a fun challenge. Anyway, I am trying to perform a bitwise XOR operation on three unsigned chars, and the program keeps stopping without warning, it just pauses for a split second and then stops: unsigned char* a = (unsigned char*) 1; unsigned char* b = (unsigned char*) 2; unsigned char* c = (unsigned char*) 3; unsigned char* result = (unsigned char*) malloc(sizeof(unsigned char)); std::cout << "Trying" << std::endl; *result = *a ^ *b ^ *c; std::cout << "Done!" << std::endl; The output being: PS C:\Users\super\Desktop> ./test.exe Trying PS C:\Users\super\Desktop> I am using Windows 10 if that helps, let me know if you need any other information, and thanks for any help you can give me :)
You're trying to dereference invalid pointers. You want to get rid of a lot of those *s. unsigned char a = 1; unsigned char b = 2; unsigned char c = 3; unsigned char* result = (unsigned char*) malloc(sizeof(unsigned char)); std::cout << "Trying" << std::endl; *result = a ^ b ^ c; std::cout << "Done!" << std::endl; Why are you allocating a single byte (sizeof(unsigned char) is 1 by definition) on the heap for the result? You could just make that another unsigned char variable, too. Editorial note: you also don't need to use std::endl.
72,333,601
72,350,128
SFML sf::View::move inconstancy
UPDATE: I couldn't figure out the exact problem, however I made a fix that's good enough for me: Whenever the player's X value is less then half the screen's width, I just snap the view back to the center (up left corner) using sf::View::setCenter(). So I'm working on a recreating of Zelda II to help learn SFML good enough so I can make my own game based off of Zelda II. The issue is the screen scrolling, for some reason, if link walks away from the wall and initiated the camera to follow him, and then move back toward the wall, the camera won't go all the way back to the end of the wall, which occurs on the other wall at the end of the scene/room. This can be done multiple times to keep making the said camera block get further away from the wall. This happens on both sides of the scene, and I have reason to believe it has something to do with me trying to make the game frame independent, here's an included GIF of my issue to help understand: My camera function: void Game::camera() { if (this->player.getVar('x') >= this->WIDTH / 2 and this->player.getVar('x') < this->sceneWidth - this->WIDTH / 2) { this->view.move(int(this->player.getVar('v') * this->player.dt * this->player.dtM), 0); } } player.getVar() is a temporary function I'm using to get the players x position and x velocity, using the argument 'x' returns the players x position, and 'v' returns the x velocity. WIDTH is equal to 256, and sceneWidth equals 767, which is the image I'm using for the background's width. dt and dtM are variables for the frame independence I mentioned earlier, this is the deceleration: sf::Clock sclock; float dt = 0; float dtM = 60; int frame = 0; void updateTime() { dt = sclock.restart().asSeconds(); frame += 1 * dt * dtM; } updateTime() is called every frame, so dt is updated every frame as well. frame is just a frame counter for Link's animations, and isn't relevant to the question. Everything that moves and is rendered on the screen is multiplied by dt and dtM respectively.
There's a clear mismatch between the movement of the player and the one of the camera... You don't show the code to move the player, but if I guess you don't cast to int the movement there, as you are doing on the view.move call. That wouldn't be a problem if you were setting the absolute position of the camera, but as you are constantly moving it, the little offset accumulates each frame, causing your problem. One possible solution on is to skip the cast, which is unnecessary because sf::View::move accepts float as arguments. void Game::camera() { if (this->player.getVar('x') >= this->WIDTH / 2 and this->player.getVar('x') < this->sceneWidth - this->WIDTH / 2) { this->view.move(this->player.getVar('v') * this->player.dt * this->player.dtM, 0); } } Or even better, not to use view.move but to directly set the position of the camera each frame. Something like: void Game::camera() { if (this->player.getVar('x') >= this->WIDTH / 2 and this->player.getVar('x') < this->sceneWidth - this->WIDTH / 2) { this->view.setCenter(this->player.getVar('x'), this->view.getCenter().y); } }
72,333,605
72,334,439
Partial specialiszation of a template class with string template argument
#include <iostream> template<unsigned N> struct FixedString { char buf[N + 1]{}; constexpr FixedString(const char (&s)[N]) { for (unsigned i = 0; i != N; ++i) buf[i] = s[i]; } }; template<int, FixedString name> class Foo { public: auto hello() const { return name.buf; } }; template<FixedString name> class Foo<6, name> { public: auto hello() const { return name.buf; } }; int main() { Foo<6, "Hello!"> foo; foo.hello(); } I'm trying to add a template specialisation Foo<6, name> and it ends in this error: macros.h: At global scope: macros.h:3:18: error: class template argument deduction failed: 23 | class Foo<6, name> | ^ macros.h:3:18: error: no matching function for call to ‘FixedString(FixedString<...auto...>)’ macros.h:7:15: note: candidate: ‘template<unsigned int N> FixedString(const char (&)[N])-> FixedString<N>’ 7 | constexpr FixedString(const char (&s)[N]) | ^~~~~~~~~~~ macros.h:7:15: note: template argument deduction/substitution failed: macros.h:13:18: note: mismatched types ‘const char [N]’ and ‘FixedString<...auto...>’ 23 | class Foo<6, name> | ^ macros.h:4:8: note: candidate: ‘template<unsigned int N> FixedString(FixedString<N>)-> FixedString<N>’ 4 | struct FixedString | ^~~~~~~~~~~ macros.h:4:8: note: template argument deduction/substitution failed: macros.h:13:18: note: mismatched types ‘FixedString<N>’ and ‘FixedString<...auto...>’ 23 | class Foo<6, name> What is the proper way to specialise template classes with string template arguments? g++ (Ubuntu 9.4.0-1ubuntu1~16.04) 9.4.0
What is the proper way to specialise template classes with string template arguments? The given code is well-formed(in C++20) but fails to compile for gcc 10.2 and lower. It however compiles fine from gcc 10.3 and higher. Demo Might be due to that not all C++20 features were fully implemented in gcc 10.2 and lower.
72,334,552
72,713,903
pybind11 - ImportError: undefined symbol: _Py_ZeroStruct
I'm following the pybind11 documentation and trying to create Python bindings for a simple function Creating bindings for a simple function, but after compiling my C++ code with the following command: g++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cc -o example$(python3-config --extension-suffix) when I try to import the library in python using: import example I get an ImportError saying undefined symbol: _Py_ZeroStruct I'm using: Ubuntu : Ubuntu 20.04.4 LTS Python : Python 3.8.10 Pip : Pip 20.0.2 What I tried to solve the issue I looked into many articles related to the same error but couldn't really get an understanding of how I'm going to resolve my issue: Python3.5 incompatibility: undefined symbol ImportError: undefined symbol: _Py_ZeroStruct undefined symbol using pybind11 cmd Undefined Symbol error when linking pybind11 with a dynamic library that calls an external function Any kind of help will be greatly appreciated.
Well after trying a lot of methods I finally decided to add pybind11 as a submodule in my project and use Python3.9 and it seemed to work this time. Anyone struggling with the same problem can try my method, it may work and don't expect help from this cruel community.
72,334,734
72,334,776
Impact of a mutable member on a complete const object and UB
A complete const object cannot be replaced per basic.life. Placement new will result in UB. This is a complete const object: struct A {int i{};}; const A cco; However, this, because it isn't a complete const object and only the subobject is const, may be replaced as of c++20: struct A {const int i{};}; A o; But what about this? struct A {int i{}; mutable int mi{};}; const A o; It looks like it's a complete const object. And the standard says: The mutable specifier on a class data member nullifies a const specifier applied to the containing class object. It would thus seem that if it nullifies the containing class object then A is no longer const and it would no longer be a complete const object. So I decided to investigate what happens when I try to alter the object using a consteval function as well as run-time evaluation: #include <memory> #include <iostream> struct A { int i{ 1 }; mutable int mi{ 2 }; }; const A a; consteval int foo() { const A a; std::construct_at(&a, A{ 8,9 }); return a.i; } int main() { std::construct_at(&a, A{ 8,9 }); std::cout << a.i << '\n'; constexpr int cexpr_test = foo(); std::cout << cexpr_test << '\n'; } Both compile time and run time results in MSVC produce 8's which indicates the contents were replaced. However, this doesn't mean UB doesn't exist. Expanding this to compiler explorer shows that the modification also succeeded in GCC. But not in CLANG's run-time evaluation. Curiously, CLANG's consteval did modify the object. So the question: Is it UB because the object remains a complete const object in spite of the standard's wording or is it UB and just wasn't picked up by any of the compiler's consteval at compile time?
dcl.stc#9 says: [Note 4: The mutable specifier on a class data member nullifies a const specifier applied to the containing class object and permits modification of the mutable class member even though the rest of the object is const ([basic.type.qualifier], [dcl.type.cv]). — end note] (emphasis mine) This means that a modification of only the mutable class member is permitted and if we try to modify any other non-mutable data members of such a const object the result will still be undefined as "the rest of the object is const". In your example this means that only the mi mutable data member is permitted to be modified for a const A object and if we try to modify i the result will be undefined.
72,334,826
72,334,841
Is it possible to define a custom cast on an object to become the result of a method call?
Is it possible to define a custom cast on an object so that the objects casts to the result of a method call? class Foo { public: ... int method() { return 3; } }; Foo foo; int bar = foo + 7; // 10
Agh. I was overthinking it. #include <iostream> #include <string> class Foo { public: Foo() { _data = 3; } int method() { return _data; } operator int() { return method(); } int _data; }; int main() { Foo foo; int bar = foo + 7; std::cout << bar << std::endl; }
72,335,246
72,335,488
c++ missing construction and destruction of an object
The following code: #include <iostream> #include <string> using namespace std; void print(string a) { cout << a << endl; } void print(string a, string b) { cout << a << b << endl; } class A { public: string p; A() { print("default constructor"); } A(string a){ p = a; print("string constructor ", p); } A(const A& o) { print("copy constructor"); } A (A&& o) { print("move constructor"); } A& operator=(const A& o) { print("copy assignment"); return *this; } A& operator=(const A&& o) { cout << "move assignment to:" << p << " from:" << o.p << endl; return *this; } ~A() { print("destructor ", p); } }; A operator+(const A& a, const A& b) { cout << "add" <<endl; A c("f"); return c; } A f(A& a, A& b, A& c) { A d("e"); d = a+b+c; print("after add"); return d; } int main() { A a("a"); A b("b"); A c("c"); A whereDidThisGo {f(a,b,c)}; print("end"); } has the following output: string constructor a string constructor b string constructor c string constructor e add string constructor f add string constructor f move assignment to:e from:f destructor f destructor f after add end destructor e destructor c destructor b destructor a Process exited after 0.06744 seconds with return value 0 Press any key to continue . . . Where is the construction/destruction of the whereDidThisGo variable defined in main?
Where is the construction/destruction of the whereDidThisGo variable defined in main? You do not see the ouptut for this due to named return value optimization(aka NRVO). it's not a good optimization for people like me who are trying to learn constructors You can disable this NRVO by providing the -fno-elide-constructors flag to the compiler. Demo. Also, note that in your example the A::operator=(const A&&) should instead be: //-----------vv------->no need for const here A::operator=(A&&)
72,335,279
72,335,331
Why is static_cast<Object&&> necessary in this function?
Trying to understand std::move, I found this answer to another question. Say I have this function Object&& move(Object&& arg) { return static_cast<Object&&>(arg); } What I think I understand: arg is an lvalue (value category). arg is of type "rvalue ref to Object". static_cast converts types. arg and the return type both being of type "rvalue ref to Object", the static_cast is unnecessary. However, the linked answer says: Now, you might wonder: do we even need the cast? The answer is: yes, we do. The reason is simple; named rvalue reference is treated as lvalue (and implicit conversion from lvalue to rvalue reference is forbidden by standard). I still don't understand why the static_cast is necessary given what I said above.
the static_cast is unnecessary. It may seem so, but it is necessary. You can find out easily by attempting to write such function without the cast, as the compiler should tell you that the program is ill-formed. The function (template) returns an rvalue reference. That rvalue reference cannot be bound to an lvalue. The id-expression arg is an lvalue (as you stated) and hence the returned rvalue reference cannot be bound to it. It might be easier to understand outside of return value context. The rules are same here: T obj; T&& rref0 = obj; // lvalue; not OK T&& rref1 = static_cast<T&&>(obj); // xvalue; OK T&& rref2 = rref1; // lvalue; not OK T&& rref3 = static_cast<T&&>(rref1); // xvalue; OK
72,335,652
72,335,724
how to round a number to N decimal places in C++? (correction)
I want to round a number (6.756765345678765) to 10 decimal places , but it returns '6.75677', although it could returns '6.7567653457' #include <iostream> #include <cmath> using namespace std; double rounded(double number, int N) { return round(number * pow(10, N)) / pow(10, N); // i've chanched float to double } int main() { double value = 6.756765345678765; cout << rounded(value, 10) } I'd like to see a function returns rounded number Frankly speaking, I'd see an alternative of function 'round' in python print(round(6.756765345678765, 10))
You can use setprecision(10) function of <iomanip>. #include <iostream> #include <iomanip> using namespace std; int main() { double value = 6.756765345678765; cout << setprecision(10) << value; } Output: 6.756765346
72,336,395
72,336,746
How to convert string expression to boolean in c++?
How can I convert the string "a > b" to bool? #include <iostream> using namespace std; float condition(float a, float b) { bool cond; /* i'd like to see a function converting string "a > b" to bool */ return cond } int main() { if (condition(7, 6)) { cout << "a > b"; } } In Python, I can do it like this: def condition(a, b): cond = f'{a} > {b}' return cond if eval(condition(7, 6)): print('a > b')
In C++, you can utilize lambda functions to achieve something similar: #include <iostream> using CmpFunc = bool(float, float); CmpFunc* condition(char op) { switch (op) { case '>': return [](float a, float b) { return a > b; }; case '<': return [](float a, float b) { return a < b; }; case '=': return [](float a, float b) { return a == b; }; default: return [](float a, float b) { return false; }; } } int main() { auto const cmp = condition('>'); if (cmp(7, 6)) { std::cout << "a > b"; } }
72,336,579
72,337,044
Good way of popping the least signifigant bit and returning the index?
I am new to C++ and I'm trying to write a function that will pop the least significant bit and then return the index of that bit. Is there a way to do this without creating a temporary variable? Right now I have a function for finding the index and one for popping the bit but I'd like to combine the two. inline int LSB(uint64_t b) { return int(_tzcnt_u64(b)); } inline uint64_t popLSB(uint64_t b, int index) { return (b ^ (1ui64 << LSB(b))); } My only idea requires a temporary index variable which just feels bad. int bestIdea(uint64_t *b) { int index = int(_tzcnt_u64(*b)); *b ^= (1ui64 << index); return index; } Is there a better way of doing this? And if there is anything else not necessary or dumb about this code I'm happy to take suggestions, this is my first project and I'm not sure about pretty much any part.
There's nothing wrong with using a temporary variable. However modern architectures are superscalar and out-of-order so to better adapt for them you should only use that for the return value and don't use it to clear the least significant bit to avoid an unnecessary dependency chain int popLsbAndReturnIndex(uint64_t *b) { int index = int(_tzcnt_u64(*b)); *b &= *b - 1; // Not depend on the previous line return index; } Now we have better instruction-level parallelism and the 2 lines in the body can run in parallel Of course some really smart compilers can recognize the pattern and compile your original code to the version without dependency, but no one can guarantee that Some more recommendations: Use std::countr_zero instead of _tzcnt_u64 if you have C++20 or higher Use references instead of pointers The result is like this int bestIdea(uint64_t &b) { auto index = std::countr_zero(*b); b &= b - 1; return index; }
72,337,435
72,337,995
error on do while loop condition in C++ with condition to continue the loop
I am making c++ program using do while loop but after inserting the condition while ( x =='y'|| x == 'Y'); I got an error where the loop is continued without letting me to insert the input again. I can't insert the input until I stop the program. #include <iostream> using namespace std; int main() { char str[30]; char symptom,quest; char a,b,x,y,Y,n,N; do{ cout<<" Enter your name: "<<endl; cin.get(str,30); cout<<"Hi " << str << ", Welcome to COVID test!"<<endl; cout<<"Let's start the self testing test!"<<endl<<endl<<endl; cout<<"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"<<endl; cout<<" COVID SELF TESTING CENTRE "<<endl; cout<<"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"<<endl<<endl; cout<<"Do you have any symptoms below: (1-Yes, 2-No)"<<endl; cout<<"Fever --> "<<endl; cin>>a; cout<<"Cough --> "<<endl; cin>>a; cout<<"Flu --> "<<endl; cin>>a; cout<<"Shortness of breath --> "<<endl; cin>>a; cout<<"Sore throat --> "<<endl; cin>>a; cout<<"Have you ever tested POSITIVE COVID-19 : "<<endl; cin>>b; cout<<"Do you had close contact with those who have been confirmed PORITIVE COVID-19 in the last 14 days? : "<<endl; cin>>b; cout<<"Do you have a history of traveling abroad or outside the state of Perak in the last 14 days? : "<<endl; cin>>b; cout<<"Are you currently undergoing a home quarantine control order by the Ministry of Health Malaysia? : "<<endl; cin>>b; cout<<endl<<endl; cout<<"========================================================="<<endl; cout<<" RESULT FOR COVID-19 SELF TESTING CENTRE "<<endl; cout<<"========================================================="<<endl; symptom=a; quest=b; if (symptom=='2'&&quest=='2') { cout<<"GREEN ZONE. Your status are low risk and no symptoms. Please folllow the SOP and Stay Safe Thank You!"<<endl; } if (symptom=='1'&&quest=='1') { cout<<"RED ZONE. Please get a clinically COVID-19 checkup from nearby hospital. Please folllow the SOP and Stay Safe Thank You!"<<endl; } if (symptom=='1'&&quest=='2') { cout<<"YELLOW ZONE. Please stay at home or self quarantine. Please folllow the SOP and Stay Safe Thank You!"<<endl; } if (symptom=='2'&&quest=='1') { cout<<"YELLOW ZONE. Please stay at home or self quarantine. Please folllow the SOP and Stay Safe Thank You!"<<endl; } cout<<"Ingin teruskan? (Y-yes, N-No): "<<endl; cin>>x; cout<<" "; }while ( x =='y'|| x == 'Y'); system("pause"); return 0; }
The problem you are seeing is that there is are leftover characters in the cin buffer, so the next time through the loop it reads those and doesn't ask the user for input. If you clear the buffer out at the end of the loop then the subsequent runs work. do { //... std::cout << "Ingin teruskan? (Y-yes, N-No): "<< std::endl; std::cin >> x; std::cout << " "; // add this to ignore and clear the current cin buffer std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } while (x == 'y' || x == 'Y'); Have a look at this question for some more related details. You may also need to add #include <limits> to use numeric_limits (although in my case iostream pulls it in so I do not need to add that include).
72,337,723
72,338,137
I just started c++ and made a calculator. What or how can I improve my code/ learn more?
So I tried making a simple calculator that can input 2 floats and do basic operations (addition, subtraction, division, multiplication). This is the first time I'm writing a code without copying the entire thing from a tutorial. I did copy some bug fixes and other things but mostly I did it myself. I want criticism and I want to know what I could've done better. #include <iostream> #include <ctype.h> #include <string> using namespace std; char start; float num1, num2, result; char op; int menu(){ cout<<"\nstart the program? \ny or n:\t"; cin>>start; return 0; } int input_number(){ cout<<"\nenter the first number: "; cin >> num1; while (!cin){ cout<<"Error. Number of elements must be numerical. Try again: " << endl; cin.clear(); cin.ignore(256, '\n'); cin >> num1; } cout<<"\nenter the second number "; cin >> num2; while (!cin){ cout<<"Error. Number of elements must be numerical. Try again: " << endl; cin.clear(); cin.ignore(256, '\n'); cin >> num2; } return 0; } int input_op(){ cout<<"\nenter which operation you want to execute (+,-,/,*): "; cin>>op; switch (op) { case '+': result= num1+num2; break; case '-': result= num1-num2; break; case '*': result= num1*num2; break; case '/': result= num1/num2; break; default: cout<<"wrong input"; break; } return 0; } int main(){ cout<<"-----Calculator X-----"; menu(); if (start=='y' || start== 'Y'){ input_number(); input_op(); cout<<"the result is : "<<result<<'\n'; menu(); } else{ cout<<"exiting program"; return 0;} }
function don't need to return 0, simply declare those as void return. except int main() the cin>>num; while(!cin){cin>>num;} can be merged as while(!(cin>>num)) ignore 256 char may not be enough use std::numeric_limits<std::streamsize>::max() instead for ctype.h, the corresponded c++ header is cctype (relevant SO question) you may actually return the result instead of store in global state. bool menu(), std::pair<int,int> input_number(), char input_op() input_number may get single number instead of 2 (and be called twice) you don't check op is valid (unlike number inputs)
72,338,190
72,338,657
className SerialNow = *((className*)ptr); vs className &SerialNow = *((className*)ptr);
What is difference between using or not reference when casting pointer to object? void someClass::method() { xTaskCreatePinnedToCore(someTaskHandler,"SerialNowTaskTX",XT_STACK_MIN_SIZE*3,this,4,&taskHandleTX,0); // passing 'this' to task handler } void someTaskHandler(void *p) { SerialNow_ SerialNow = *((SerialNow_*)p); // compile but not working properly SerialNow_ &SerialNow = *((SerialNow_*)p); // compile and working SerialNow_ *SerialNow = ((SerialNow_*)p); // compile and working but I prefer . over -> int A = SerialNow.somethingA; SerialNow.somethingB(); while(1) { } vTaskDelete(NULL); }
Preliminary remark First, keep in mind that casting void* pointers is in C++ a rather dangerous thing, that can be UB if the object pointed to is not compatible with the type you're casting to. Instead of a C-like cast between parenthesis, prefer a C++ more explicit cast, that shows better the level of danger. If p would be a polymorphic base type, prefer using the safer dynamic_cast. Otherwise use a static_cast to avoid some common mistakes. Only in last resort use reinterpret_cast, but you'd have to be really sure about what you're doing. What's the difference between your statements? If we'd suppose that p is a valid pointer to a type that is compatible with SerialNow_ this is the meaning of your different statements: SerialNow_ SerialNow = *((SerialNow_*)p); The first makes a copy of the the object that is pointed by p. If you later change the content of the object pointed by b, it will have no impact on the object SerialNow. Keep in mind that if the object pointed by p is not a SerialNow_ but a subclass, slicing might occur. SerialNow_ &SerialNow = *((SerialNow_*)p); The second creates a reference that refers to the object that is pointed by p. You can use SerialNow as if it were an object, but in reality it refers to the same object than the one pointed by p: SerialNow_ *SerialNow = ((SerialNow_*)p); The third creates a pointer to the object that is pointed by p: The second and the third respect polymorphism. If the object pointed to by p is not a SerialNow_ but a subtype, polymorphism will work, i.e. if you call a virtual function, the one corresponding to the real run-time type of the object will be invoked.