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 |
|---|---|---|---|---|
69,546,592 | 69,546,613 | Non recursive fibonacci function | I was trying to write a non recursive fibonacci function in C++. Here is my code for it:
int fib(const int num)
{
std::vector<int> array{ 0, 1 };
for (int i = 2; i < num; ++i)
{
array[i] = (array[i - 1] + array[i - 2]);
}
return array[num];
}
int main()
{
const int n = 10;
for... | You initialized array with only two members, so only the indexes 0 and 1 are valid. Your loop goes from 2 to n which goes beyond the allocated bounds of the array when you do array[i]. To add a new element into a vector you should use push_back() instead. It will allocate new space in the array:
array.push_back(array[i... |
69,546,908 | 69,547,286 | C++ static class member with private constructor | Why can a private constructor be used in this case? I can't explain it to myself. In this case, I initialize the class field (the type of which is the same class) from the outside, since it is static.
Edit1:
I use C++ 17 (gcc 11.2).
#include <iostream>
using namespace std;
class MainMenu {
public:
MainMenu(const ... | I would use the following mental model for it:
a. Note that your are instantiating the variable (it would have an incomplete type at the class's scope, so it cannot be inline withing the class's scope), not actually (re)assigning it
b. it is already declared global/static on class's scope so technically the constructor... |
69,547,319 | 69,547,730 | Reference promotion for a derived class with no data members | I have an interesting problem involving a hierarchy of classes in a library that I maintain. A very simplified view of the situation is as follows:
class Base {
// private data + public interface to said data
};
class ClassA : public Base {
// Behaviour
};
class ClassB : public Base {
// Behaviour
};
So here I have... | Multiple inheritance
One way to achieve your goal is through multiple inheritance.
class A : virtual public Base {
//...
};
class B : virtual public Base {
//...
};
class AorB : public A, public B {
//...
};
With virtual inheritance, you only have one Base instance that is shared between the A and B that make up Aor... |
69,547,984 | 69,548,262 | How to get clang to warn about very simple narrowing | If I am using clang tools, what is the recommended way to get clang or some part of the clang toolchain to tell me that e.g. passing an int to a function that takes a short might be a bad idea?
Given this very simple program
static short sus = 0;
void foo(short us) {
sus = us;
}
int main() {
int i = 500000;
foo(... | The -Weverything option is useful in situations like this. It enables every warning option that clang has, including many that -Wall -Wextra doesn't include. Many of them are useless or counterproductive, but if there is one that warns on the code you consider problematic, this will let you find it, and tell you whic... |
69,548,441 | 69,548,463 | Error: Operand of '*' must be a pointer but has type "double" | I know this question has been asked before, but the answers there don't seem to be related to the issue I'm having.
Here's my code
#include <iostream>
int main()
{
double E;
double R;
double t;
double C;
std::cout << "This program will calculate the current flowing through an RC curcuit!\n\n";... | C++ doesn't have a ** operator like some languages do. You need to use the std::pow function to do exponents, or std::exp for the particular case of raising the mathematical constant e to a power.
#include <cmath>
...
double expo = std::exp(pow);
|
69,548,632 | 69,608,716 | How to call a void function within if statement (Arduino) | I wrote a code supposed to do the following: if I press one button while in loop void btnpress(), the program is sent to another function void blink2(), and then one led goes on and after 3 secs the led should go off, and it should also return to void btnpress() again via btnpress();.
The issue is that if i press the b... |
if I press one button while in loop void btnpress(), the program is
sent to another function void blink2(), and then one led goes on and
after 3 secs the led should go off, and it should also return to void
btnpress() again via btnpress();
According to this statement, I can suggest you to use the following code just ... |
69,549,382 | 69,559,855 | What trait makes uninitialized_copy(_n) sustituable by copy(_n)? | I am trying to understand the meaning of the types properties and supported operations, https://en.cppreference.com/w/cpp/types .
I have a library that implements in terms of low level functions things similar to std::copy_n, of course I would have to implement uninitialized_copy as well, but for many of the types, tha... | To replace uninitialized_copy with copy, the two actions must be equivalent:
uninitialized_copy: construct a new object of type Destination from an object of type Source
copy: assume an object of type Destination exists and assign to it from an object of type Source
One must put sufficient requirements on the type su... |
69,549,493 | 69,549,546 | c++ Type error for fixed-size array being passed to template requesting array pointer | I have a template function like the following:
template<typename T>
T foo(byte* &buffer){
...
}
When I try to access it with a fixed-size array I get an error:
byte buffer[100] = {};
foo<int>(buffer);
However, when I create a new variable from buffer and pass that, no error:
byte buffer[100] = {};
auto b = buf... | The error in the first case is because the array buffer does not decay because you have passed it be reference. That is you cannot bind a reference to a pointer to byte to an array of byte.
While in the second case b is a pointer which you can pass by reference.
Solution 1
One way to solve this is by removing the refer... |
69,549,923 | 69,549,980 | Result of method used to call another method yields inconsistent results | I currently have to write a program that allows a user to pick between two objects to test.
This isn't the same program exactly but it's the same premise.
class defined by header file
#include <iostream>
class example {
private:
int x;
public:
example() {
x = 10;
}
void setNum(int input) {
... | The problem is that you're passing and returning the arguments by value instead of reference. To solve this you can pass and return the arguments by reference as shown in the below modified code:
main.cpp
#include <iostream>
#include "Header.h"
//return and pass by reference
example& selectObj(example &A, example &B)... |
69,550,242 | 69,552,124 | Question about C++ global variable in JNI on android | Is using C++ global variable in JNI on android acceptable?
If so, I'd like to know the life-cycle of it.
When a.cpp is connected to b.java and instance of b is created(is global variable initialized at this point?) and destroyed(is global variable destroyed at this point?).
In a nutshell, global variable in C++ side sh... | The lifetime of native objects is tied to the lifetime of the native library that hosts them.
This, in turn, is governed by the lifetime of the Java ClassLoader that loaded the library:
In addition, native libraries can be unloaded when their corresponding class loaders are garbage collected.
In Android applications ... |
69,550,341 | 69,555,300 | Allocating an object of abstract class type in OMNET ++ define_module | I build OMNET project. The main codes as follow:
Routing.h
class INET_API Routing : public cSimpleModule, public ILifecycle, public cListener { }
Routing.ned
simple Routing like IManetRouting{ }
Routing.cc
Define_Module(Routing);
When I build the project, the error- Allocating an object of abstract class type Rou... | And this is correct. You cannot create an instance of an abstract class. You MUST implement all the methods defined by ILifecycle and cListener otherwise the behavior of the class is undefined and it is considered abstract.
|
69,550,439 | 69,550,509 | In-place creation of std::optional<MyStruct> | Assume the following code snippet:
#include <optional>
struct MyStruct
{
// MyStruct(int a) : a(a) {}
int a;
};
int main()
{
std::optional<MyStruct> ms1 = std::make_optional<MyStruct>(1);
std::optional<MyStruct> ms2{2};
std::optional<MyStruct> ms3;
ms3.emplace(3);
std::optional<MyStruct> ms... |
My main question is: Which compiler is correct, clang or gcc?
GCC is correct. Since Clang has not yet implemented P0960, this will cause the following assert to fail and disable the optional's constructor:
static_assert(std::is_constructible_v<MyStruct, int>);
is there any way to create a struct without constructor... |
69,550,614 | 69,560,240 | Rotating an image using Borland C++ Builder and Windows API functions | I built this example to quickly rotate images 90 degrees but I always get a cut of the image on the sides. After many tests, unfortunately I still don't understand the cause of the problem.
void rotate()
{
Graphics::TBitmap *SrcBitmap = new Graphics::TBitmap;
Graphics::TBitmap *DestBitmap = new Graphics::TBitma... | If rotating the whole image, the width and height for destination image should be flipped:
DestBitmap->Width = SrcBitmap->Height;
DestBitmap->Height = SrcBitmap->Width;
The transform routine was centering the image based on original width/height. We want to adjust x/y position to push the starting point to left/top fo... |
69,550,687 | 69,550,770 | Using recursion in C++ class - Passing its own data member | I am writing a pre-order traversal for Tree class:
class Tree {
public:
...
void preOrder(TreeNode* root)
{
if (root != nullptr)
{
cout << root->key << " ";
preOrder(root->left);
preOrder(root->right);
}
}
private:
TreeNode* root = nullptr;
}
... | Like the error message says, you can't use this in a method parameter. Just define a 0-parameter overload of preOrder() that calls the 1-parameter version.
class Tree {
public:
...
void preOrder()
{
preOrder(root);
}
void preOrder(TreeNode* aRoot)
{
if (aRoot)
{
... |
69,551,486 | 69,553,340 | Problem on finding the number of leave node in a binary tree in C++ using array | I am working on a C++ code to find out the number of leave node in a binary tree using array input
my code is:
int leaf(int data[],int size) {
int result = 0;
for (int i = 0; i <= size; i++) {
if (data[i] == -1)
i++;
if (((data[(2*i)+1] == -1) && (data[(2 * i) +2] == -1)) || ((data[(... | Some issues:
When the for loop variable gets to equal size you will have an out of bounds index-access to data. The loop should exit in that case -- size is an invalid index, so use i < size as loop condition.
Your for loop increments the loop variable with i++; there should be no reason to increment i on top of that... |
69,551,783 | 69,551,885 | Extend from 3 hour slot to N days | I want to set up params.arrival_rate every 3 hours of sim_time. This comprises a day but I would like to extend to N days. So, each time slot of 3 hours (in the code below is in minutes) of this N day, params.arrival_rate takes a value. Any optimal function to do so?
My actual code looks like this:
if(sim_time >= 0... | Assuming you want the same pattern every day, it suffices to take the time modulo 1440 minutes:
int day_time = sim_time % 1440;
int day_no = sim_time / 1440;
Now you can use day_time to get the time in the current day and use that to calculate params.arrival_rate. day_no will contain the day number (starting from 0)... |
69,552,216 | 69,552,376 | A Problem with Recursive Void Lambda Expressions in C++ | I would like to implement recursive void lambda expressions inside a function. I have created the C++ snippet below to illustrate my problem. Lambda is the recursive void lambda expression I would like to build inside Func1. However, when I compile with g++, I run into the following compiler errors:
Lambda_void.cpp: In... | See this question for recursive lamda-functions explanation. You can declare your Lambda as std::function<void(std::vector<int>&)> and capture it inside lambda:
std::function<void(std::vector<int>&)> Lambda;
Lambda = [&Lambda](std::vector<int>& A) {
while (A.size() < 5) {
A.push_back(1);
Lambda(A);
... |
69,552,348 | 69,552,582 | Understanding macro code statement with lambda and __attribute__ | My program(C++) is defining a macro for throw statements. It is something like:
#define FOO_THROW(some-exception-type, some-error-message) \
do \
{ \
[&]() __attribute__((cold, noinline)) ... | do...while(0) allows the macro to by called with semicolon at the end, i.e. macro(x,y,z); (note the semicolon at the end), that's an old trick back from C, you can look it up separately.
As for the rest... it defines a lambda (immediate function object) capturing everything by reference (not sure why) that throws excep... |
69,552,467 | 69,704,068 | clang format: break before braces, empty line after opening brace and empty line before closing brace | I'm trying to format classes inside namespaces in the following way (BreakBeforeBraces: Allman):
namespace test_a::test_b
{
struct A
{
int a;
int b;
};
} // namespace test_a::test_b
but clang format keeps changing it to
namespace test_a::test_b
{
struct A
{
int a;
int b;
};
} // namespace test_a::... | clang format can't do that specifically for namespace for the moment, but you can use KeepEmptyLinesAtTheStartOfBlocks to put empty line for all blocks. what if you use BreakBeforeBraces: Custom ?
|
69,552,769 | 69,554,437 | C++: Alternative to the CHtmlVIew to show PDF/HTML files in MFC based application | Are the any alternatives how to display PDF/HTML file in the MFC based application without using ActiveX elements like CHtmlView?
Thanks in advance.
| The alternative would be WebView2. It uses the Microsoft Edge (Chromium) browser engine, unlike CHtmlView that's based on IE.
If the reason you are looking for an alternative is, that you need a more up-to-date browser implementation, then WebView2 delivers. If, on the other hand, you are looking for an alternative, th... |
69,552,907 | 69,553,029 | C++ passing data from object of class A to object of derived class B | For the sample code below, I'm trying to pass (or attribute, if that suits you better) the data from object of class A to the object of derived class B. What I don't understand so far, is how do I transfer the data from the parent class object, to the derived class object.
The "code" below expresses how I've tried to d... | Minimal changes to make your code compile is using Foos copy constructor and simply access the inherited members in Bar::printData:
#include <string>
#include <iostream>
class Foo{
protected:
std::string Name, Surname;
public:
void readData()
{
std::cin >> Name >> Surname;
}
};
class Bar : public Foo
{
pub... |
69,553,402 | 69,553,448 | C++: Return the iterator pointing to element equally to the target | I want to find out the iterator pointing to an element equal to the target.
The following code does not work for me, what's wrong with this code?
#include <iostream>
#include <vector>
template <typename T>
typename std::vector<T>::iterator find_it(std::vector<T> vec, const int target){
std::vector<T>::iterator it ... | vec is passed by-value, it'll be destroyed when find_it returns, the returned iterator to it is dangling, dereference on the iterator leads to UB.
You can change it to pass-by-reference.
template <typename T>
typename std::vector<T>::iterator find_it(std::vector<T>& vec, const int target){
typename std::vector<T>::... |
69,553,581 | 69,554,328 | Does calling std::terminate violate noexcept? | Suppose I have a function which may call std::terminate:
int my_fun(int i) noexcept {
if(i==0) std::terminate();
return 3/i;
}
Am I allowed to declare this noexcept? Nothing is 'thrown' as far as I can tell...
| You are correct and can safely define your function noexcept.
The function std::terminate itself is noexcept and does not throw anything. It just terminates your program, and your program will never reach the return statement or reach the end of the function scope.
As the behaviour of std::terminate() can be overridden... |
69,553,669 | 69,553,863 | New operator followed by address? | What is the following code doing?
int a;
int *b;
b = new (&a) int(5);
is it equivalent to:
int a;
int *b;
a = 5;
b = new int(a);
?
| They are NOT equivalent. The second one allocates memory and constructs an object of the given type in that memory, then returns the address of that memory. In your example, that address is stored in b.
The first variant is called placement new and assumes that storage has already been allocated at the address pointed ... |
69,553,909 | 69,557,069 | How can I get z position of hector_quadrotor in ROS? | I am trying to get z position of hector_quadrotor in simulation. I can get X and Y axis coordinates but I couldn't get Z coordinate. I tried to get it by using GPS but the values are not correct. So I want to get Z coordinate by using barometer or another sensor.
Here the a part of pose_estimation_node.cpp (You can fin... | To use a barometer you need to actually add that sensor to your robot. What you're looking at is only the callback meaning such messages are supported. If you want to add a new sensor to your robot I'd suggest looking at this tutorial.
All that being said, if you're getting incorrect altitude values you need to go back... |
69,554,555 | 69,554,697 | Storing value in 2d array variable during runtime in c++ | My main code is .ino file for STM32F103C8T6 with STM32 official core. I have also included my library files of .h file and .cpp file.
I want store a values in 2d array called uint32_t Page[15][14]; in .h file of my library
How to store a value in 2d array variable during runtime. I have posted my code below. For me the... | When calling HATRIX::HatriX_Signal(...), you pass a copy of a uint32_t of the multidimensional array Hatrix.Page to the function.
Inside the HATRIX::HatriX_Signal(...) function, you assign a new value to this variable called Page. But since it's just a copy of the value from the array, the array itself won't be effecte... |
69,554,728 | 69,561,620 | Can multiple readers synchronize with the same writers with acquire/release ordering? | After reading "Concurrency in action" I could not find an answer to one question - are there guarantees in the standard for reading side effects when we have one store(release) and many loads(acquire) on one atomic variable?
Suppose we have:
int i{};
atomic<bool> b{};
void writer(){
i=42;
b.store(true,memory_order_r... | This is a text-book example of a happens-before relationship between the store to i in writer and the load from i in both reader threads.
That multiple readers are involved does not matter. The store to b synchronizes with all readers that observe the updated value (which will eventually happen thanks to the loop).
I t... |
69,555,386 | 69,559,276 | boost odeint gives very different values from Python3 scipy | I am trying to integrate a very simple ODE using boost odeint.
For some cases, the values are the same (or very similar) to Python's scipy odeint function.
But for other initial conditions, the values are vastly different.
The function is: d(uhat) / dt = - alpha^2 * kappa^2 * uhat
where alpha is 1.0, and kappa is a co... | With boost::odeint you should use the integrate... interface functions.
What happens in your code using do_step is that you use the dopri5 method as a fixed-step method with your provided step size. In connection with the large coefficient L=kappa^2 of about 800, the product L*dt=80 is far outside the stability region ... |
69,555,532 | 69,629,288 | CMake specifying Native Build System Options in CMakeLists.txt(managed C++ Project) | i got stuck with a problem which has to do with a managed c++ Project.
Currently we have a working Build and we are about to use CMake to generate our Solution Files in the future.
In our solution we have some Managed C++ Project and C# Projects. I tried to generate/build the Managed C++ Projects and it works. But ther... | I finally came to a pretty Solution which was there initially.
This post helped my to get on the right Track:
How can cmake add custom entry in a project's vcxproj PropertyGroup?
Basically I don't need to iterate over the .xml File myself to edit the Tag.
I can tell CMake to set it for me as a global option with:
set_t... |
69,555,967 | 69,556,475 | This is explanation on recursion tracing and i can't understand some logic in it. Please help me with the logic |
The function written in this pic is for explaining recursion. It says that the function takes T(n) time to run but it contains a recursive call and then it takes T(n-1) time to run. But we know that function takes T(n) time and same function call is taken then it should again take T(n) time because function is doing s... | The image is this
void Test(int n) {
if (n > 0) {
printf("%d",n); // 1
Test(n-1); // T(n-1)
}
}
// T(n) = T(n-1) + 1
By definition T(n) is the time taken by Test(n). Also T(n-1) is just a label for "time taken to call Test(n-1)".
As the function only calls printf which is con... |
69,556,320 | 69,556,443 | no return statement in function returning non-void while using C++ | I am trying to understand the C++(GCC compiler) expectation of return statement in a non-void function.
For example, running this piece of code is working fine:
int foo()
{
throw "blah";
}
While, on the other hand, if we try to use/call some function to complete the throw, it is facing the well known error/warni... | The compiler isn't going to go to very much trouble to detect this situation, because functions like throw_blah which are guaranteed to never return are rare, and because except in the simplest of situations, there's no way for it to reliably do so. If you have a function like throw_blah which is defined to never retur... |
69,556,427 | 69,556,548 | new bool** matrix vs new bool*matrix vs new bool matrix different types of cpp initialization confusion? | So,far after doing my own research i know bool** matrix will create 2d array,bool* matrix will create 1d array. Now,when implementing graphs using adjacency matrix
private:
bool** adjMatrix;
int numVertices;
public:
Graph(int numVertices) {
this->numVertices = numVertices;
adjMatrix = new bool*[numVe... | new bool*[numVertices] allocates and constructs an array of bool* (pointer to bool) of length numVertices. new bool[numVertices] allocates and constructs an array of bool of length numVertices.
What your code is doing is:
Declaring adjMatrix as a pointer to a pointer to bool
Setting adjMatrix to point to the first ele... |
69,556,488 | 69,558,565 | Reference implementation of vrecpeq_f32 intrinsic? | There is vrecpeq_f32 ARM NEON Intrinsic.
The official explanation for vrecpeq_f32: https://developer.arm.com/architectures/instruction-sets/intrinsics/#f:@navigationhierarchiessimdisa=[Neon]&q=vrecpeq_f32 .
Floating-point Reciprocal Estimate. This instruction finds an approximate reciprocal estimate for each vector el... | The ARM documention provides pseudocode detailing the exact algorithm being performed. Look for FPRecipEstimate which uses fixed-point RecipEstimate.
That may look like a lot of code, but a big chunk of it is there to handle various edge cases, operation modes, and element sizes.
Just wondering if we can write a refer... |
69,556,967 | 69,559,711 | converting data to struct hostent from getaddrinfo() | I am replacing old code to linux. I was using:
server_host = getipnodebyname(host.c_str(), AF_INET, 0, &err_num);
and
server_host = getipnodebyaddr(addr, sizeof(INET_ADDRSTRLEN), AF_INET, &err_num);
that it has to be replaced by the new getaddrinfo().
At moment I added:
struct addrinfo *p_addr = (struct addrinfo *) N... | There is no C library function to convert an addrinfo into a hostent. You will have to construct the hostent yourself using the data from the addrinfo, eg:
#include <vector>
addrinfo hints = {0};
hints.ai_family = AF_INET;
hints.ai_flags = AI_CANONNAME;
addrinfo *p_addrs = NULL;
int result = getaddrinfo(host.c_str(... |
69,557,155 | 69,557,393 | x86 Memory Alignment of struct vs. cache line? | Rcently I'm working on a "searching system" and something about memory/cache performance confuse me.
assume my machine info : x86 arch(L1-3 cache, 64 bytes cache line), linux OS
CPU reads 64 bytes(cache line) each time, so does CPU read data from memory address(to cache) always 64 multiple? For example 0x00(to 0x3F), 0... | I think the part you might be missing is the alignment requirement that the compiler imposes for various types.
Integer types are generally aligned to a multiple of their own size (e.g. a 64-bit integer will be aligned to 8 bytes); so-called "natural alignment". This is not a strict architectural requirement of x86; u... |
69,557,872 | 69,558,014 | std::span as a base class for std::vector | I'm currently developing a custom C++ container library that is similar to std::vector, but I also want to have features of std::span baked in. In particular, I want to be able to write functions that take in a std::span-like parameter, and also work with a std::vector-like argument.
What I can do is to construct a cla... | The LSP states that a reference or pointer to a derived class should obey all of the invariants of a reference to a base class.
This has to be every operation. This is harder than you think.
Replacing a span's referenced buffer is a perfectly cromulant span operation. Doing so to the span parent component of a derive... |
69,558,232 | 69,578,851 | Using Assert() in a C++ test project for "test project" bugs? | Is it appropriate to use the Assert() function in a Visual Studio C++ test project for bugs WITHIN the test project? The Visual Studio test projects for C++ use
namespace Microsoft::VisualStudio::CppUnitTestFramework
For instance, I have a function that builds a vector full of random char value strings, how should I ha... | I would not reccommend using any form of assertions in tests. The rationale is as follows. Assertion is a diagnostic code that is normally executed in "Debug" mode and skipped in "Release". You don't intend to run tests in two different modes, do you? And you are not going to test tests. Verification of the condition ... |
69,558,269 | 69,558,419 | How would C++ hardware destructive & constructive interference size work with the mandated declaration order? | For reference, the interference size is part of C++17, P0154R1, and mandated declaration order is proposed for C++23, P1847R4.
As far as I understand...
The first proposal requires the compiler to move alignas-ed member variables closer together / farther away.
The second proposal would require the compiler to lay ou... | P0154 makes no changes to how member variables are laid out. It merely exposes some constexpr variables, which you can use to adjust the alignment of member variables through alignas. But alignas doesn't gain any special properties.
That is, these two structs have the same layout, if hardware_destructive_interference_s... |
69,558,438 | 69,558,801 | setw and accentuated characters | I want to display a "pretty" list of countries and their ISO currency codes on C++.
The issue is that my data is in French and it has accentuated characters. That means that Algeria, actually is written "Algérie" and Sweden becomes "Suède".
map<string, string> currencies; /* ISO code for currency and country name: CAD/... |
Convert to using std::wstring instead of std::string
Convert to using wide string constants (L"stuff" vs "stuff")
Convert to using std::wcout instead of std::cout
Use setlocale to set a UTF-8 locale
Use wcout.imbue to configure wcout for a UTF-8 locale
Example:
#include <map>
#include <string>
#include <iostream>
#in... |
69,558,521 | 69,558,592 | Friend Function name undefined | I tried to pass a friend function name comp to set_intersection, compiled in Visual Studio 2019 with a compilation error: E0020 identifier "comp" is undefined
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Test {
friend bool comp(const Test& A, const Test& B) { return A.a ... | comp is not visible for lookup here. For friend declaration,
A name first declared in a friend declaration within a class or class template X becomes a member of the innermost enclosing namespace of X, but is not visible for lookup (except argument-dependent lookup that considers X) unless a matching declaration at th... |
69,558,602 | 69,558,690 | reference to function is ambiguous in c++ | Below is my c++ code. When I am compiling the below code in c++17, I am getting an error like this "reference to ‘greater’ is ambiguous. Can someone help me on this
#include <iostream>
using namespace std;
void greater(int num1, int num2, int num3);
int main()
{
int a, b, c;
cout<<"Enter three numbers"<<endl;
cin>>... | I would only add using namespace std; if your code is small or for one-off cases. Generally not good practice since in this case, the C++ standard library includes std::greater(). Thus when you are declaring your own version and add using namespace std;, the compiler doesn't know which to use.
Here's a simple way to fi... |
69,559,589 | 69,559,746 | Zeroing-Out multiple arrays with a single memset/assuming memory layout allowed? | Looking at the source-code of the Arduino-Ethernet-Library I found this:
class DhcpClass {
private:
...
#ifdef __arm__
uint8_t _dhcpLocalIp[4] __attribute__((aligned(4)));
uint8_t _dhcpSubnetMask[4] __attribute__((aligned(4)));
uint8_t _dhcpGatewayIp[4] __attribute__((aligned(4)));
... | The performance improvement is not significant, although in an arduino environment,
you may be fighting to reduce every byte of generated code (more than execution speed).
As listed, the code is a bad idea, although it will "probably" work OK, that's usually not good enough.
For this case, you could do something like t... |
69,559,867 | 69,657,950 | GCC > 7 on Ubuntu 18.04, expected to work? | I want to understand what's happening under the hood when using a newer GCC than the "default" version for a given version of Ubuntu.
Starting with a plain Ubuntu 18.04, I have:
/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.25
Then I install gcc-11 (via the toolchains/test ppa repo) and I get:
/usr/lib/gcc/x86_64-lin... | After all the great info I got from the comments, I think I got a good enough understanding to answer the question. Thanks everyone!
If the libstdc++ has the same major version (the one in the SONAME), then they are backwards-compatible. Meaning that something built on a older libstdc++ is guaranteed to run on a newer... |
69,560,080 | 69,560,495 | C++ MATLAB Engine won't output to console | I am following the matlab example for using matlab in c++ from:
https://uk.mathworks.com/help/matlab/matlab_external/build-c-engine-programs.html
https://uk.mathworks.com/help/matlab/matlab_external/test-your-build-environment.html
and I compile and run it without issue, except that it won't print anything.
I'm using w... | The issue was finding the dlls, adding the path to the matlab bin to my path fixed this issue
|
69,560,280 | 69,560,326 | how to check if unique_ptr points to this | In following peace of code, I'm trying to find another object that has the same coordinates as this. How to do it correctly?
auto& organism_vector = world->get_vector();
auto attacked_organism = find_if(begin(organism_vector), end(organism_vector), [this](const unique_ptr<Organism>& attacked_organism)
... | Change *this != *attacked_organism to this != attacked_organism.get():
auto& organism_vector = world->get_vector();
auto attacked_organism = find_if(begin(organism_vector), end(organism_vector),
[this](const unique_ptr<Organism>& attacked_organism)
{
return this->get_coordinates() == attacked_organism->... |
69,560,690 | 69,560,733 | Efficient way to get a reversed copy of std::string | Dealing with algorithmic tasks I frequently need to get a copy of reversed std::string. Also, the source string should not be modified. As far as I concerned, there are two ways to do it:
Use std::reverse :
// std::string sourceString has been initialized before.
std::string reversedString = sourceString;
std::revers... |
My question is which approach I should prefer according to efficiency
The one which should be preferred according to efficiency is the one that has been measured to be more efficient. Both have the same asymptotic complexity.
But, I won't bother to measure the difference unless it happens to be a bottleneck. I prefer... |
69,561,153 | 69,561,406 | smooth out corners of a 3-point line strip | I have a line strip defined by 3 points, each having an x and y coordinate.
I'm trying to smooth out the middle (point 2) corner as shown in the picture below:
the gray line is the original line strip and the black one is the smoothed-out one.
The smoothed out area should be constant across multiple values (as in it i... | Pick 2 points on each line that are the same distance to the corner. On those points draw two lines at right angles to the lines you already have (normal vectors pointing bottom left). They will cross at a point which will be the center of a circle, part this circle will then be the smoothed corner.
|
69,561,483 | 69,561,565 | getter setter c++ not as expected | i want to ask about getters/setters. i have 2 classes besides 'main'. I get an error when accessing a variable from a different class.
this is my code
#include <iostream>
using namespace std;
class Employee {
private:
// Private attribute
int salary;
public:
// Setter
void setSalary(int s) {
... | In main function you have one instance of Employee to which you set a salary of 50000.
In boss.tes() function, you have a different instance of Employee, which doesn't have any value in salary member, that is the reason you get a "garbage" value when printing 'boss ask salary'.
I don't know what should be the logic in ... |
69,561,534 | 69,561,853 | How to always have N number of lines in a ofstream file with real-time data | I'd like to write lines to a file using ofstream, 10 times, and I want the 11th line to be written in the 1st line's place, 12th in 2nd, and so on (so that my file would always have 10 lines, to preserve log file size).
So far my best try involves a circular buffer, shown below:
#include <cstdio>
#include <iostream>
#i... | You can sort-of get the behavior you want by doing a
myfileo.seekp(0, std::ios_base::beg);
... every time you've just finished writing out the tenth line of text. That will move the file's write-position back to the top of the file, and from there on you'll be overwriting existing contents of the file instead of mak... |
69,562,141 | 69,562,415 | If char and int differ only in the number of bits, why are they different when printing? | In Difference between char and int when declaring character, the accepted answer says that the difference is the size in bits. Although, MicroVirus answer says:
it plays the role of a character in a string, certainly historically. When seen like this, the value of a char maps to a specified character, for instance via... | A char may be treated as containing a numeric value and when a char is treated such it indeed differs from an int by its size -- it is smaller, typically a byte.
However, int and char are still different types and since C++ is a statically typed language, types matter. A variable's type can affect the behavior of progr... |
69,562,408 | 69,563,361 | Trying to press a button and toggle an LED flash at 2Hz until i press the button again | i'm trying to learn coding and this has really stumped me so i thought i would ask you lovely people.
basically i'm trying to press a button and have an LED toggle on that is flashing on and off twice in a second, this will be continuous until i press the button again that will turn it off.
here is my code so far.
bool... | Because of the calls to delay(1000), your code requires you to press the button in the exact split-second instant when digitalRead(1) is called. The Arduino cannot listen for button presses while delay() is in action. Also, you call delay(1000) twice, which flashes the LED on and off once in two seconds, not twice in o... |
69,563,038 | 69,563,310 | error: no match for 'operator+=' (operand types are 'long double' and 'std::__cxx11::basic_string<char>') | I need to read values from a tuple that could be any datatype and then add them if they are numbers, or concatenate them if they are castable as strings.
tuple<int32_t, bool, string, float, const char*, char, int> t{10, true, "Modern", 2.3f, "C++", 'e', 13}; // Example Tuple
So I thought a template would be the way to... | You can use the C++17' is new compile-time conditional if constexpr. It will compile only the chunk that you need and discard the rest.
if constexpr (std::is_convertible<T*, std::string>::value){
stringConcatenation += tupleValue;
}
// Check for strings and char pointers
else if constexpr (std::is_convertible<T, st... |
69,563,354 | 69,591,716 | How can you use std::setw() with array output? | I am making a blackjack game in C++, and I am trying to print out the players and dealers cards in addition to their sums, capital and so on. However I'm running into an issue with std::setw() when printing out the vector of cards. Here is a code snippet:
int width = 18;
std::cout << std::left << std::setw(widt... | I have found a solution. You can use stringstream to add int values to a string with no errors in conversion, this is how I fixed my code:
#include <sstream>
std::stringstream playerCards{};
for (int i{}; i < player.cards.size(); i++) {
playerCards << player.cards[i] << " ";
}
int width = 18;
std::cout << std::le... |
69,563,394 | 69,563,740 | Converting string back to byte array C++ | So I have a string that contains a byte array of HEX values.
I am trying to figure out how to go from the string back to the original byte array.
I am using an Arduino-based board.
Simply put, I want to turn this:
char addr3[47] = "0x28, 0xB6, 0x4C, 0x4E, 0x0D, 0x00, 0x00, 0x86";
Back into this:
byte addr2[8] = {0x28, ... | To accomplish this you need to parse the string and convert the individual values to byte. You can do this using the sscanf function in the c library. I don't know if the arduino has an implementation of the sscanf function. But I would look into that first. If it does not then you will have to write a function that re... |
69,563,480 | 69,563,508 | Issues cleaning a string only to include alphabet characters | I'm having some issues with a part of a C++ program I'm writing to encode and decode a Playfair cipher. The part of the program I'm having issues with is the first step (unfortunate, I know), which involves removing all whitespace, punctuation, and non-alphabet characters. This is what I have:
std::string step1(std::st... | std::remove/_if() does not actually remove anything, it just moves matching items to the end of the container, and then returns an iterator to the beginning of that range of items. The caller can then use that iterator to actually remove the items from the container.
You are passing that iterator to the overload of st... |
69,563,813 | 69,563,902 | convert std::array of bytes to hex std::string | I'd like a way to take an arbitrary-size array of bytes and return a hex string. Specifically for logging packets sent over the net, but I use the equivalent function that takes a std::vector a lot. Something like this, probably a template?
std::string hex_str(const std::array<uint8_t,???> array);
I've searched but the... | If you know the size of the std::array at compile time you can use a non type template parameter.
template<std::size_t N>
std::string hex_str( const std::array<std::uint8_t, N>& buffer )
{ /* Implementation */ }
int main( )
{
// Usage.
std::array<std::uint8_t, 5> bytes = { 1, 2, 3, 4, 5 };
const auto va... |
69,564,388 | 69,628,345 | OpenCV C++ absdiff() unhandled exception | I tried finding the frame difference between a still image and a frame taken from my webcam, using absdiff(). My code is as follows:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/objdetect.hpp>
#include <iostream>
using namespace std;
using nam... | I figured out the solution to this problem. In short, it was only a small resolution issue, which could be fixed by matching the resolution of img with web.
Here are the two lines of code that seemed to resolve the issue if anyone is interested :D
int resx = 500, resy = 500; // 500x400 resolution
resize(img, img, { res... |
69,565,123 | 69,565,224 | How to use std::invoke_result_t in c++17 or 20 instead of std::result_of_t in c++14? | when I use std::result_of_t in c++14 it's doing as i wish:
void just_simple()
{
std::cout << "【4】: in func return nothing. " << std::endl;
}
template<typename Callback, typename... Args>
auto InTemplate_Call(Callback&& bc, Args&&... args)
{
typedef typename std::result_of_t<std::decay_t<Callback>(std::decay_t<... | The difference between invoke_result and result_of is that the former accepts the callable type and arguments type, but your std::decay_t<Callback>(std::decay_t<Args>...) is just a function type that returns a std::decay_t<Callback>.
The following shows the differences:
#include <functional>
void just_simple() {}
tem... |
69,565,125 | 69,566,163 | Does std::lock_guard release the mutex after constructed with std::adopt_lock option? | I know my question is quite similar to this Why does std::lock_guard release the lock after using std::adopt_lock?, but the behavior I see is not. Here is my code:
#include <mutex>
#include <iostream>
using namespace std;
std::mutex m;
void fun2();
void fun1() {
cout << "fun1" << endl;
std::unique_lock<std::mu... | When you constructed a std::unique_lock to manage the mutex, you should stick to it unless you first break the association of the std::unique_lock with the mutex using std::unique_lock::release. In your sample, you touched the raw mutex when it's still managed by a std::unique_lock and this is wrong.
|
69,565,333 | 69,566,130 | Are there overflow check math functions for MSVC? | While looking for functions that do overflow checks on signed and unsigned integer arithmetics, I came across this answer, which presents nice compiler intrinsics to do checked math in GCC. Since the code I'm currently writing needs to be cross-platform, I need something similar for the MSVC (Microsoft Visual Studio) c... | For unsigned addition and subtraction, MSVC has _addcarry_u16/32/64 and _subborrow_u16/32/64, all defined in <intrin.h>. They seem to produce optimal code, including generating add and sub instead of adc and sbb if you pass constant 0 for the carry in.
Unfortunately, there are no analogous intrinsics that return the ov... |
69,565,521 | 69,565,650 | How to format a string according to the formatting method entered by user in c++? | How to format a string according to the formatting method entered by user in c++?
For example, here is an integer:
int x = 100;
If a user inputs a formatting method (a string):
"%x",
I want to output: 0x40.
And another user inputs a formatting string:
%.4f,
I want it output:100.0000.
How to do it?
| I see the following two concepts:
1.
read in the formatting string from the user
reject anything with more than one format specifier
reject anything with wrong format specifier for the type of the variable you want to output (using a float specifier for an integer for example would be wrong; just mentioning it specifi... |
69,566,191 | 69,566,423 | std::any_cast throws a bad any_cast error when converting void* to function pointer | I wrote the code below,
std::unordered_map<std::string_view, std::any> symbols_;
symbols_["foo"] = dlsym(handle_), "foo");
When i use any_cast
return (std::any_cast<void(*)()>(symbols_["foo"]))();, the program will throw a error: bad any_cast.
I found the main reason because of the function .
template<typename _Tp>
vo... | Here you store a void* in the std::any object:
symbols_["foo"] = dlsym(handle_, "foo");
To instead store a void(*)(), you need to cast the void* that's returned by dlsym:
symbols_["foo"] = reinterpret_cast<void(*)()>(dlsym(handle_, "foo"));
In this case, you may want to just store the void* and cast when using it in... |
69,567,240 | 69,567,431 | changing list of character to list int in C++ | i try to change from string to list of char, than list of char change to list int. here is my code
int main() {
std::string int1 = "1122334455";
std::list<char> listChars(int1.begin(), int1.end());
std::list<int> intList(listChars.begin(), listChars.end());
for(const auto& elem: intList){
std::c... | Yes, the output is correct because you had declared a string i.e, std::string int1 = "1122334455"; and then you are trying to print it as integer then the compiler will automatically typecast it according to the ASCII value of all characters of the string.
ASCII value of "0" is 48
ASCII value of "1" is 49
ASCII value o... |
69,567,284 | 69,583,215 | ESP32 Firebase: authenticating results in error code 400 - but Firebase does recognize my login | I am trying to authenticate using signIn() method and exact replica of example code from ESP32 Client library (the new version)
When I run my code I successfully connect to WiFi and also I can
successfully CREATE new account from the ESP32 board.
I need to know if my log in or registration was successful
In my Firebas... |
The problem was that I was checking for the
Firebase.authenticated() method too early, and the Firebase did not
have time to authenticate.
If I check it in the main loop() it works.
GitHub discussion where we find the solution.
|
69,567,383 | 69,567,572 | Is using a reference to a derived class member in its base class well defined in C++? | I was looking into some code and it seemed to work but I am not sure if it is defined behavior.
I think there is a problem in it because Base is constructed with a reference to a Derived member variable - which is in my understanding constructed after Base.
I did some research on this and all I found were answers stati... |
Is using a reference to a derived class member in its base class well defined in C++?
Yes.
SomeClass m_derObj(123);
This is invalid syntax. If you intended to write a default member initialiser, you must use either curly braces or equals initialiser.
Base(SomeClass & obj): m_obj(obj)
{
// Does using m_obj her... |
69,567,737 | 69,568,382 | Max capacity for FBString? | For FBString, max_size() simply returns std::numeric_limits<size_type>::max(). However, the higher two bits of capacity_ in struct MediumLarge is used to denotes the type of FBString(small/medium/large), which means the max of capacity_ will be 2^62-1(64-bit processor), it's less than the max value of size_t. Do I misu... | Since the documentation for folly::FBString claims to be:
100% compatible with std::string
it actually seems to be a bug (in my opinion).
BTW, for large strings, FBString applies copy-on-write (COW), which also breaks the compatibility with std::string (since C++11).
See Legality of COW std::string implementation in ... |
69,567,916 | 69,568,029 | How to split a vector into three variables in C++ | In Python the following expression splits the list a into the three variables x,y,z:
a = [2,5,7]
(x,y,z) = a
Is there anything similar in C++? I've tried writing the following code but it does not works:
#include <iostream>
int main() {
int a[] = {3, 5, 7};
int x,y,z;
(x,y,z) = a;
}
Compiler fails with the... | You can use structured bindings starting from C++17, like so:
std::tuple<int, int, int> a{ 1, 2, 3 };
auto [x, y, z] = a;
See: https://en.cppreference.com/w/cpp/language/structured_binding
Pre-C++17 you can use std::tie, like so:
std::tuple<int, int, int> a{ 1, 2, 3 };
int x, y, z;
std::tie(x, y, z) = a;
See http... |
69,568,299 | 69,568,440 | Divide integer in array and store it as double in array | for(int i = 0; i < iData; i++)
{
if(hPred[i]<=jData[i])
{
akur[i] = hPred[i] / jData[i];
}
else if(hPred[i]>jData[i])
{
akur[i] = hPred[i] / jData[i];
akur[i] = akur[i] - 1.000;
}
}
I got some issues here. I wanted to divide data in hPred[] with jData[] and store it in a... | for(int i = 0; i < iData; i++){
if(hPred[i]<=jData[i]){
akur[i] = (float)hPred[i] / jData[i];
}else if(hPred[i]>jData[i]){
akur[i] = (float)hPred[i] / jData[i];
akur[i] = akur[i] - 1.000;
}
}
typecast any operand to float before division
|
69,568,387 | 69,612,488 | Generate protobuf files for a library target in CMAKE | In the following project structure:
root/
├─ CMakeLists.txt
├─ protocol/
│ ├─ msg.proto
│ ├─ CMakeLists.txt
├─ app/
│ ├─ main.cpp
│ ├─ CMakeLists.txt
I could generate the protobuf files. However, once the app target is added into the project, the configuration step fails, because the protobuf files are not genera... | Based on help from @Tsyvarev:
After moving ${LIB_HEADERS} from PUBLIC to PRIVATE, the protobuf files are now generated.
To make them reachable through the library for the include
#include "protocol/msg.pb.h"
${CMAKE_BINARY_DIR} Needs to be changed into ${CMAKE_CURRENT_BINARY_DIR} in target_include_directories.
In case... |
69,568,397 | 69,569,941 | Encoded Sound loses data when encoding Opus | I'm trying to encode with Opus some data recorded via PortAudio, so whenever I try to encode data, the written data is lost because the unsigned char vector ends up being empty for every iteration of the vector, the original data is recorded from PortAudio
here are my structures :
typedef struct {
int size;
std... | It looks like the problem is that you're keeping two sizes. You're mixing C and C++ style, which probably explains the std::vector<unsigned char> *. But more importantly, std::vector<unsigned char> stores its own size, yet you also store a seprate size. And it looks like they don't agree.
The fix is easy. Don't store t... |
69,571,287 | 69,571,466 | Can I exclude a number or subrange of numbers inside a range of random numbers in modern C++? | I have:
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> probability(0, 100);
I want to exclude some numbers in this range of probabilities.
Example 1: Let's say, I want to generate a random number between 0 and 100, but this number can never be 4.
Example 2: Let's say, I want to genera... | If you want to stay with a uniform_int_distribution you can do it manually like this:
Example1: Let's say, I want to generate a random number in between 0 and 100, but this number can never be 4.
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> distribution(0,99);
auto temp = distribut... |
69,571,550 | 69,571,855 | Qt UDpsocket working on same computer but not on two computers on same network | I am able to send and receive to two different programs running on same computer. But not able to do the same when running them on different computers. Both computers are on same Local area network. I am working on windows 10.
#include "communicationmanager.h"
communicationManager::communicationManager(int portNumber,... | You need to bind to QHostAddress::Any in order to actually receive packets from outside the local machine. QHostAddress::LocalHost will only receive traffic from the same physical machine.
|
69,571,825 | 69,633,602 | Reflecting LuaBridge classes from Lua scripts | Before April 2019, it was possible for a Lua script to reflect the methods and properties of a LuaBridge class using string keys __parent, __class, __propget, and __propset. This was an incredibly useful tool for creating test scripts and development tools to maintain a large class framework exported into Lua.
From loo... | Since no one seems to have a good suggestion, I realized I could roll my own reflection of the names of properties, methods, and constants. For my purposes I don't really need to execute or access them.
So rather than muck around inside LuaBridge I added __class, __propget, and __propset static properties to every clas... |
69,571,947 | 69,575,486 | What does it mean that data is prepared in the function of mosquitto_want_write()? | According to the API, the mosquitto_want_write() function returns TRUE when data to be used in the socket is prepared.
But what does it mean to have data ready? Where is the data being prepared? What function call can prepare the data?
Is the data prepared by the call Mosquito_publish()?
Unfortunately, I couldn't f... | Look no further than the definition of mosquitto_want_write:
bool mosquitto_want_write(struct mosquitto *mosq) {
bool result = false;
if(mosq->out_packet || mosq->current_out_packet){
result = true;
}
return result;
}
A call to mosquitto_publish eventually ends up in send__publish, which calls ... |
69,571,993 | 69,572,058 | Issue while extracting tuple element type in variadic tuple | I'm trying to write generic function that iterates through std::tuple elements. In doing so, i need to extract the element type of the given tuple element that is being processed. However, i'm running into an issue regarding type equality between the extracted type and the actual type of the tuple element. The below co... | You're not getting the type of the element of the tuple correctly. They should be
using ValueType = typename std::tuple_element<I, std::tuple<Tp...>>::type;
// ^^^^^^^^ ^^^^^^
static_assert(std::is_same<ValueType, int>::value, "Should be true");
using ValueType2 =... |
69,572,294 | 69,577,892 | why does hotspot jvm use extern "C" in its JNI modules? | Since jvm itself is implemented and built by c++, why does it need to declare extern "C"?
extern "C" is used to generated c-compatible target, why does a c++ jvm need that?
| One nice quality of JNI is that you can compile it once and link it to any JVM for that platform. These days that's less of an issue since pretty much all JVMs are based on OpenJDK, but once upon a time there were several JVMs that had completely different implementations. My JNI library compiled on Windows could link ... |
69,572,317 | 69,573,088 | Why does boost::basic_array_source give other values than what I have stored with boost::iostreams::back_insert_device? | I am trying to use functions of a library that reads and writes from/to streams. To adapt my data to that library, I wanted to use boost::iostreams from boost 1.77.0. Still, a first very simple example does not work as expected. Why?
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/device/back_inse... | It works correct to me, but not in the intuitive way though. You are putting integers 1 2 and 3 into the vector of chars via stream, so they land there as their ASCII codes, 49, 50 and 51 respectively. In the initial loop you are actually printing characters, not their integer representations, thus. I suggest you shoul... |
69,572,484 | 69,572,542 | If I had already declared the size and initialize the array in this C++ snippet how is this code running? | I am new to C++(please assume no C knowledge while answering).
I have just started learning about arrays and ran the following code :-
#include<iostream>
using namespace std;
int main(){
int arr_[10] ={1,2,3,4,5,6,7,8,9,0};
int i=0;
while (i<4)
{
printf("Value of arr_[ %i ] = %i \n",i ,arr_[i])... | When you try to access the out of bound element of the array then the output is undefined. That is why you are getting different results on different run of the program.
arr_[15] = 555;
cout<<arr_[11]<<endl<<arr_[12]<<endl<<arr_[15];
Both of the above statements produce undefined behavior.
You can read more on this ... |
69,573,120 | 69,573,363 | can you replace enable_if to disable a function it if constexpr? | So I know you can use enable_if to disable a function template (e.g. if the type is not integral) - but can you do the same with constexpr?
i.e. is there an equivalent for this:
template<class T, typename = std::enable_if_t<std::is_integral_v<T>> >
T test2()
{
return {};
}
with constexpr - something like:
template... | It is as simple as this:
template <typename T>
T test()
{
static_assert(std::is_integral_v<T>);
T output{};
return output;
}
|
69,573,327 | 69,603,379 | Qt Creator display in application output: NVD3DREL: GR-805 : DX9 Overlay is DISABLED | As I am working with my project, I noticed that when I run my app, inside the Application Output area I can see message:
NVD3DREL: GR-805 : DX9 Overlay is DISABLED
NVD3DREL: GR-805 : DX9 Overlay is DISABLED
NVD3DREL: GR-805 : DX9 Overlay is DISABLED
I have no idea what it means, but to be honest it has no impact on... | The problem is a problem in the Nvidia Driver 496.13. I had the same problem, and reverting to an older version fixed it
|
69,573,668 | 69,573,809 | dynamic_cast on polymorphic class copy segfaults | The following code snippet causes a segmentation fault during the dynamic_cast. Can anybody explain to me why this happens?
#include <cassert>
#include <cstdint>
uint8_t buffer[32];
class Top {
public:
virtual ~Top() = default;
};
template <typename T>
class Middle : public Top {
public:
void copy() {
... | auto memory{reinterpret_cast<T *>(buffer)};
*memory = *dynamic_cast<T *>(this);
This is incorrect approach, you cannot just interpret some bytes as T. Objects are created only by calling the appropriate constructors which for example initialize the virtual jump table.
The second line is also wrong even in your context... |
69,573,790 | 69,574,137 | How to group CTests together? | I would like to make groups of CTests to improve readability with a structure like this:
How can I do this? My current CMakeLists.txt:
cmake_minimum_required(VERSION 3.20)
project(Test)
set(CMAKE_CXX_STANDARD 14)
enable_testing()
add_executable(env environment.cpp)
add_test(Environment env)
add_subdirectory(unit) # ... | CTest doesn't support this, as it's not a classical unit testing framework, but rather a convenient way to "run stuff" that is already configured (in most cases) to be built with CMake.
What you can do is:
Impose a naming scheme, e.g. prefix tests by a common identifier. For all tests that are registered with add_test... |
69,574,043 | 69,574,434 | NodeJS source code cannot find set_immediate_callback_function definition | I am trying to understand how Node works internally. I am really interested in the check phase but could not make sense of thing how that phase queue is processed. Right now I cannot understand where set_immediate_callback_function is defined. Such method is part of Environment class but I cannot see it.
This methods i... | The set_immediate_callback_function is generated by the preprocessor, by a technique called X-Macros.
Let's break it down. You are referring to this code:
void SetupTimers(const FunctionCallbackInfo<Value>& args) {
CHECK(args[0]->IsFunction());
CHECK(args[1]->IsFunction());
auto env = Environment::GetCurrent(args... |
69,574,129 | 69,574,713 | Problem in assigning of dynamic memory with dereference operator | I don't understand why the second for loop doesn't access my dynamic memory well.
After I exit the loop, the dynamic memory will somehow lose its data, while if I use the "second method" it will be ok.
Could you explain to me why is that?
Here is the code:
#include <iostream>
int main()
{
int* foo;
foo = new (... | After you allocate the array and assign its starting address to foo, you are incrementing foo in the 1st loop to access each int in the array. By the time you get to the second loop, foo is now pointing past the end of the array. That is why your 2nd loop cannot access the values correctly.
Your "second method" does ... |
69,574,143 | 69,574,946 | move semantics in constructor in return statement | I know that when returning a local in order to keep RVO we should allow the compiler to perform move elision by returning a value like so
std::vector<double> some_func(){
std::vector<double> my_vector;
//do something
return my_vector;
}
rather than
std::vector<double> some_func(){
std::vector<double> m... | This one is more efficient:
std::pair<std::vector<double>,std::vector<double> > some_func() {
std::vector<double> my_vec_a;
std::vector<double> my_vec_b;
//do something
return std::make_pair(std::move(my_vec_a),std::move(my_vec_b));
}
without the calls to std::move the two vectors will be copied.
The ... |
69,574,163 | 69,574,594 | c++ change object properties of object that is key in map? | Say I have the following classes:
#include <string>
class Item {
public:
Item(std::string name, int id);
virtual int getWeight() = 0;
protected:
std::string name;
const int id;
}
#include <vector>
#include <memory>
#include "Item.h"
class Bucket : Item {
public:
Bucket(std::string name, std::strin... |
I think the problem is, that as I put a Bucket into a map (Bucket is the key), it becomes const
Correct. Maps are supposed to be ordered, and if you were able to mutate a key, you could break this invariant. Doing this would potentially break every subsequent search or insert horribly.
The linked workaround is effect... |
69,574,308 | 69,574,361 | Friend function for class in dll | Lets say I have the following class in my dll
class Test { private: int x; };
and following function in client side application which uses my dll
void test();
Is there a way to make test function friend for Test class?
|
Is there a way to make test function friend for Test class?
Yes, add a friend declaration to the class definition:
class Test {
private:
int x;
friend void test();
};
|
69,574,909 | 69,575,144 | Declaring an object in a header when its definition is in a different header | I am new to cpp, looking at an existing project.
There are several places in the project where an object is defined in a namespace in some header file and then declared in the same namespace and used in other declarations in some other header file. Example:
MyStruct.hpp:
namespace A { struct MyStruct { int i; }; }
MyC... | What you are seeing is a forward declaration being used.
Since foo() takes a MyStruct by reference, MyClass.hpp doesn't need to know the full declaration of MyStruct in order to declare foo(), it only needs to know that MyStruct exists somewhere. The linker will match them up later.
MyClass.cpp, on the other hand, nee... |
69,575,307 | 69,575,692 | Microsoft C/C++: what is the definition of "strict conformance" w.r.t. implementation? | Context:
/Za, /Ze (Disable Language Extensions):
... the C compiler conforms strictly to the C89/C90 standard
/permissive- (Standards conformance):
... and sets the /Zc compiler options for strict conformance
C++ Conformance improvements, behavior changes, and bug fixes in Visual Studio 2019:
... /permissive may b... | The C11 standard defines a strictly conforming program and implementation in section 4 paragraphs 5-7 as follows:
5 A strictly conforming program shall use only those features of the language and library specified in this
International Standard. It shall not produce output dependent
on any unspecif... |
69,575,497 | 69,575,704 | Is it possible to capture a type template into a template argument? | Is it possible to capture a template from a template argument i.e. have a nested template specifier with a template argument that holds the template type?
template< typename T, typename Label = std::string>
class foo {
// ...
};
template <
template < typename C, typename T > typename C<T>,
... | Yes, you can just use template specialization:
#include <string>
template<typename T, typename Label = std::string>
class foo {};
template <class T, typename Label = std::string>
class bar;
template <template<class...> class C, typename T, typename Label>
class bar<C<T>, Label> {
C<foo<T, Label>> A;
};
Demo.
|
69,575,585 | 69,575,679 | Should I delete variables if created them using "new" operator inside map::insert()? | I am writing scene manager which, among other things, contains a map of all objects, or rather pointers to them. I remember to delete my variables created using "new" and i tried doing it in my Scene deconstructor, but I got 0xC0000005 exit code and afaik it means that i tried to use memory that doesnt really exist any... | So..
As t.niese answered 0xC0000005 exit status in my code came from a difference between creating and deleting methods used.
When using new, you should delete it using delete
When using new[], you should use delete[]
|
69,575,909 | 69,576,105 | How to use lambda intead of std::bind in create_subscription method in ROS2 | I am creating a small euclidean clustering node for the point cloud, utilizing PCL's implementation of the KD tree.
Currently, my subscriber definition looks like this,
ClusteringNode::ClusteringNode(const rclcpp::NodeOptions &options)
: Node("clustering_node", options),
cloud_subscriber_{create_subscript... | The std::bind() statement:
std::bind(&ClusteringNode::callback, this, std::placeholders::_1)
Would translate into a lambda like this:
[this](const auto msg){ callback(msg); }
Or, if the callback() has a non-void return value:
[this](const auto msg){ return callback(msg); }
|
69,575,926 | 69,576,197 | Does compiling with gcc flag -fno-exceptions reduce the size of the executable binary? | While reading the section about exception handling and the compiler flag -fno-exceptions in the gcc manual, I came across the following lines:
Exception handling overhead can be measured in the size of the
executable binary, and varies with the capabilities of the underlying
operating system and specific configuration... | It can reduce the size of the binary, and it often does for larger programs. However, it's not guaranteed to always do so.
a) User code being compiled with -fno-exceptions only prevents using the keywords try, catch and throw and does not generate a smaller binary by itself, right ?
Nope, it definitely has an impact ... |
69,576,022 | 69,578,945 | How to instantiate an Octave classdef object in C++ and call its methods | I know how to call a function defined in an .m-file using the Octave interpreter and feval as shown in the Octave manual but not how to do something similar using Octave classes and their methods.
If I have a simple class defined in Octave using the classdef method such as
classdef TestClass < handle
properties
v... | If you already know how to call an Octave function from C++, then all you are missing is that a.b() is the same as b(a). Calling a method is just like calling a function, there is no distinction. Octave figures out which overload of the function to call based on the input arguments.
The bit of Octave code you posted,
c... |
69,576,225 | 69,576,351 | C++ ostream parameters | I am building a project that solves a boggle board. The two functions I'm interested in at the moment are
void Boggle::SolveBoardHelper(bool printBoard, int row, int column, int rowMax, int columnMax,
ofstream& output, int numSteps, int steps[4][4], string currPath)
void Boggle::SolveBoa... | void Boggle::SolveBoard(bool printBoard, ostream &output) {
// remove the two lines below and just use `output` in the rest of the function:
//ofstream outputFile;
//outputFile(output);
for(int pos_x = 0; pos_x < BOARD_SIZE; pos_x++) {
for(int pos_y = 0; pos_y < BOARD_SIZE; pos_y++)
... |
69,576,398 | 69,578,252 | BindingError: Passing raw pointer to smart pointer is illegal | Consider the following C++ code and corresponding Emscripten bindings.
class IBar {
void qux() = 0;
};
struct BarWrapper : public wrapper<IBar> {
void qux() override {
return call<>("qux");
}
}
EMSCRIPTEN_BINDINGS(IBar) {
class_<IBar>("IBar")
.smart_ptr<std::shared_ptr<IBar>>("IBar")
... | I figured out a solution that doesn't return adding a method that accepts a raw pointer.
It works by expanding the bindings for IBar.
EMSCRIPTEN_BINDINGS(IBar) {
class_<IBar>("IBar")
.smart_ptr<std::shared_ptr<IBar>>("IBar")
.function("qux", &IBar::qux)
.allow_subclass<BarWrapper, std::share... |
69,576,651 | 69,576,896 | Tell compiler not to execute destructor on my __thread variable | I specifically want no constructors and no destructors on one of my variables. It's defined as this
struct Dummy { ~Dummy() { assert(0); } };
__thread Dummy dumb;
The real code is zero initialized and grabs memory out of the thread local memory pool. The pool is destroyed at the end of main so this destructor tries to... | Before I get into the answer, anyone reading this should know that this is generally a very bad idea, and should be treated as a last resort. However, what the OP wants is feasible, so here it is:
Destructors are possibly the single most reliable thing in the C++ language. So if you want to prevent one from being execu... |
69,576,733 | 69,576,812 | Referring to template parameters to define types for function parameter | I would like to do something like this:
template <typename T, int Size>
struct config {
T field;
/* various other things */
}
template <typename C> // where C is a specific version of the 'config' object.
void func(C arg0, C::T arg1, std::array<int, C::Size> &arg2) {
int i = C::Size;
}
ie, can I choose the ty... | You can of course add a type alias/static constexpr to config, but the only way to guarantee the first parameter of the function is instantiation of config, is the second alternative.
A solution using type alias/ static const:
template <class T, int N>
struct config
{
using FieldType = T;
static constexpr int S... |
69,577,145 | 69,577,588 | Reference in container? | I'm having an issue with passing a string as reference to a lambda, when it is in a container. I guess it disappears (goes out of scope) when I call the init() function, but why? And then, why doesn't it disappear when I just pass it as a string reference?
#include <iostream>
#include <string>
struct Foo {
void init... | Part 1: This looks busted at a glance.
"text" is not a string, it's a literal that is being used to create a temporary std::string object, which is then used to initialize the std::pair. So you'd think it would make sense that the string, which is only needed transiently (i.e only until the std::pair is constructed), i... |
69,577,462 | 69,577,527 | Why doesn't constexpr function returning std::string doesn't compile when outside templated class? | Note: I am using gcc, but tested on godbolt.org and it also works on msvc, but not on clang
I accidentally discovered that the following simple function compiles while being in a templated class, but not as a free function. Could someone explain why?
Compiles OK:
template <typename T = void>
class A
{
publi... | std::string is supposed to be a literal type in C++20. However, it seems that GCC hasn't implemented this new feature yet, so it cannot accept std::string as the return type of a constexpr function.
However, when the constexpr function is part of a template, it doesn't exist as a function until it's instantiated. A cla... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.