question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
71,031,763 | 71,032,005 | Move tuple containing lambda | I am trying to implement a generic RAII cleanup. This looked like it was working, until I tried to use the move constructor:
#include <functional>
#include <tuple>
#include <utility>
template <typename R, typename D>
class Cleaner {
public:
Cleaner() = default;
Cleaner(R r, D d = {}) : data(std::move(d), std::move... | Your issue is that lambda is not default constructible (non-capturing ones are since C++20).
You might change constructor to:
Cleaner(Cleaner&& other) noexcept :
data(std::move(other.data)),
owns(other.owns)
{
other.owns = false;
}
Demo
|
71,032,192 | 71,032,292 | does pop( ) method delete the object from the memory? | In the following code:
#include<iostream>
#include<queue>
using namespace std;
int main()
{
queue<int> q;
int a = 5;
q.push(a);
cout << q.front() << endl; // 5
int* b = &(q.front());
q.pop();
cout << *b; // Outputs 5 but why ?
}
Is a copy of 'a' created inside the queue when I p... | Calling the destructor means that the object is destroyed and the program is no longer using it. It doesn't mean that the memory it took is now overwritten.
So, in short:
The object data might still be in memory as garbage.
So the contents of the same memory address will depend on whether the program has already used ... |
71,032,456 | 71,032,457 | Is enum E { a } e = E(2); valid? | A recent and interesting C language-lawyer question asked:
Is enum { a } e = 1; valid?
This Q&A asks the same question for the similar cases for C++(*): are these valid?
enum EA { a } ea = EA(2); // #1
enum EB { b } eb = static_cast<EB>(2); // #2
I've already noted that the variation enum EC { c } ec ... | Unspecified behavior until C++14; undefined behavior since C++17
Whilst the corresponding construct is legal in C—as answered thoroughly in the linked-to C language-lawyer Q&A—due to the stronger "compatible type" requirement, the same does not hold for C++, where "C style" unscoped enums with no fixed underlying type ... |
71,032,474 | 71,032,565 | Std::nth_element is not giving the correct element | I don't know why in this case the function std::nth_element is not giving me the correct median for the X axis.
For this test I created a vector of point: std::vector<Point> points = {Point {70, 70}, Point {50, 30}, Point {35, 45}};
The function call is:
int median = (start + end) / 2;
Point split = get(points.begin() ... | The variable end is not correctly pointing to the end of the vector. Hence, you only perform nth_element() on the first 2 elements. Since the variable median value is 1, the point with greater x value will be returned.
You can use points.end() instead of points.begin() + end.
|
71,032,714 | 71,032,838 | Reading unsigned int into uint64_t from binary file | I am trying to read a binary file using fstream. I know the types of everything in this file but there are two different versions, an old and a new version. The old version contains variables of type 'unsigned int' deemed to have insufficient range, and are replaced by 'uint64_t' in the new version. I'd like one file r... | You need to read it into a variable of the correct type and then you can assign it to your uint64_t variable.
static_assert(std::endian::native == std::endian::big ||
std::endian::native == std::endian::little);
constexpr auto file_endianess = std::endian::big; // or little
std::uint64_t... |
71,033,511 | 71,033,676 | Why can't I use `using` in a multiple inheritance c++? | I tried to implement some interfaces and their children. This is my idea:
Interface
/ \
Interface2 InterfaceDefination
| /
Interface2Defination
And this is my code:
#include <iostream>
class Interface {
public:
virtual void method1() = 0;
virtual void print() = 0;
}... | A using declaration is a declaration. It is not a definition. It does not define anything "new". What it does is declare: ok, I have a symbol X, but it really refers to X in my parent class (for this version of a using declaration).
You might ask what's the point, aren't you inheriting X from your parent class in the n... |
71,033,950 | 71,034,025 | In C++ map, which is better for usage/perfomance and conforms to the guidelines, using find_if or find then and .at | I am using a C++ map, in which I need to search for an element then get the element if it is exist.
The first way to do that is using find
if (mymap.find(mykey) == mymap.end())
{
//return error code
return ERROR_CODE;
}
else
{
value = mymap.at(mykey).second;
return SUCCESS_CODE;
}
second way to do tha... | You should not use std::find_if which is linear, whereas you might have iterator in logarithm time. You might do
auto it = mymap.find(mykey)
if (it == mymap.end())
{
//return error code
return ERROR_CODE;
}
else
{
value = it->second;
return SUCCESS_CODE;
}
|
71,034,159 | 71,044,910 | How to encapsulate the H.264 bitstream of video file in C++ | I'm trying to convert a video file (.mp4) to a Dicom file.
I have succeeded to do it by storing single images (one per frame of the video) in the Dicom, but the result is a too large file, it's not good for me.
Instead I want to encapsulate the H.264 bitstream as it is stored in the video file, into the Dicom file.
... | The trick is to redirect the value of the attribute PixelData to a file stream. With this, the video is loaded in chunks and on demand (i.e. when the attribute is accessed).
But you have to create the whole structure explicitly, that is:
The Pixel Data element
The Pixel Sequence with...
...the offset table
...a single... |
71,034,432 | 71,034,876 | Generate const array of pointers to callback functions | I'd like to generate an array of N pointers to callbacks so I don't have to type them explicitly (LOC is not the issue here).
I use C++17.
Here is what I have:
using Callback = void(*)();
auto constexpr N = 2;
const Callback callbacks[N] = {
[](){ auto i = 0; std::cout<<"callback " << i << "\n";},
[](){ auto i = 1; ... | Off Topic Suggestion: don't use, when you can, C-styles arrays but C++ std::array.
For example: the following line
const auto callbacks = generate_callbacks<N>();
can't works if you want that callbacks is a C-style array (a function can't return that type) but works when generate_callback() return a std::array<Callba... |
71,034,909 | 71,042,795 | Finding element in QList | Suppose I have a struct SignalError which has an element "errName" and many other elements:
typedef struct SignalError
{
QString errName;
.....
};
I create QList of this struct:
QList<SignalError> signalErrList;
I will append the struct element to the QList using append call.
SignalError sgErr1 = {"Error_1"};... | You should use QList<SignalError> signalErrList; not a QList of pointers.
If you don’t care about order, you should use a std::set<SignalError> which will give you deduplication automatically.
If you care about order and the O(N) search isn’t a problem, then use QList or std::vector and do
if (auto it = std::find(signa... |
71,035,326 | 71,035,587 | std::ranges algorithm function object customisation points AKA niebloids - problems with std lib types | All done with gcc 11.2 and libstdc++-11
Below code shows a variety of ways of using std::sort and then std::ranges::sort to sort builtins, user defined types and a std library type.
Only the std library type gives me trouble:
I can't easily define a custom operator< or operator<=> because it is UB to add that to names... | You need to specify a comparison for T if std::less<T> is unavailable.
Both std::sort and std::ranges::sort require a strict weak ordering predicate, not operator<=> (but that can supply one, via < and std::less)
template<typename T>
bool complex_less (std::complex<T> lhs, std::complex<T> rhs) { return abs(lhs) < abs(r... |
71,035,341 | 71,035,654 | Linked List insertion isn't working in for/while loop | I am learning DSA, and was trying to implement linked list but the insertion function that i wrote is not
working in a for or while loop, its not the same when i call that function outside the loop, it works that way. I am not able to figure it out, please someone help me.
#include <iostream>
class Node {
public:
i... | When inserting the nth item (1st excluded) tmp is a null pointer, i don't understand what you are doing there, you are assigning to next of some memory then you make that pointer point to another location, losing the pointer next you assigned before, you must keep track of the last item if you want optimal insertion. T... |
71,035,511 | 71,039,860 | Disabling specific test instance defined from a dataset | Let's say I have the following test code:
struct MyData
{
MyData( int in_, double out_ )
: m_in{ in_ }
, m_out{ out_ }
{}
int m_in;
double m_out;
};
std::ostream& operator<<( std::ostream& os_, MyData data_ )
{
os_ << data_.m_in << " " << data_.m_out << std::endl;
return os_;
}
std... | You can supply a command line argument, like:
./sotest -l all -t "!*/*_1"
Which outputs:
More Advanced/Dynamic
You could also supply your own decorator based on enable_if, which you could make to use your own custom command line options (you'll need to supply your own test_main to parse those).
For an example of such... |
71,035,574 | 71,036,143 | C++ pass by reference tricky situation | I'm trying to figure what happens to an "rvalue",temporary object, after the variable used to refer this object deleted from stack.
Code example:
#include<iostream>
using namespace std;
class Base
{
private:
int &ref;
public:
Base(int &passed):ref(passed)
{
cout << "Value is " << ref << endl;
}
int g... | From Reference declaration documentation
it is possible to create a program where the lifetime of the referred-to object ends, but the reference remains accessible (dangling). Accessing such a reference is undefined behavior.
In your program the referred-to object ref ends at } after ref++. This means that the ref da... |
71,035,706 | 71,035,861 | How to define configuration dependent properties in VS C++ project? | I'm really new to C++ and Visual Studio, I know there are ifdef and ifndef to do the conditional compilation. But my boss ask me to create 2 different configurations (similar to debug and release) to automate this. For example:
#if $(some_configuration_dependent_flag)
// I can do something specific for only config1
#... | Visual Studio allows per config pre-processor definitions.
Use menu Project/Properties (on right click + Properties on the project) to open the Property Page dialog
Then in C/C++ / Preprocessor, you find Preprocessor Definitions. You select the configuration you want to change, and can add or modify any definition.
|
71,036,436 | 71,037,226 | How to use boost tests with SFML and cmake? | I'm writing a simple game in C++ with use of SFML. I want to use boost tests, but when i try to i get undefined reference in every place i use SFML features (the game itself works fine, it's just the test that don't). Sample test:
#include <boost/test/unit_test.hpp>
#include "Sentry.h"
BOOST_AUTO_TEST_SUITE(BasicModel... | TestProject is missing the SFML library in the link options (see also What is an undefined reference/unresolved external symbol error and how do I fix it?). Your main executable apparently does have it, but you don't show it.
Look for something like
LINK_LIBRARIES(sfml-system sfml-window sfml-graphics sfml-audio)
Or ... |
71,036,571 | 71,036,861 | Why does "L.insert(it--, i);" behave differently from "L.insert(it, i); it--;"? | These are two pieces of code that I ran under the C++11 standard. I expected the post-decrement of the iterator to produce the same effect, but these two pieces of code produce completely different results. Where is my understanding off?
list<int> L;
int main() {
L.push_back(0);
L.push_front(1);
auto i... | Consider exactly when the post-decrement happens. In the second case, obviously the insert happens, modifying the list itself. The iterator is still valid, pointing now at the second entry. Then the decrement is computed, moving the iterator to the first entry.
In the first case, however, the post-decrement "makes a... |
71,037,134 | 71,040,133 | Accessing QObject subclasses from other threads | I need some help understanding the details of accessing QObject subclasses from other threads.
From Qt documentation:
"If you are calling a function on an QObject subclass that doesn't live in the current thread and the object might receive events, you must protect all access to your QObject subclass's internal data wi... |
Is it sufficient to rewrite the m_value variable to be std::atomic?
Assuming you join the thread before the model is destroyed, I think yes.
There is nothing in the above that is specific to QObject.
I think they wanted to stress "the object might receive events" part, which may not be a direct call in your code, b... |
71,037,506 | 71,037,877 | How to assign .editorconfig to a Visual Studio 2019 C++ solution? | I am editing a VS solution that has a different coding style than the one I normally use. I found in the docs that VS 2019 supports EditorConfig: https://learn.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2019
I created .editorconfig file in the root of my solution:
I put this in ... | EditorConfig files are only applied to the directory they are in and its sub-directories you need to put the file in the same folder as your source code (or a folder above it) not in the same folder as your solution/project files.
|
71,037,508 | 71,037,520 | C++ macros generating and error which I can't identify | Here I was just practicing on macros and I tried this but it's generating an error, says expecting and ; but it seems right from me.
#include <iostream>
using namespace std;
#define REP(i, a, b) for(int i = a, i <= b; i++)
int main()
{
int i;
//REP showing an error
REP(i, 0, 6){
cout << "Hello"<< " ";... | replace for(int i = a, i <= b; i++)
with for(int i = a; i <= b; i++)
the ',' symbol after "= a" is wrong, should be semi-colon.
|
71,037,756 | 71,074,708 | Unrecognized Token C/C++(7) Error in Visual Studio Code | Unrecognized Token C/C++(7) Error in Visual Studio Code
I am unsure why I am receiving these error messages; I am trying to compile c++11 code on VSC.
Please help? Thank you
see code here
For example, on Line 7 there is an "Unrecognized Token C/C++(7) Error" :
string str = “fine”;
| Yes, you are using fancy unicode quotes. It may happen when you copy code from some messenger. Messengers often replace original quotes to that type of quotes.
|
71,037,914 | 71,038,321 | Serialize array char, int8_t and int16_t in protobuf for C++ | In protobuf, how would you serialize an array of char's, (u)int8_t or (u)int16_t? Should the message look like this:
message ArrayWithNotSupportedTypes
{
int32 type = 1;
string byte_stream = 2;
}
where type could store some unique id of the element type stored in the array.
And then the byte_stream is populated with ... | If the array size is not big, you can waste some space to make the interface simpler.
message ArrayWithNotSupportedTypes
{
repeated int32 data = 1; // one data entry per one element
}
If the array size is big, you can use your solution to indicate the type
message ArrayWithNotSupportedTypes
{
enum Type {
CHAR ... |
71,038,331 | 71,046,789 | dyld: Library not loaded despite correct rpath | I am debugging a problem where I am trying to link against a dylib, and set the program's rpath to a directory containing the library.
I have narrowed this to the following MWE:
> ls deps/include/spinnaker/
AVIRecorder.h Camera.h CameraPtr.h Exception.h …bunch of headers
> ls deps/lib/libSpinnaker.dylib*
dep... | install_name_tool -id @rpath/libSpinnaker.dylib.1.24.0.60 deps/lib/libSpinnaker.dylib.1.24.0.60
install_name_tool -change libSpinnaker.dylib.1.24.0.60 @rpath/libSpinnaker.dylib.1.24.0.60 wat
You noticed that the @rpath was missing from the installed name of the library. install_name_tool is the command which allows ... |
71,038,566 | 71,055,711 | Does Tuxedo XA transaction manager support ActiveMQ as resource manager for C++ applications? | I am looking for examples or resources to prove support for ActiveMQ as one of the resource managers with Tuxedo as the XA transaction manager. I am working on building a C++ Application to do the same. I am unable to find any documentation on Tuxedo community or Google for the same.
| No, it does not support it out of the box. There is a list of resource managers supported in $TUXDIR/udataobj/RM. To support ActiveMQ, you should add an entry in the RM file with the resource manager name, a symbol name that contains pointers to XA functions, and a list of libraries for linking the resource manager. Af... |
71,038,939 | 71,039,747 | Why can't I add or remove a QListWidgetItem? | I have two ListWidget at my ui and I want to move one QListWidgetItem from availableMeasurementsListWidget to selectedMeasurementListWidget
But this won't work for me. Nothing adds into selectedMeasurementListWidget and the item does not removes from availableMeasurementsListWidget. Why?
That only who works is displayi... | Note that QListWidget:: removeItemWidget doesn't remove the QListWidgetItem from the QListWidget: it only...
Removes the widget set on the given item.
To remove an item (row) from the list entirely, either delete the item
or use takeItem().
So you probably want something like...
auto *available = ui->availableMeasure... |
71,039,870 | 71,040,002 | How can I print an array via pointer | Our teacher gave this code and we need to get this code operational.
How can I print the values inside of array?
cout << wizardsCollection->birthYear;
is returns what I gave but wizardsCollection->nameSurname returns empty value.
Here's the rest of the code:
struct Wizard {
string nameSurname;
int birthYear;
... | You have a huge problem here. wizardsCollection is created on the stack. As soon as the function returns, that stack memory goes away. Your pointer will be pointing into empty space. You need to use a std::vector for this, to manage the memory.
#include <iostream>
#include <string>
#include <vector>
struct Wizard {... |
71,039,897 | 71,039,984 | How do I explicitely initialize the copy constructor for a class that inherits from std::enable_shared_from_this | Consider the following test code:
#include <memory>
class C : public std::enable_shared_from_this<C>
{
public:
C(C const& c){}
};
int main()
{
}
Compiling this with -Wextra will generate the following warning
warning: base class 'class std::enable_shared_from_this' should be explicitly initialized in the c... | You can explicitly initialize it by calling its default constructor like this:
C(C const& c) : enable_shared_from_this() {}
You can also do it by calling its copy constructor like this:
C(C const& c) : enable_shared_from_this(c) {}
The copy constructor actually does the same thing as the default constructor (it marks... |
71,039,947 | 71,040,343 | Is if(A | B) always faster than if(A || B)? | I am reading this book by Fedor Pikus and he has some very very interesting examples which for me were a surprise.
Particularly this benchmark caught me, where the only difference is that in one of them we use || in if and in another we use |.
void BM_misspredict(benchmark::State& state)
{
std::srand(1);
const... |
Is if(A | B) always faster than if(A || B)?
No, if(A | B) is not always faster than if(A || B).
Consider a case where A is true and the B expression is a very expensive operation. Not doing the operation can save that expense.
So the question is why don't we always use | instead of || in branches?
Besides the cases... |
71,040,175 | 71,040,950 | CMake nested OBJECT library dependencies | I created a project with some nested library dependencies using the OBJECT library type. The motivation for this is to avoid link order issues with static libraries.
I have a simple directory structure as follows:
├── bar
│ ├── bar.c
│ └── bar.h
├── foo
│ ├── foo.c
│ └── foo.h
├── main.c
└── CMakeLists.txt
foo... | Object libraries cannot be chained this way. You must link directly (not transitively) to an object library to acquire its object files. As it says in the documentation,
Object Libraries may "link" to other object libraries to get usage requirements, but since they do not have a link step nothing is done with their ob... |
71,040,243 | 71,040,693 | Which memory barriers are minimally needed for updating array elements with greater values? | What would be the minimally needed memory barriers in the following scenario?
Several threads update the elements of an array int a[n] in parallel.
All elements are initially set to zero.
Each thread computes a new value for each element; then,
it compares the computed new value to the existing value stored in the arra... | Relaxed is fine, you don't need any ordering wrt. access to any other elements during the process of updating. And for accesses to the same location, ISO C++ guarantees that a "modification order" exists for each location separately, and that even relaxed operations will only see the same or later values in the modifi... |
71,040,349 | 71,069,950 | Location of the error token always starts at 0 | I'm writing a parser with error handling. I would like to output to the user the exact location of the parts of the input that couldn't be parsed.
However, the location of the error token always starts at 0, even if before it were parts that were parsed successfully.
Here's a heavily simplified example of what I did.
... | I'm building upon the rici's answer, so read that one first.
Let's consider the rule:
numbers:
%empty
| numbers number ';'
| error ';' { yyerrok; }
;
This means the nonterminal numbers can be one of these three things:
It may be empty.
It may be a number preceded by any valid numbers.
It may be an e... |
71,040,425 | 71,040,567 | SFINAE not working with member function of template class | I have a template class where I would like to remove a member function if the type satisfies some condition, that, as far as I understand, should be a very basic usage of SFINAE, for example:
template<class T>
class A
{
public:
template<typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
... | You're missing a dependent name for the compiler to use for SFINAE. Try something like this instead:
#include <type_traits>
template<class T>
class A
{
public:
template<typename Tp = T>
typename std::enable_if<std::is_floating_point<Tp>::value, Tp>::type
foo () {
return 1.23;
}
};
int main() {... |
71,040,975 | 71,144,383 | Build and run a Qt application on macOS via Bazel | I tried to build and run a Qt5 (5.15.2) application on macOS (10.15.7) using Bazel 5.0.0.
Unfortunately, I run into some problems.
The building part seems to work, but not the run part.
I installed Qt5 on my machine using Homebrew:
brew install qt@5
brew link qt@5
I adapted https://github.com/justbuchanan/bazel_rules_... | I followed your steps with Mac OSX 10.15.7, Qt (installed by homebrew) 5.15.1 and both bazel 4.2.2-homebrew and 5.0.0-homebrew and initially I could not build the project from git:
* 3fe5f6c - (4 weeks ago) Add macOS support — Vertexwahn (HEAD -> add-macos-support, origin/add-macos-support)
This is the result that I ge... |
71,040,977 | 71,041,026 | Differrent results in different compilers c++ | I have created the following program:
#include <iostream>
int main(){
int a,b,mod, a1,b1;
std::cin >> a >> b;
if(a >= b){
mod = a % b;
} else {
mod = b % a;
}
if(mod == 0){
std::cout << a;
} else {
while(a1 != 0 && b1 != 0){
a1 = a % mod;
... | a1 and b1 is not initialized by correct numbers. If you set correct initial version, you should get consistent behavior.
|
71,040,986 | 71,041,166 | Upgrade from VS2015 to VS2022: Error LNK1104 cannot open file 'msvcprtd.lib' | I am trying to upgrade a project from VS2015 to VS2022 and getting the following error:
Error LNK1104 cannot open file 'msvcprtd.lib'
When I compile it as 2015 project, it works, but once I switch it to 2022, it fails.
| In my case, I needed to select the checkmark 'Inherit from parent or project defaults' in library directories
I created a new empty project and compared the library settings with my older project to see what was the difference.
|
71,041,077 | 71,041,529 | CMAKE_CXX_SOURCE_FILE_EXTENSIONS not working with thrust/cuda | Thrust allows for one to specify different backends at cmake configure time via the THRUST_DEVICE_SYSTEM flag. My problem is that I have a bunch of .cu files that I want to be compiled as regular c++ files when a user runs cmake with -DTHRUST_DEVICE_SYSTEM=OMP (for example). If I change the extension of the .cu files... |
Why is cmake not respecting my CMAKE_CXX_SOURCE_FILE_EXTENSIONS changes?
The extension-to-language for <LANG> is set as soon as <LANG> is enabled by inspecting the value of the CMAKE_<LANG>_SOURCE_FILE_EXTENSIONS variable when the language detection module exits.
Unfortunately, there is no blessed way to override thi... |
71,041,135 | 71,041,227 | Why does this test fail if someone else runs it at the same time? | I was watching a conference talk (No need to watch it to understand my question but if you're curious it's from 35m28s to 36m28s). The following test was shown:
TEST(Foo, StorageTest){
StorageServer* server = GetStorageServerHandle();
auto my_val = rand();
server -> Store("testKey", my_val);
EXPECT_EQ(my_val,... |
One of the speakers said: "you can only expect that storing data to a production service works if only one copy of that test is running at a time."
Right. Imagine if two instances of this code are running. If both Store operations execute before either Load operation takes place, the one whose Store executed first wi... |
71,041,528 | 71,043,428 | How to make external dependencies on a shared items project in VS? | I am in need of sharing some header files between two different projects. So I created a shared items project, and now I can't figure out how to add external dependencies to it, so I could use includes from the WDK 10 shared folder. Did anyone run into this problem before? I can still add external dependencies on a lib... | As the article says
These “shared items” projects don’t participate in build but they can
contain any number of C++ headers and sources.
And you need to add the dependencies to the actual build project.
|
71,041,798 | 71,041,854 | How to convert from any type to std::string in C++ | I'm making a LinkedList class using template, since I want to use it for whatever type I need afterwards
template <typename T> class LinkedList {}
I'm trying to make a function that adds all the elements of a list into a string:
std::string join(const char *seperator)
{
std::string str;
auto curr = this->head;... | There is no universal way to convert an object of arbitrary type to a string in C++. But the most commonly supported facility for outputting data as strings are output streams. So, you could use std::ostringstream like this:
std::string join(const char *seperator)
{
std::ostringstream strm;
auto curr = this->he... |
71,042,002 | 71,042,061 | Confusion about this pointer and callback functions | Let's say I have the following scenario where I define a callback function m_deleter.
class B {
public:
B() = default;
~B(){
if (m_deleter) {
m_deleter();
}
}
std::function<void()> m_deleter = nullptr;
};
class A {
public:
void createB(B& b) {
auto func = [this... | It doesn't. But due to the fact that in the method printMessage you don't reference any fields from the class A, there is no crush. This is an UB however.
Here is the code that avoids this issue but demonstrates the correct behavior:
class A {
public:
void createB(B& b) {
auto func = []() {
A::p... |
71,042,135 | 71,042,176 | Is `-ftree-slp-vectorize` not enabled by `-O2` in GCC? | From https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
It says "-ftree-slp-vectorize: Perform basic block vectorization on trees. This flag is enabled by default at -O2 and by -ftree-vectorize, -fprofile-use, and -fauto-profile."
However it seems I have to pass a flag explicitly to turn on SIMD. Did I mis undert... |
Is -ftree-slp-vectorize not enabled by -O2 in GCC?
Yes and no. It depends on the version of the compiler.
From https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
You have linked to the latest version of documentation. It applies to the version that is currently under development, which at the moment is versio... |
71,042,377 | 71,042,568 | What is the proper design pattern for a callback in destructor which uses a pointer which may or may not point to valid object? | Let's say we have the following scenario.
We have a ImageManager class which is used to internally store and manage image data.
The ImageManager class has a public member populateImage, which will read an image into memory, then return a populated MyImage which is a std::shared_ptr around an Image object. This object w... | Overall the design smells. If the ImageManager is a local object, and MyImage are outside of the scope, why do you need to delete the items in the map?
Anyway, I promised you to show the shared/weak idiom. Wrap the map into a shared_ptr. That would mean that the map will be destroyed together with the ImageManager (if ... |
71,042,417 | 71,042,450 | "Undefined symbol" error with my functions when using classes | I'm writing a program that calculates the area and diameter using classes and functions. My issue is that I'm getting an undefined symbol error with my functions. I'm sure it's probably an easy fix ... I just can't figure it out.
(Writing the code on a mac)
Here's the code:
#include<iostream>
using namespace std;
clas... | int main()
{
// delete printArea() and printDiameter() lines
// void printArea(Circle);
// void printDiameter(Circle);
Circle aBigCircle, aLittleCircle;
aBigCircle.radius = 50;
aLittleCircle.radius = 4;
aBigCircle.printArea();
aBigCircle.printDiameter();
aLittleCircle.printArea();
aLittle... |
71,042,424 | 71,042,584 | c++ getservbyport returning wrong information | When I run this code:
#include <iostream>
#include <netdb.h>
int main(){
struct servent* serv = getservbyport(22, "tcp");
if(serv != NULL){
std::cout<<"name: "<<serv->s_name<<" type: "<<serv->s_proto<<std::endl;
}
return 0;
}
The result is:
name: pcanywherestat type: tcp
If I were to run gets... | getservbyport(3) and family store numeric values in Big Endian (aka, network byte order). As a result, you need to convert any int's, in this case with htons(), thusly:
struct servent* serv = getservbyport(htons(22), "tcp");
hton*(3) convert values between host and network byte order
Edit: the functions htons, htonl,... |
71,042,765 | 71,044,776 | Why are there no monadic operations in std::expected? | In C++23, monadic operations in std::optional was adopted, and later on std::expected. Why were monadic operations like and_then, transform, and or_else not included in the main paper?
| The std::expected proposal is very old. The adopted revision is P0323R12, which already suggests a long life, but that paper even predates the P-numbering system and started out as N4015, dated May 2014.
I bring this up because std::expected, even by itself, has taken a very long time to wind its way through the proces... |
71,042,923 | 71,043,248 | Can't make my example using std::ranges::copy_if(R&& r, O result, Pred pred, Proj proj = {}) compile | I've reduced the code failing to compile to the one below:
[Demo]
#include <algorithm> // copy_if
#include <iostream> // cout
#include <iterator> // back_inserter
#include <ranges>
#include <string>
#include <vector>
struct A
{
std::string p{};
std::string d{};
};
int main()
{
std::vector<A> v{{"/usr/b... | The projection applies only to the predicate, not to the result. There's already a way to transform the data entirely—std::views::transform:
std::ranges::copy_if(
v | std::views::transform(&A::p),
std::back_inserter(o),
[](const std::string& p){ return (p.size() > 10); });
(This compiles in GCC and MSVC, b... |
71,043,035 | 71,043,142 | How to understand the requirement of `std::lower_bound`? | As per the document about std::lower_bound, which says that:
The range [first, last) must be partitioned with respect to the expression element < value or comp(element, value), i.e., all elements for which the expression is true must precede all elements for which the expression is false. A fully-sorted range meets th... |
What's element < value
value is the parameter to lower_bound, see at the beginning of that page:
template< class ForwardIt, class T > ForwardIt lower_bound( ForwardIt
first, ForwardIt last, const T& value );
The value in question is mentioned right here, the last parameter to the template. And element, references t... |
71,043,055 | 71,043,327 | Linked list c++ insertback | I am really new to data structures. I am trying to figure out why my insertback() function doesn't work. The first print does 3,2,1 but the second doesn't print anything. I think it has something to do with head, but I'm not really sure. Please help.
#include <iostream>
using namespace std;
struct Node
{
int data;... | You are not initializing head to NULL to indicate an empty list, so ``head` will have a random garbage value, and thus all of your methods exhibit undefined behavior.
Once that is fixed, your while loops in both Print() and Insertback() are buggy, as they are not account for head being NULL when the list is empty.
Also... |
71,043,203 | 71,131,937 | Is template metaprogramming fully able to be substituted in C++20? | Although the idea of template metaprogramming - calculate something at compile time when possible - is wonderful,I wonder if current C++20 features allow us to avoid the TMP fully by using constexpr, consteval, if constexpr,concept, and other C++20 features. Is this true? Or some functionality that TMP offer is not abl... | No, template metaprogramming cannot be fully replaced by C++20 language utilities; though a large amount can.
constexpr, consteval, etc. all certainly help lighten the load off of things that are traditionally done with TMP (as has been increasingly the case over the years), but templates still serve an orthogonal purp... |
71,043,552 | 71,052,909 | How to use a C/C++ library (like NCurses) in Haxe | I have a cli written in Haxe and compiled to a binary via C++ (hxcpp). I would like to use ncurses in it. I have worked with ncurses in C and I've worked with JS externs in Haxe but I'm can't figure out the Haxe/C++ documentation to connection the two together.
I haven't used much more of the HXCPP compiler than the ba... | HXCPP uses an xml-based build system. When you launch haxe -cp src --cpp bin/cpp path.to.Main:
Haxe files are transpiled to C++ and a Build.xml is produced in the output directory, i.e. bin/cpp/Build.xml;
everything is then built by HXCPP, merging the newly generated project Build.xml with the global default xml defin... |
71,043,619 | 71,043,645 | Bazel: submodule in project does not use bazel , pushing to git doesnt include locally added BUILD file in submodule, how do i build? | I am just starting to learn how to use bazel following this tutorial
One thing I am unsure how to do is how to use a submodule, from my own repo for example. where I do not use bazel. The repo just has some c/h files that I need to pull in. To make things work locally I added a BUILD file in folder pulled in from submo... | If you use new_local_repository with a relative path to import the submodule, you can set build_file or build_file_content to add the BUILD file. You should be able to use that same BUILD file as-is.
Because it will be in a different external repository, you'll need to access it via the corresponding label.
For exampl... |
71,043,905 | 71,044,793 | C++ template what does this class assignment in template mean? | template<classT>
class MyClass {
using KeyType = int;
using MapType = std::map<KeyType, int64_t>;
MapType map_;
template <class T1 = T, class = std::enable_if_t<std::is_same<T1, int>{}>>
IndexValueType LowerBound(KeyType k) const {
auto it = map_.lower_bound(k);
if (it == map_.end()) {
return NOT_FOUND... | LowerBound is a member template function declared inside the class template MyClass. It's similar to a function template but it is enclosed in a class (template).
The code can be simplified as
template <typename T>
class MyClass {
template <typename T1 = T, typename = std::enable_if_t<std::is_same<T1, int>{}>>
... |
71,044,230 | 71,044,297 | Can't get Boost C++ Libraries to work in an AWS Linux Environment | I am trying to transfer a C++ project started by a colleague to a AWS Cloud9 environment.The project was originally developed on Mac and makes use of the Boost library.
I've set up the AWS Cloud9 environment to use Amazon Linux. Once the environment created I import the project using the "Upload Local Folder" function.... | Amazon Linux 2 has boost 1.53. This is too old, and container_hash has not been yet available.
You have to manually build newer version of boost.
|
71,045,477 | 71,048,868 | Is there a way to enumerate interfaces using NI Daqmx | I have a C++ application interfacing with a NI DAQ card, however the name of the device is hard coded and if changed in the NI Max app it would stop working, so is there a way to enumerate connected devices to know the name of the cards that are connected ?
| List of all devices can be retrieved with DAQmxGetSysDevNames(). The names are separated by commas.
Once you have the list of all names, you can use the product type to find the correct device.
const std::string expectedProductType = "1234";
constexpr size_t bufferSize = 1000;
char buffer[bufferSize] = {};
if (!DAQmxFa... |
71,045,603 | 71,045,787 | Multiple override-methods in inheritance each have multiple possible implementations | Let me introduce the following three classes: AbstractProcessor and these two child classes. The code below is not complex because there are only two child classes, but what if procedures1 and procedure2 both has many N candidate implementation? In such case, there are NxN child classes and a lot of duplication will be... | Inheritance is not the solution to everything. Sometimes all the problems are gone once you don't use inheritance. There are many different ways to do what you want. One is to store the callables as members:
#include <functional>
#include <iostream>
struct Processor
{
std::function<void(Processor*)> procedure1;
st... |
71,045,789 | 71,073,316 | How to check memory leaks using memory usages of a process? | int ParseLine(char* line){
int i = strlen(line);
const char* p = line;
while(*p < '0' || *p > '9') p++; // Search until a number is found.
line[i - 3] = '\0'; // Remove " kB"
i = atoi(p);
return i;
}
int GetCurrentVirtualMem(){
std::string cur_proc;
cur_proc = "/proc/" + std::to_string((int)... | If I understand you correctly you want to check for memory leaks on Linux using a process image from an process that has not been instrumented in any way.
https://github.com/vmware/chap (free open source) does this.
First you gather a core:
echo 0x37 > /proc/<pid-of-your-process>/coredump_filter
gcore <pid-of-your-proc... |
71,045,918 | 71,047,638 | How to print a X with two letters inside a square | I am trying to make the this shape but stuck at here. I tried with counters more than one but failed again.
P p p p p p Q
p P p p p Q q
p p P p Q q q
p p p Q q q q
p p Q q Q q q
p Q q q q Q q
Q q q q q q Q
int main()
{
int loopLimit = 7;
int upperCharacter = 0;
do {
int loopCounter = 0;
... | A pen and a paper solved this question.
Here's the solution:
for (int satirSayaci = 1; satirSayaci < 8; satirSayaci++) {
for (int karakterSayaci = 1; karakterSayaci < 8; karakterSayaci++)
{
if (karakterSayaci >= 8 - satirSayaci) {
if (karakterSayaci == 8 - satirSayaci || kara... |
71,046,011 | 71,046,265 | Send UWP Object from C++ to C# | I have code in C++ that generates a SpatialCoordinateSystem instance and wish to send this over for my C# code to use. I saw here that a I can simply create such an instance in C# if I have a native pointer to said object, so this was my initial approach. Unfortunately, I am not able to get this to work as I keep encou... | You can use COM to transfer data from C++ to C#. What you have to do is create similar structure (COORD in your case) in C# code. Then create an interface in C# code and implement one function inside that interface that will accept the argument of type of that structure (COORD). Now, you just have to make a tlb file fr... |
71,046,440 | 71,046,582 | In C++ How can I read in different types of data in one instream of the same cin object | I wrote a custom class CMyistream_iterator. Its constructor has an argument of an istream object.
template <class T>
class CMyistream_iterator
{
private:
T valArray[100];
int pos;
public:
CMyistream_iterator(istream& in):pos(0){
T n;
int i=0;
while(in>>n){
*(valArray+i) ... |
It seems that when the integer iterator comes to the character 't', it was converted into EOF.
That is not what happens. When cin >> n in the int iterator encounters the character 't', it fails to read in an int value, and thus puts cin into an error state that you need to explicitly reset with cin.clear() before you... |
71,047,000 | 71,047,081 | error: no matching function for call to 'Node::Node()' - second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...) | I've defined a structure like this:
struct Node
{
int32_t a;
int32_t b;
double c;
double d;
Node (int32_t a, int32_t b, double c)
{
this->a = a;
this->b = b;
this->c = c;
this->d = 0.0;
}
};
I'm implementing a map of map like this:
unordered_map<UInt32,unordered_map<int32_t,N... | It is because that unordered_map<int32_t,Node> tries to call the constructor Node() with no argument, and because you defined the constructor with three argument, Node() is deleted. Consider adding Node()=default; inside the class definition.
|
71,047,085 | 71,047,681 | Can't find error in my merge sort implementation, getting wrong output? | In the code below I was given unsorted array had to find kth smallest
Given an array arr[] and an integer K where K is smaller than size of array, the task is to find the Kth smallest element in the given array. It is given that all array elements are distinct.
#include<bits/stdc++.h>
using namespace std;
Merge funct... | The non-standard variable length arrays and other considerations notwithstanding (seriously, get a good reference book and reputable tutorial guide), the problem is in your merge algorithm:
At the end of merge you're trying to put the sorted marr data back into arr. That is done here:
for(k=0;k<=(r-l);k++,l++)
{
ar... |
71,047,307 | 71,047,522 | Call different constructors from different structs based on input parameter value | recently I'm working on an problem like that
struct A {
A() {/* Constructor A */ }
void method() { /* method A */ }
};
struct B {
B() {/* Constructor B */ }
void method() { /* method B */ }
};
struct C : public A, public B {
C(int which) :A() {}
C() :B() {}
static C ConstructIt(int which)... | It seems you want polymorphism. There are several ways.
One common way is with interface and virtual functions:
struct C
{
virtual ~C() = default;
virtual void method() = 0;
};
struct A : C {
A() {/* Constructor A */ }
void method() override { /* method A */ }
};
struct B : C {
B() {/* Construc... |
71,047,430 | 71,048,077 | Why I can't pass string literals to const char* const& in this specialized function template | Why pass a string literal to const char* const& in a specialized function template is illegal, while to const char* is legal?
Here's the thing. There are two excercises about template specialization in C++ Primer:
Exercise 16.63: Define a function template to count the number of
occurrences of a given value in a vecto... | You don't "pass to a function template specialization". The call is deduced against the original template definition (regardless of any specialization), deducing a type if successful. Then if a specialization exists for the deduced type then that will be called.
The error message is about type deduction failing . You ... |
71,047,476 | 71,048,213 | What is the best way to tell the compiler to differentiate between two types which hold the same kind of data | Suppose we have two types which are basically ints:
alias UserID = int;
alias ItemID = int;
And suppose we have two functions which take arguments of the two types:
void add_user(UserID id) { std::cout << "Adding user with id " << id << '\n'; }
void add_item(ItemID id) { std::cout << "Adding item with id " << id << '\... | You can use "shadow types" (they have names but no definition) and a template (or use some "strong typedef" library):
template <typename>
class Id
{
int val;
operator int() const { return val; }
};
using UserID = Id<struct user_tag_>;
using ItemID = Id<struct item_tag_>;
And you should provide operator overlo... |
71,048,332 | 71,048,447 | Does "auto" keyword always evaluates floating point value as double? | Continuing the question, which was closed:
C++: "auto" keyword affects math calculations?
As people suggested I modified the code by adding "f" suffix to floating-point values.
#include <cmath>
unsigned int nump=12u;
auto inner=2.5f;
auto outer=6.0f;
auto single=2.f*3.14159265359f/nump;
auto avg=0.5f*inner+0.5f*outer;
... | The issue is that your code is using ::sin instead of std::sin (and the same for cos). That is, you’re using the sin function found in the global namespace.
std::sin is overloaded for float. But ::sin isn’t, and it always returns a double (because ::sin is the legacy C function, and C doesn’t have function overloading)... |
71,048,420 | 71,048,449 | Multidimensional array printing wrong values in cpp | I've been struggling with a simple class representing a matrix in C++. Instead of using a multidimensional array, I've decided to use a flat array and access the values by calculating the index of the according cell by [row * x_dim + col]. I want to use 2D matrices only.
Ideally, I would also create getter and setter f... | This is the wrong index:
row * test.x_dim + col
Suppose you are in the last iteration of the outer loop then row == x_dim-1 and you get:
(x_dim-1) * x_dim + col
while it should be (supposed x is rows):
(y_dim-1) * x_dim + col
Tip: Your variable naming col vs x_dim and row vs y_dim can be made better. x, x_dim and... |
71,048,555 | 71,055,458 | Extract boost log attribute values of arbitrary type | There is a logging system with the number of attributes of arbitrary types. The attributes are added by external program(s) using public API (function template). The types aren't known beforehand. The typical way to print out an attribute's value looks like (simplified):
void print(logging::attribute_value const& attr)... |
Is there a way to print out (or convert to strings) all values regardless of their types, assuming the types overload streaming operator?
No, Boost.Log doesn't support that, you must know the name and type of the attribute value in order to be able to extract or visit it.
What you could do is maintain your own mappin... |
71,048,946 | 71,052,900 | Is there a way to check if a class is convertible to some template instantiation? | The question
Here some code
struct Base
{
int SomeMethod(const Base&);
template <class T> int SomeMethod(const T&);
};
template <class Tag> struct Derived : Base
{
using Base::SomeMethod;
int SomeMethod(const Derived&);
template <class OtherTag> std::enable_if_t<!std::is_same_v<Tag, OtherTag>> Some... | No. There's an infinite set of possible conversions, even an infinite set of conversions to Derived<SomeUnknownType>. Your compiler cannot test every possible type T to see if ImplicitOpToAnotherTagInstantiation is perhaps convertible to Derived<T>.
It could test a finite set, if you provide that. But you only have tag... |
71,049,080 | 71,049,168 | C++ how to add destructor to anonymous class? | how do you add a destructor to an anonymous class in C++? like in PHP if i want to run something when my class go out of scope it'd be
$foo = new class() {
public $i=0;
public function __destruct()
{
echo "foo is going out of scope!\n";
}
};
but in C++ with normal non-an... | This cannot be done in C++. However, the real C++ analogue of anonymous classes is called an anonymous namespace:
namespace {
struct foo {
// ... whatever
~foo();
};
}
// ... later in the same C++ source.
foo bar;
Now you can use and reference foos everywhere in this specific C++ source file. Other C... |
71,049,612 | 71,051,386 | Overloading class name with integer variable | I am learning C++ using the books listed here. In particular, i read about overloading. So after reading i am trying out different examples to clear my concept further. One such example whose output i am unable to understand is given below:
int Name = 0;
class Name
{
int x[2];
};
void func()
{
std::cout << ... | Since you added the language-lawyer tag:
When a class and a variable of the same name are declared in the same scope, then the variable name hides the class name whenever name lookup would find both of them, see [basic.scope.hiding]/2 of the post-C++20 standard draft. (Note that there was significant rework of the word... |
71,050,254 | 71,050,564 | OpenCV & C++: returned cv::Mat causes a Segmentation Fault | I'm writing a class that grabs frames from basler USB cameras using pylonAPI and converts them to openCV format. Here's the code of the grabbing method:
std::pair<cv::Mat, cv::Mat> GrabPair()
{
int key;
Pylon::CImageFormatConverter fmtConv;
Pylon::CPylonImage pylonImg1, pylonImg2;
fm... | the problem here is, that the Mat constructor using an external pointer is NOT refcounted. once you leave the GrabPair function, both Mat's are invalid (dangling pointer)
you need to clone() them (deep copy of the data !) e.g. like:
return std::make_pair(outImageL.clone(), outImageR.clone());
|
71,050,437 | 71,128,510 | Adding elements to C++ vector | I want to learn more about C++ coding, especially to design and create a desktop application.
To begin, I want to create a notification app where I can make a task by giving the task a name and content. For this, I use 2 vectors (name and content).
I initialize the vectors like this:
std::vector <LPWSTR> NameTask;
std... | I change it and it work. it may not be the ideal and correct way but i will let it how it is.
if (wmId == ID_BUTTON) {
//local variables (only for the Button event)
int len_name = GetWindowTextLength(TextBox_Name)+1; //give the lenght value of the text in the textbox
int len_content ... |
71,050,636 | 71,050,704 | Unique_ptr with custom deleter | Here is a MRE of my code:
#include <memory>
struct Deleter
{
void operator() (A* a) {}
};
class A
{
A(int a) {}
};
int main()
{
std::unique_ptr<A, Deleter> unique = std::make_unique<A, Deleter>(5);
}
I get this error:
error C2664: 'std::unique_ptr<A,std::default_delete<A>> std::make_unique<A,Deleter,0>(... | You cannot use std::make_unique with a custom deleter. You’ll need to use the regular constructor instead:
auto unique = std::unique_ptr<A, Deleter>(new A(5), Deleter());
Of course this will still require you to fix the rest of your code: make the constructor of A public, and declare A before Deleter. And you’d need t... |
71,050,669 | 71,050,758 | C++ Polymorphic behaviour with global array of Base Class type | Why is the code below able to demonstrate polymorphic behaviour
TwoDShapes* s2d[2];
int main()
{
Circle c1(/*parameter*/);
Rectangle s1(/*parameter*/);
s2d[0] = &c1;
s2d[1] = &s1;
for (int i = 0; i < 2; i++)
cout << s2d[i]->toString() << endl;
return 0;
}
BUT the code below throws a... | c1 and s1 are local variables to function test.
The moment it finishes, you can no longer access them.
So, s2d[i] contains a pointer to some local variable of test function. By the time this code cout << s2d[i]->toString() << endl; runs, the test function already terminated. So all local variables are destroyed. Callin... |
71,050,980 | 71,051,677 | Python to .cpp and back again with ctypes via an .so | I'm doing something stupid, but not seeing what... I've reduced my problem to the below (absurd) example - but it highlights where my issue is - I'm clearly not able to pass data into and/or return from, c++, coherently.
test.cpp
extern "C"
double reflect(double inp){
return inp;
}
The above is compiled with:
g++ ... | Object files and shared libraries do not contain any information about the types of function parameters or return types, at least not for C linkage functions.
Therefore ctypes has no way of knowing that the function is supposed to take a double argument and return a double.
If you call it with anything else than ctypes... |
71,051,289 | 71,051,442 | Im trying to create a a code that count numbers divisible by 9 by putting numbers into an array and count the numbers in it | Im trying to create a a code that count numbers divisible by 9 by putting numbers into an array and count the numbers in it but it only prints 1 instead of the number of numbers divisible by 9 please help me i want to use array to count those numbers
#include <iostream>
using namespace std;
int main(){
int a,b,i;
... | Nowhere in your code are you adding numbers to the array. Anyhow, it is not possible to add elements to arrays, because they are of fixed size. Your array has a single element.
Moreover, int numbers[]={i}; is undefined, because i has not been initialized.
Further, it is not clear what is the purpose of sizeof(numbers)/... |
71,051,368 | 71,053,082 | Synchronizing between a local and remote GUI | Consider the following GUI:
when the user press the + button the value is incremented to 6.
However on another computer another user is running the same GUI.
The two GUIs have to stay in sync.
If one of the users press the + button the value should be updated for both GUIs.
The remote GUI, the client, communicate with... | It cannot work with those commands.
The logic is well-known from the design of multi-core CPU's. You need Compare-and-Swap (CAS), Load-Link/Store Conditional (LL/SC) or something equally powerful. With the weak protocol you have, it can be proven that the race conditions are unsolvable.
|
71,051,954 | 71,057,856 | Converting Metal Shader texture type from 2D to 2D Multisample | I am following a tutorial by 2etime on YouTube about Apple's Metal graphics API. Everything works as intended, but when I try to change the view's sample count, I get a lot of errors. The errors, though, are easily fixed. So far, I've changed the sample count in every file, but I am stuck at the shaders. To change the ... | Sampling in a way that sample function means doesn't make sense for multisampled textures. What you are looking for instead is reading the exact sample value at a given texcoord.
If you look in the Metal Shader Language specification, in section 6.12.8 it describes which functions exist for 2D multisampled textures.
Th... |
71,052,051 | 71,052,119 | Does move constructor only affect the memory space pointed to by the pointer member of the class? | For example, this Code:
struct President
{
std::string name;
std::string country;
int year;
President(std::string p_name, std::string p_country, int p_year)
: name(std::move(p_name)), country(std::move(p_country)), year(p_year)
{
std::cout << "--constructed\n";
... |
And my meaning is right?
Sorry, no. Your move constructor will work as you describe, in that it will 'steal' the contents of the name and country member variables from other, but the copy constructor will not. std::move does nothing with a const object and you should remove it from your copy constructor. After all... |
71,052,442 | 71,052,479 | "lvalue required as left operand of assignment" for all of my if/else statements. What have I done wrong? | I'm making a basic calculator that uses if/else statements to select a sign to use in the equation. All of the else/if statements are reporting an error:
error: lvalue required as left operand of assignment
#include <iostream>
using namespace std;
int main()
{
//declare variables
int num1;
int num2;
... | You have your assignments reversed. = is not a commutative operator.
They should all be of the form
sol = num1 op num2
What you are trying to do is assign the (uninitialised) value of sol to the unnamed temporary that results from the calculation. Happily this is a hard error with fundamental types.
|
71,052,452 | 71,052,553 | Aggregate initialization of a derived class with designator | From cppreference we can know:
Since C++17 for derived types:
If the initializer clause is a nested braced-init-list (which is not an expression), the corresponding array element/class member /public base (since C++17) is list-initialized from that clause: aggregate initialization is recursive.
Since C++20 for aggreg... | As you've discovered, you can't use both designated initialization and also name the base class. In order to do that, the language needs to be extended to support that case. See P2287R1, which I have not finished yet. Unfortunately, won't make C++23.
Until the language directly supports designated the base class (or di... |
71,052,584 | 71,053,275 | Linux - Open socket for specific network adapter | The problem
I have a computer that is supposed to connect to two machines (or rather sets of individual devices) via TCP. To make things tricky, these two machines share the same IP address range and also have partially identical addresses, only one is connected via one ethernet adapter and the other one via a second e... | Just pinning the sockets to a specific interface wouldn't do the job, since there are much more things going on... If you connect say to 192.168.0.3, the kernel looks into the routing table to find the right interface to send the packet over. You cannot have two entries in the routing table with the same subnet specifi... |
71,052,805 | 71,053,030 | Error nested std::thread inside a thread throws an error | I'm trying to get this simple test to create a nested thread inside another thread, but it keeps failing. Tried removing this nested function and the code works fine on its own.
Code example/test:
#include <thread>
#include <iostream>
#include <vector>
void simple() { std::cout << "\nNested Thread"; }
void function... | You are reading and writing to sum and thread_group from multiple threads at the same time. A simple solution is you make sure that only one thread at a time has access to them by using a std::mutex and locking it while accessing those variables. You also need to make sure that all threads are finished working with thr... |
71,052,971 | 71,085,072 | How to store boost::hana::map inside a class? | I want to store boost::hana::map inside a class so that I can write code like this inside the class:
if constexpr (boost::hana::contains(map_, "name"_s)){
std::cout << map_["name"_s] << std::endl;
}
But I am getting an error:
note: implicit use of 'this' pointer is only allowed within the
evaluation of a call to ... | Yes, using this here appears to be right out.
Since the information you are trying to access should be accessible at compile-time, one simple workaround would be to use the type of the entire expression.
void print_name()
{
if constexpr (decltype(boost::hana::contains(map, "name"_s)){})
{
Print(map["nam... |
71,053,102 | 71,060,949 | GDB issue when using enum with type definition in c++ | I have an enum with an explicit underlying type definition like this:
enum test : uint16_t
{
test_x = 0x7fff, // 0111 1111 1111 1111
test_y = 0x8000 // 1000 0000 0000 0000
};
And variables in my code that are assigned the enum values like this:
test num1 = test_x;
test num2 = test_y;
When I try to look at th... | I will answer my own question after getting some helpful pointers in the comments.
This turned out to really be a bug in the GDB version I was using.
upgrading to a newer version solves this issue.
(I upgraded from 8.1 to 10.2)
(gdb) print num1
$1 = test_x
(gdb) print num2
$2 = test_y
(gdb) show version
GNU gdb (GDB; J... |
71,053,504 | 71,060,859 | Strange behaviour insert_one mongocxx 3.6 | Working with mongocxx I am trying to retrieve the object id assigned by mongodb when I insert a new object in a collection(insert_one method), and convert this id into a string. This is the code:
const mongocxx::database& db = _pClient->database(_dbName.c_str());
mongocxx::collection& collection = db.collection(col... | The debugger is showing you the individual bytes in decimal.
I used the mongo shell to convert these to hex, you can see that it is indeed the ObjectID you were looking for, it just looks strange in decimal
mongos> [98,3,-24,41,-88,89,0,0,-93,0,88,-78].map(n=>("0" +((n & 255).toString(16))).slice(-2)).join("")
6203e829... |
71,053,575 | 71,056,261 | vector::push_back using std::move for internal reallocations | A type X has a non-trivial move-constructor, which is not declared noexcept (ie. it can throw):
#include <iostream>
#include <vector>
#include <memory>
struct X {
X()=default;
X(X&&) { std::cout << "X move constructed\n"; } // not 'noexcept'
X(const X&) { std::cout << "X copy constructed\n"; }
};
struct ... | According to [vector.modifiers]/2 if the element type of std::vector is not copy-insertable and not nothrow-move-constructible, then an exception thrown from a move constructor of the element type results in an unspecified state of the container.
std::vector must prefer the copy constructor if the type isn't nothrow-mo... |
71,054,550 | 71,055,477 | Boost multiprecision rounding towards 0 | The code below compiles just fine on Windows using VC++:
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
namespace mp = boost::multiprecision;
using BigFloat = mp::cpp_dec_float_50;
using BigInt = mp::uint256_t;
template <int decimals = 0, typename T... | Like many people already suggested, expression templates are the culprit:
T is deduced as
boost::multiprecision::detail::expression<
boost::multiprecision::detail::divides,
boost::multiprecision::number<
boost::multiprecision::backends::cpp_dec_float<50>>,
boost::multiprecision::detail::expression<
... |
71,054,845 | 71,055,091 | Partial deduction of template parameter using constructor | I have seen this asked before in several ways, and all the solutions are always the same: use a helper function or even use nested classes. For me, both of those solutions look clumpsy. So I wonder how come in the c++17/c++20 era there is not better solution to this problem:
EDIT: The question here is if there is any m... | I most often use a "type tag" to overcome this kind of problems. It also comes in handy for similar issues, like the lack of partial specialization of function templates.
#include <type_traits>
template<typename T> struct type_t{};
template<typename T> constexpr type_t<T> type;
template<class T1, class T2>
struct imp... |
71,055,422 | 71,056,251 | C++ vector of vector conversion | I am fairly new to C++ and this might be a dumb question.
If I have 2 vectors,
vector<vector< double >> v1 , has values
and
const vector<vector< double> * > * v2, has no values
.
How would I go about storing the elements from v1 to v2 or would it be possible to cast v1 as
const vector<vector< double> * > *
| v1 is a vector of vectors, i.e. each element of v1 is a vector of type vector<double>.
v2 is a pointer to a vector of pointers, that is it points to a vector, which has pointers (to other vectors) as elements.
As you can see, v1 and v2 are completely different, in terms of types and binary layout, so no, you cannot cas... |
71,055,837 | 71,060,671 | Purposeful random memory allocations | For an experiment, I want to measure time it takes to find a given record with random memory access. The record is a simple class:
template<class TKey, class TData>
class Record {
TKey key;
TData data;
public:
Record(TKey key, TData data) {
this->key = key;
this->data = data;
}
};
Now I simply allocat... | The best answers are commented under the question by UnholySheep and
Fabian. See their comments for the correct answer.
|
71,055,963 | 71,056,056 | Understanding SendMessage wparam | I am working on an MFC project, which has the following code:
NMHDR pNMHDR;
pNMHDR.hwndFrom = GetSafeHwnd();
pNMHDR.idFrom = GetDlgCtrlID();
pNMHDR.code = EN_CHANGE;
GetParent()->SendMessage(WM_NOTIFY, (EN_CHANGE << 16) | GetDlgCtrlID(), ( LPARAM ) &pNMHDR);
Please help me in understanding what (EN_CHANGE << 16) | Get... | Per the EN_CHANGE documentation for standard EDIT controls:
wParam
The LOWORD contains the identifier of the edit control. The HIWORD specifies the notification code.
So, the code is taking the constant EN_CHANGE, shifting its bits to the left 16 places, and then OR'ing the bits of the control ID. Thus, EN_CHANGE en... |
71,056,992 | 71,057,087 | Can't modify a string in C++ array | Trying to learn datastructures, I made this class for a stack. It works just fine with integers but it throws a mysterious error with strings.
The class List is the API for my stack. Its meant to resize automatically when it reaches the limit. The whole code is just for the sake of learning but the error I get doesn't ... | string* list = new string[max]; in the resize method defines a new variable named list that "shadows", replaces, the member variable list. The member list goes unchanged and the local variable list goes out of scope at the end of the function, losing all of the work.
To fix: Change
string* list = new string[max];
to
l... |
71,057,083 | 71,059,095 | How to change the location of .pdb files for static libraries? | Now I found out I can change the .pdb file location for C++ executable projects in Linking -> Debugger in the project settings.
How can I change the location for static library projects? As they do not have the Linker menu.
I tried changing C/C++ -> Output files -> Program Database File Name, but without luck. They are... | After changing the Program Database File Name, pdb will be added to the specified directory. In addition, if the lib file directories are not changed, another pdb file will also be added aside the lib. This may be why you think it was unsuccessful, but in fact it has been done.
|
71,057,307 | 71,066,390 | Drogon: how to use execSqlCoro? What headers to include? | I'm tryin to use the execSqlCoro function of Drogon. However, I am getting an error:
error: unable to find the promise type for this coroutine
26 | auto municipalities = co_await db->execSqlCoro(
What headers to I have to include to get the correct promise type?
See tests here. I tried
#include <drogon/orm/DbClie... | I'm the author of Drogon's coroutine subsystem. I'm sorry for the confusion. That error message shows up when you didn't mark the function that calls the coroutine having return type as Task<T> (or to be accurate, an awaitable type that is compatible with Drogon or cppcoro's coroutine concept). For example the followin... |
71,058,520 | 71,058,879 | Getting value of random address location without storing it in a variable | #include<iostream>
using namespace std;
struct node{
int data;
node* l,*r;
};
int main()
{
node* n1 = new node;
cout<<(n1->l);
return 0;
}
in the above code I didn't initialize struct data, l and r. so now the address stored in n1->l is CDCDCDCD. Now if I want to see the value stored in that ad... | In general, you can cast any integer to a pointer at your own risk.
node* my_ptr = (node*)0xDEADBEEF; // Casting to a pointer
node my_node = *(node*)0xDEADBEEF; // Casting to a pointer and dereferencing
The second line is what I believe you want to do "without storing the address in a variable". However that's hacky ... |
71,058,628 | 71,058,689 | Program gets frozen because of a loop | I'm making a program which calculates the date by giving the program a date and number of days to add to that date in input. In order to do this, I need to make a switch and make it repeat with a loop, but for some reasons, the program gets frozen and doesn't do anything after the user inserts the number of days to add... | Your loop runs until addDays falls to <= 0. The problem is, when you add addDays to day, if the resulting finalDay IS within the current month's number of days, you ARE NOT breaking the loop, and you ARE NOT adjusting the values of day or addDays either, so the loop iterates again with the same day and addDays values,... |
71,058,972 | 71,061,472 | How do I clear a c variable after use to use it again? | If I send a message over serial the first time it receves the right code it works but after that it stops working.
const unsigned int MAX_MESSAGE_LENGTH = 32;
const char EMPTY[1] = {'\0'};
void setup() {
Serial.begin(9600);//bPS
}
String readserial(){
char message[MAX_MESSAGE_LENGT... | Your message length message_posisn't being reset to zero. Whatever value it has, the value will be "kept" because you have declared it as static. If you remove the statickeyword, message_pos will be reset to zero every time you call readserial().
You can also, as pointed out, set message_posto zero as you return the s... |
71,059,078 | 71,061,199 | Qt: Inherit QObject in parent and other QWidget subclass in child | I am writing a series of custom classes for Qt. What I need is to have a base class that has few custom signals and slots, and children classes will have it. However, I do know that inheriting from the same classes will be thrown an error. I have read the documentation but only dictates that I need to include QObject i... | Multiple inheritance from QObject will not work for several reasons.
(Moc-Compiler does not work correctly and QObject has member variables which makes mutliple inheritance unsafe).
You better work with composition instead of inheritance in case you want to provide the same behavious to several objects.
|
71,059,957 | 71,060,976 | Clang and GCC has an inconsistent interpretation to the case where the parameter name appears as an unevaluated operand | #include <iostream>
void fun(int a = sizeof(a)){
std::cout<< a<<std::endl;
}
int main(){
fun();
}
Consider this case. Clang accepts it while GCC rejects it. According to [dcl.fct.default] p9
A default argument is evaluated each time the function is called with no argument for the corresponding parameter. A par... | GCC is wrong. It assumes that a is not yet in scope in the default argument, although generally the point of declaration is immediately after the declarator before the initializer and none of the exceptions apply here. [basic.scope.pdecl]/1
An older bug report for this is here.
Note however, that the bug report has equ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.