question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
72,519,241 | 72,519,460 | Static assertion failed error in defining set (STL container) with user defined objects c++17 | I defined a set with data type as user defined object here.
#include<bits/stdc++.h>
using namespace std;
class triplets{
public:
int x,y,z;
triplets(){
}
triplets(int x,int y,int z){
this->x=x;
this->y=y;
this->z=z;
}
};
class Cmp{
public:
Cmp(){};
bool oper... | bool operator() (const triplets &a, const triplets &b){
should be
bool operator() (const triplets &a, const triplets &b) const{
|
72,519,383 | 72,522,923 | Boost Beast Read Conent By Portions | I am trying to understand how can I limit the amount of data that is read from the internet by calling 'read_some' function in boost beast.
The starting point is the incremental read example in the beast's docs.
From the docs I understood that the really read data is stored in the flat_buffer.
I make the following expe... | The operating system's TCP IP stack obviously needs to buffer data, so that's likely where it gets buffered.
The way to test your desired scenario:
Live On Coliru
#include <boost/beast.hpp>
#include <iostream>
#include <thread>
namespace net = boost::asio;
namespace beast = boost::beast;
namespace http = beast::http;
u... |
72,519,493 | 72,519,551 | Forcing string literal argument to cause std::string class template deduction | I would like to write a class template, which is able to hold different types. However, I want to avoid specializations of type char* or char[]. Character strings should always be std::string. The code below is what I have so far. However, writing Scalar("hello") yields T = char[6] and not T = std::string. I could writ... | Deduction guide (c++17) might help:
template <std::size_t N>
Scalar(const char(&)[N]) -> Scalar<std::string>;
Demo.
|
72,520,213 | 72,520,354 | nested lambdas cause compiler to run out of heap | I'm writing some code which passes lambda functions to a suite of recursive functions. Some of these lambda functions are nested inside other lambda functions. I think I'm writing valid code but I'm getting a fatal error C1060: compiler is out of heap space error.
Here is a much cut down version of the code
struct Null... | Per [expr.prim.lambda.closure]
The type of a lambda-expression (which is also the type of the closure object) is a unique, unnamed non-union class type
To instantiate Repetition::match, the compiler must instantiate Null::match which requires an instantiation of Repetition::match... and so on. Each time the compiler ... |
72,521,037 | 72,521,342 | Implementing virtual functions in child's .cpp causes "undefined reference to `vtable for <child's class>`" | I have an interface:
//Card.h
#include "../Players/Player.h"
class Card {
public:
virtual void applyEncounter(Player& player) const = 0;
virtual void printInfo() const = 0;
virtual ~Card() {}
};
And a class that inherits from it
// Barfight.h
// ...
#include "../Players/Player.h"
#include "Card.h"
class... | You are building your project in wrong way.
You've have shown this:
g++ -std=c++11 -Wall -Werror -pedantic-errors -DNDEBUG -g *.cpp -o my_test
What is scary you have a wild card here and your code uses relative paths.
This is straight way to forgot some file, what will lead to linking issue.
Note that wild card is not... |
72,521,471 | 72,521,628 | Strange output when use Pointers in c++ | Considere the following code in c++:
#include <iostream>
using namespace std;
int main() {
int x=2, y;
int *p = &x;
int **q = &p;
std::cout << p << std::endl;
std::cout << q << std::endl;
std::cout << *p << std::endl;
std::cout << x << std::endl;
std::cout << *q << std::endl;
*p =... | The variable y was not initialized
int x=2, y;
So it has an indeterminate value.
As the pointer q points to the pointer p
int **q = &p;
then dereferencing the pointer q you get a reference to the pointer p.
So this assignment statement
*q = &y;
in fact is equivalent to
p = &y;
That is after the assignment the point... |
72,521,499 | 72,529,948 | What is the difference between glPolygonMode GL_LINE and glDrawElements GL_LINE_LOOP mode? | The following code snippets give me exactly the same result:
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glDrawElements(GL_LINE_LOOP, vbo.rows(), GL_UNSIGNED_INT, 0);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDrawElements(GL_LINE_LOOP, vbo.rows(), GL_UNSIGNED_INT, 0);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)... | glPolygonMode change the rasterization mode, but does not change the primitive. The primitive type stays the same and there are still GL_TRIANGLES primitive drawn. glPolygonMode has no effect on other primitives than triangles. GL_LINE_LOOP is a different primitive type. It connects all the vertices to a single line. I... |
72,521,879 | 72,522,947 | How to display text (sf::Text) from a class with SFML? | I'm trying to create a button class, with some text in it.
I encountered an issue with the text inside the button, it simply does not display.
After much trouble debugging my code, I managed to isolate the faulty code portion.
(In examples below, I recreated the issue with a minimal code)
someText.h
class someText{
pr... | You are victim of sf::Text class behaviour:
It is important to note that the sf::Text instance doesn't copy the
font that it uses, it only keeps a reference to it. Thus, a sf::Font
must not be destructed while it is used by a sf::Text (i.e. never
write a function that uses a local sf::Font instance for creating a
text... |
72,521,923 | 72,521,990 | Is it possible to assign address value directly to a pointer? | I'm learning C++ from www.learncpp.com. The tutorials are good and I could ask the author myself by commenting but it takes some time to get a reply. So, here is something I'm confused in lesson 23.7 near the end of the lesson.
A warning about writing pointers to disk
While streaming variables to a file is quite eas... | Yes you can, and in C++ it looks something like:
auto ptr = reinterpret_cast<ptr_type>(0x0012FF7C);
Where ptr_type is a valid pointer type, like int* for example.
To add a bit more clarity to the problem outlined in the lesson:
Memory addresses are constantly being reclaimed and reused as required by the different pr... |
72,521,938 | 72,522,313 | Implementing LRU Cache using doubly linked list and unordered map in c++ | I have implemented LRU cache after watching multiple online sources but am unable to understand why the code outputs value "alpha" for 3 , please suggest how to cure this in the LRU cache implementation . I have checked multiple online sources but all of them are for implementing int to int mapping , here i want to giv... | In feedin replace
if((it.second) == L.end())
with
if((it.second) == --L.end())
and ensure capacity can never be zero. This shouldn't be much of a restriction because there is no point to a LRU cache that can't cache anything.
Explanation:
I believe the mistake is in believing that L.end() returns an iterator referrin... |
72,522,263 | 72,538,581 | Issue with 3d rotation along the X axis | I'm working on a project that required a 3d cube to be rotated along 3 axes. The cube is made up of 12 triangles, each with an instance of the Triangle class. Each triangle has a p0, p1, and p2 with the type sf::Vector3f. The triangles also have a float* position and a float* rotation. The position and rotation of a tr... | bro you did it all wrong. use this 3D point rotation algorithm. i know it is javascript but the math still the same
|
72,522,679 | 72,522,716 | c++ how to overwrite method in subclass | I have some code I'm trying to get to work, I'm open to other suggestions on how to do this. Basically, I have some base class that I want a bunch of subclasses to inherit. I then have a function that needs to call the subclass version of this method.
#include <iostream>
using namespace std;
//my base class
class Bas... | You need to declare the member function in the base class as virtual. For example
virtual void myMethod() const {
std::cout << "Base class?" << std::endl;
}
And in the derived class to override it
void myMethod() const override {
std::cout << "Subclass?" << std::endl;
}
And the function call_method must have... |
72,523,157 | 72,533,955 | Strange/inconsistent behavior with armadillo with `copy_aux_mem` and solving with a triangular matrix | Consider the following C++ code
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
// [[Rcpp::export(rng = false)]]
void possible_bug(arma::vec &x, arma::mat const &sig_chol){
if(x.n_elem != sig_chol.n_rows * sig_chol.n_cols)
throw std::runtime_error("boh");
arma::mat x_mat(x.begin(), sig_chol.n... | This is an intended change in version 11.1.1. See https://gitlab.com/conradsnicta/armadillo-code/-/issues/210#note_974299524
The way to go is to set strict to true in the constructor of arma::mat and other objects.
|
72,523,412 | 72,523,426 | Storing numbers manually into int ** makes some numbers random | c++ | I'm trying to fill an array of int array to create a tilemap for a videogame. However I've used switch case and I tried to fill the map when initializing it but some of the number are random for an unknown reason.
Here's the code:
int **Process::get_story_map(int lvl)
{
int **map = new int *[10];
switch (lvl)
... | {
case (0): {
int line01[10] = {5, 0, 1, 1, 2, 2, 1, 1, 0, 5};
int line02[10] = {0, 0, 1, 1, 2, 2, 1, 1, 0, 0};
int line03[10] = {1, 1, 1, 1, 2, 2, 1, 1, 1, 1};
int line04[10] = {1, 1, 1, 1, 0, 0, 1, 1, 1, 1};
int line05[10] = {2, 2, 1, 0, 0, 0, 0, 1, 2, 2};
int line0... |
72,523,775 | 72,693,638 | C++ Microsoft docs - File handling / Get folder path | I have learned C/C++ Basics and practiced , but I have hard time understanding
Microsoft documentation and find it confusing Documention example
for example : I try to create command line program that should let the user open
folder dialog and choose folder , as result the folders path should be stored in variable
did ... | I used to wcout to print out path
TCHAR path[260];
BROWSEINFO bi = { 0 };
LPITEMIDLIST pidl = SHBrowseForFolder(&bi);
SHGetPathFromIDList(pidl, path);
wcout << path << '\n';
We can use com interface as well :
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow);
{
... |
72,523,818 | 72,524,105 | Unable to Launch Child Process with command line arguments C++ | I am trying to code a program that launches a child process and the child process will execute the program with the arguments entered in the command line.
This is what the command line should look like.
./launch program arg1 arg2 arg3
argv[0] = "./launch"
argv[1] = "program" --> This is the program I want the child p... | You appear to assume that *arguments will expand to multiple items, but this is a Python list unpacking feature that C++ does not have. Instead, C/C++ uses * here for pointer dereferencing.
Your statement will therefore declare a nullptr-terminated list of two arguments, rather than N arguments the way you appear to in... |
72,523,844 | 72,524,641 | How to read a 2d triangle array from txt file? | I want to read 2d triangle array from a txt file.
1
8 4
2 6 9
8 5 9 6
I wrote this code. At the end I wanted to print it out if I got the array right. When I run it it does not print the array, but in debug it prints. So there is a problem, but I cannot find it. Sometimes it gives segmentation fault, but I dont unders... | You can just use vector instead of malloc. Like this:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <vector>
using namespace std;
int main() {
ifstream input_file("input_file.txt");
vector<string> numbers;
if (input_file.is_open()) {
string line;
whi... |
72,523,879 | 72,525,427 | add to queue a template function c++ | i search on google how to store and to execute functions (template function or not) passing in queue but i didn't find an enough good answer...
this is my code
Window.h
struct QueueEventFunction {
std::vector<std::function<void()>> v; // stores the functions and arguments
... | The big problem with your code is that you take the function pointer as a pointer
template <typename F, typename ...Args>
void Enqueue(F (*f), Args... args)
and
template <typename F, typename ...Args>
void addQueue(F (*f), Args...args);
What you really want is
template <typename F, typename ...Args>
void Enqueue(F f,... |
72,524,438 | 72,525,656 | simplify template interface, remove redundant typenames | #include <cstddef>
#include <utility>
template <size_t N, typename... V>
struct T {
int test(size_t n, const char** ss) {
if (N > n)
return 1;
return []<size_t... I>(const char* ss[N], std::index_sequence<I...>) {
return test_impl(ss[I]...);
}(ss, std::make_index_seq... |
sizeof...(V) == N
No, the compiler doesn't know it. (Take a look at the error messages)
Since you have this prequisite, you don't have to have the template parameter N.
template <typename... V>
struct T {
int test(size_t n, const char** ss) {
constexpr int N = sizeof...(V);
if (N > n)
... |
72,525,107 | 72,525,391 | How to force C++ linker to catch conflict of enum definitions? | I have these two source files that compile and link without any problem.
a.cpp
enum class numbers
{
one,
two,
};
const char* getName(numbers number)
{
switch (number)
{
case numbers::one:
return "one";
break;
case numbers::two:
return "two";
break;
}
}
b.cpp... | The shown error is a violation of the One Definition Rule.
The C++ standard does not require either the compiler or a linker to report a diagnostic when the One Definition Rule is violated. I.e. "no diagnostic required".
In other words: your C++ compiler is not required to report this specific error. This is because in... |
72,525,307 | 72,525,499 | When 'nested stack unwinding' is OK? | AS I understand that we can not throw exceptions from dtor,
and the reason is said like:
"if an exception was thrown inside 'stack unwinding', then there is no clear way to handle 'nested unwinding', thus 'throwing from dtor' is prohibited.".
What makes me confuse is that, to obey above rule, we write codes like this:
... | Throwing an exception while stack unwinding is in progress is fine. But throwing an exception from a destructor of an object that is being unwound from the stack or from any other function invoked by the exception handling mechanism (e.g. a catch parameter constructor) causes a call to std::terminate.
Throwing from a f... |
72,525,482 | 72,525,732 | Why does constinit allow UB? | Say I initialize variables like this:
#include <cstdint>
constexpr uint16_t a = 65535;
constinit int64_t b = a * a; // warning: integer overflow in expression of type 'int' results in '-131071' [-Woverflow]
constexpr int64_t c = a * a; // error: overflow in constant expression [-fpermissive]
Both b and c produce unde... | This is related to CWG issue 2543.
As it stands currently, because the compiler is allowed to replace any dynamic initialization with static initialization if it can and because constinit is only specified to enforce "no dynamic initialization", it might still allow an initializer which is not a constant expression (ma... |
72,526,095 | 72,526,244 | Why does inheriting constructors break aggregate initialization? | Why does inheriting constructors from a base class break aggregate initialization?
For example, this works:
struct MyArray : std::array<int, 2ul> {};
MyArray a{1, 2};
but this doesn't work:
struct MyArray : std::array<int, 2ul>
{
using std::array<int, 2ul>::array;
};
MyArray a{1, 2};
| Since C++17, aggregates can have base classes, so that for such structures being derived from other classes/structures list initialization is allowed:
struct MoreData : Data {
bool done;
};
MoreData y{{"test1", 6.778}, false};
In C++17 an aggregate is defined as
either an array
or a class type (class, struct, or... |
72,526,361 | 72,526,881 | Difference between inheriting from std::iterator and explicitly typedefing its member types | I thought there are no differences, but I'm confused because while reading the draft of C++ standard, 24.5.1.1, reverse_iterator, I found that the reverse_iterator is inherited from iterator and also has explicit typedefs difference_type, pointer, and reference.
template <class Iterator>
class reverse_iterator : public... | This has been in the standard since C++98, so it is going to be a bit hard to find some context for how it came about.
Here is a just a guess:
They may have wanted to inherit the iterator from std::iterator as a matter of policy to inherit all iterators from it (not sure about that).
But if you were to simply copy the ... |
72,527,224 | 72,545,381 | aeron 1.37 pingpong(c) test gets a slightly higher latency number compare to 1.31.2 | I've been using real-logic/Aeron(c/c++ version) for almost 2 years.
Recently I was thinking of upgrading Aeron from 1.31.2 to 1.37.0.
But after run the pingpong test, I got a slightly higher latency number(around 0.1 us rtt) from 1.37.0.
I ran the Ping on one server, and Pong on another server.
I tested version by vers... | Aeron 1.38.2 has some significant changes which improve the performance.
|
72,527,510 | 72,528,242 | Why does each instantiation of a lambda function result in a unique type? | Recently I asked a question about some code I had which was causing my compiler to run out of heap space. This code contained a recursive template function which was being passed a lambda function. Each instantiation of the template function caused (via the recursive call) another instantiation of the same template fun... | The question is more easily answered by considering the opposite. If it were not true, then some lambda's would have the same type. Furthermore, the Standard should then say which lambda's have the same type, and which lambda's have distinct types.
Note that with "type" we mean more than just the signature of operator(... |
72,527,536 | 72,527,741 | AND Operation for -1 | While implementing logical operations in the code, I discovered a phenomenon where it should not be entered in the if statement.
It turns out that this is the AND (&&) operation of -1 and natural numbers.
I don't know why the value 1 is printed in the same code below.
I ran direct calculations such as 1's complement an... | The expression a && b is a bool type and is either true or false: it is true if and only if both a and b are non-zero, and false otherwise. As your question mentions complementing schemes (note that from C++20, an int is always 2's complement), -0 and +0 are both zero for the purpose of &&.
When assigned to the int typ... |
72,527,627 | 72,528,716 | Updating map values in place | How could I simplify this code to update the int value in the map in place?
Basically I want to leave the exceeds unchanged (which is the bool) and just update the int value.
std::map<OrderInfo, std::pair<int, bool>> ncpOrders;
int NotCompletelyProcessedOrders::IncAttempts(OrderInfo& ordInfo) {
auto it = ncpOrders... | You make this over-complicated. Note that default construction of std::pair<int, bool> meets your requirement, so you can just do:
std::map<OrderInfo, std::pair<int, bool>> ncpOrders;
int NotCompletelyProcessedOrders::IncAttempts(OrderInfo& ordInfo) {
return ++ncpOrders[ordInfo].first;
}
and outcome should be exa... |
72,527,822 | 72,528,027 | Why is the address of the same pointer different? | I was trying linked list on C++ and when I try to print the data of the list, it gives funny result which tells me that the list is null. When I print the address of the variable in main and print the address of the parameter of the same variable in the function, it gives different results. Could anyone please explain ... | head and head_1 are two different variables so they have two different addresses. But the values of those variables are also addresses (or pointers) and those values are the same.
When you are dealing with pointers it's easy to get the address of a variable and the value of a variable mixed up because they are both poi... |
72,528,728 | 72,590,334 | Bazel Android c++_shared/c++_static issues | We have a project that uses a library that is built on top of Google's Mediapipe, which is built using the Bazel build system.
The project itself is an Android Native Library, built using Gradle with CMake
externalNativeBuild {
cmake {
cppFlags "-std=c++17 -fopenmp -static-openmp -fe... | I managed to get it working as suggested by using c++_static on all of our shared objects (SDK, Mediapipe, OpenCV and others)
|
72,529,160 | 72,529,204 | Create copy of self in base destructor | I want to write a family of classes that create copies of themselves under certain conditions when getting destructed. Please see the code below
#include <string>
#include <iostream>
bool destruct = false;
class Base;
Base* copy;
class Base {
public:
virtual ~Base() {
if (!destruct) {
destruct = true;
... | You can't.
By the time the base destructor runs, the derived destructor has already run and destroyed information that the copying would need to preserve.
You need to change your approach.
|
72,529,167 | 72,529,206 | error: redefinition of polymorphic class with a pointer in constructor | i'm curretly trying to make a game of battleship in c++ and i am in the procces of coding three cpu levels with polymorphism,targetet board object is passed as a pointer into constructor and it works up until i try to make a drived class and i keep receiving this error :
error: redefinition of 'cpu_medium::cpu_medium(b... | You define cpu_medium::cpu_medium(board &e) twice, exactly as the error message says.
In cpu_battleships.h change
cpu_medium(board &e):cpu_easy(e){};
to
cpu_medium(board &e);
That way the constructor is only defined in cpu_battleships.cpp
|
72,529,411 | 72,548,158 | Cocos 2dx 4.x. Enable C++17 in Android Studio | I am trying to learn Cocos 2dx game engine. I generated a simple project with this command:
cocos new -l cpp -p com.testgame1 -d path_to_dir testgame1
Next, I try to build an android project. Everything is successful. Then I wrote a lot of code that uses C++ standard 14, 17. Example (file main.cpp):
void cocos_android... | In your game project folder, open up CMakeLists.txt, and add the following after the include(CocosBuildSet) statement:
set(CMAKE_CXX_STANDARD 17)
If you want to apply C++17 to the cocos2d engine code as well, then adding this may work:
set_target_properties(cocos2d PROPERTIES
CXX_STANDARD 17
CXX_STANDARD_REQUI... |
72,529,929 | 72,531,852 | Unable to compile example code from AWS SDK for C++ - Developer Guide | I am trying to upload a file using an encrypted client and i`m having a hard time setting the body of the PutObjectRequest object. I am using the sample code.
PutObjectRequest putObjectRequest;
putObjectRequest.WithBucket("BUCKET_NAME")
.WithKey(AES_MASTER_KEY);
std::shared_ptr<Aws::IOStream> input_data... | As the code is missing #include <fstream> Aws::FStream (which is a typedef for std::fstream) is an incomplete type and the compiler doesn't know that std::fstream is derived from std::iostream so doesn't know how to convert from std::shared_ptr<Aws::FStream> to std::shared_ptr<Aws::IOStream>.
Visual studio isn't very h... |
72,531,078 | 72,540,370 | Where is code of the instantiation of C++ vector? | I have a very simple code as below, which uses a C++ vector:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> g1;
return 0;
}
By coping the code to the website https://godbolt.org/, I know the generated assembly code is as below:
main:
stp x29, x30, [sp, ... | You are simply confused because godbolt.org doesn't show standard library functions by default in the assembly view.
Click on "Filter..." and then deselect "Library functions".
Then you will get the missing symbols, for example the std::vector<int> default constructor and destructor.
They are not shown by default becau... |
72,531,618 | 72,533,194 | Const correctness of operator* in std::unique_ptr | Why can 'operator*' member function of std::unique_ptr be marked const (https://en.cppreference.com/w/cpp/memory/unique_ptr/operator*) while functions like 'front()', 'back()', 'operator[]' etc in std::vector not be marked const? Both are returning non-const references to the resources they are managing.
The core probl... | The difference lies in the definition of a container.
A std::vector is considered a container. This means that the objects managed by a std::vector are considered parts of the vector.
The references returned from front(), back() and operator[] must be const if the vector is const. Modifying those objects will modify ... |
72,531,788 | 72,531,885 | Using iterator to initialize string, get "transposed pointer range" exception | Maybe a noob question but why these two lines:
vector<char> v{"h","i"};
string s1(v.cbegin(), v.cend());
won't compile?
It says "debug assertion failed, exception:transposed pointer range".
| Debug assetions happen in run-time, not compile time.
In any case, you should change:
vector<char> v{"h","i"};
to:
vector<char> v{ 'h','i' };
char literals should be enclosed with ', not ".
This way your code should compile and run properly.
See also @Eljay's comment above for more info how the compiler actually inte... |
72,531,849 | 72,532,230 | Why isn´t my If-Else statement working properly? | I have a project where I have to change some parametres depending on the field of rotation I want for a magnetic field generator. I am not a developer and c++ is not my program of expertice, but I need to find a way to change between two different configurations using a toggle function. I tried using an If-Else stateme... | Variables field_orientation and rot_axis you declare inside if or else blocks are completely unrelated to variables field_orientation and rot_axis you declared before if statement. Because they share names, variables inside smaller scopes shadow the names in the outer scope, and you can only access variables from small... |
72,532,148 | 72,532,247 | Calling a function with parameters of vector<int> and lambda function in main() with an anonymous lambda | Question:
Using the following unfinished function (finish it), call it in the main function with an anonymous lambda function as a parameter and print all numbers that are NOT divisible by 2, 3 and 5.
vector<int> izdvoji(vector<int>& x, function<bool(int)> kriterij);
int main()
{
vector<int> brojevi = { 1, 4, 5, 7, ... | Your condition is wrong. Try for example 31, which is not divisible by 2, 3 or 5:
return !(31 % 2 || 31 % 3 || 31 % 5);
return !( 1 || 1 || 1 );
return !( true );
return false;
Check divisiblity by x % n == 0:
return !(x % 2 == 0 || x % 3 == 0 || x % 5 == 0);
For the warning about unsigned vs signed compar... |
72,532,225 | 72,532,358 | Passing Class Objects as Arguments of Classes | I have been working on a tetris game and I have to pass an object into a function as its argument to use the object inside the function.
I made this function and it should be able to control the Board object from Main.cpp to update the coordinate.
void BlockInfo::send(Board board)
{
for (int i = y; i < y + 4; i++)
... | With void BlockInfo::send(Board board) and blcInf.send(board); you always make a copy of board and inside send you modify that copy - but not the original board from main.
You need to pass the Board by reference, not by value.
With void BlockInfo::send(Board& board) you are not making a copy but a reference. So send is... |
72,532,530 | 72,532,574 | Can't update values of members when constructor is invoked | I've created two classes, 'Cylinder' and 'random', with 'Cylinder' publicly inherited by 'random'. So I created an object of 'random' and tried to change values of member variables of "Cylinder'. Couldn't get it to work
#include "constants.h"
#include<iostream>
class Cylinder{
public:
double r,h;
public:
... | You need to delegate to the superclass constructor in the member initializer list for your constructor, not in the body of the constructor itself:
random(double r,double h) : Cylinder(r, h) {}
As is, the default superclass constructor got invoked implicitly (thus seeing default values on your random instance), and the... |
72,533,139 | 72,572,297 | Libtorch errors when used with QT, OpenCV and Point Cloud Library | I am trying to use libtorch, qt widgets, point cloud library(pcl) and opencv in a project. For this project I am using cmake lists. The issue is that when I am using all four libraries together, errors are thrown by libtorch. If I use libtorch, opencv and qt everything works fine, also if I use pcl qt and opencv everyt... | After many tries I have managed to bind the four libraries together and make them work. There were many issues that had to be solved even after solving the error mentioned in the original question. I will describe in short what I did such that if anyone will ever face this issue to know how to solve it.
There are many ... |
72,533,147 | 72,535,012 | Get image from a fingerprint using Python and Ctypes | I'm trying to get an image from the fingerprint scanner Futronic FS88h, here is what I've been doing until now.
from ctypes import windll, wintypes
from os import device_encoding
import ctypes
lib = ctypes.WinDLL('ftrScanAPI.dll')
FTRHANDLE = ctypes.c_void_p
# classes
class FTRSCAN_DEVICE_INFO(ctypes.Structure):
... | There's a C# example here. Using it as a reference:
# Relevant definitions from the library header:
# #define FTR_API_PREFIX
# #define FTR_API __stdcall
#
# typedef void* FTRHANDLE;
# typedef void* FTR_PVOID;
# typedef int FTR_BOOL;
#
# typedef struct
# {
# int nWidth;
# int nHeight;
# int nImageSize;
#... |
72,533,385 | 72,533,511 | Get type of instantiated unnamed struct | I'm writing an app in C++ that interfaces with some code written in C.
The following is a simplified version of a struct defined in C code that I can't modify.
struct event{
uint8_t type;
union {
struct /* WishThisHadAName */ {
// ...
} connect;
struct {
// ...
... | Simple as using event_connect_t = decltype(event::connect);.
Then you can use it as void onConnect( event_connect_t *evt );.
You can't declare a compatible type, but you can just extract the existing type declaration from the definition. decltype can resolve static member references just fine.
|
72,533,435 | 72,533,531 | error: zero as null pointer constant while comparing template class using spaceship operator (<=>) | Similar question: warning: zero as null pointer constant while comparing iterators - that is about comparing iterators, this question is about comoparing template classes.
I was migrating c++14 codebase to c++20. however using spaceship operator gives an warning zero as null pointer constant, which i can't figure out w... | Here's a more minimal example:
#include <compare>
struct quantity {
int i;
constexpr auto operator<=>( const quantity& ) const = default;
};
bool f(quantity a, quantity b) {
return a < b;
}
What's actually happening here is that a < b evalutes as (a <=> b) < 0. The way that comparison categories are spec... |
72,533,601 | 72,534,455 | Conditionally compile function if `std::optional` exists | I am having a mixed C++14/C++17 codebase and I want to enable a function isEmpty only if I am having std::optional at hand. So, I tried SFINAE:
template <typename T, typename int_<decltype(std::nullopt)>::type = 0>
inline bool isEmpty(const std::optional<T>& v) {
return !v;
}
However, that doesn't work.
How can I co... | If your compiler is recent enough (e.g. GCC >= 9.1 or Clang >= 9.0.0), you may include header <version> and conditionally compile your function template if macro __cpp_lib_optional is defined:
#include <version> // provides, among others, __cpp_lib_optional
#ifdef __cpp_lib_optional
template <typename T>
inline bool i... |
72,533,614 | 72,544,035 | C++20 import modules with dot notation from main file in Clang | In a C++20 project built with Clang (stdlib=libc++), I have the next structure:
testing_core.cppm
export module testing.core;
export namespace testing {
class TestSuite {
public:
static constexpr const char* var [] = { "Hi, constexpr!" };
};
void say_hello();
}
clang++ -c --std=c++20... | Solution it's pretty straightforward. In Clang, (at least in versions up to 14.0.4), you must explicitly include the -fmodule-file=<some_interface> for the module files that includes the dot notation in it's identifier.
So, for the main.cpp file build process, it must include -fmodule-file=./out/modules/interfaces/test... |
72,533,711 | 72,536,213 | Removing last trailing comma from the arguments of a macro | I need to remove the last trailing comma from a list of macro arguments (because they will be eventually expanded into template arguments where the trailing comma is not admitted).
So I need a macro remove_trailing_comma() which called like remove_trailing_comma(arg1, arg2, arg3, ) expands to arg1, arg2, arg3.
I've tri... | You'll probably should go with @eljay's answer, but if you need to support way more arguments, here is one that supports ~2000 arguments in 22 lines and adding more lines grows that number exponentially.
#define E4(...) E3(E3(E3(E3(E3(E3(E3(E3(E3(E3(__VA_ARGS__))))))))))
#define E3(...) E2(E2(E2(E2(E2(E2(E2(E2(E2(E2(__... |
72,534,040 | 72,534,239 | How to provide multiple options to link a function | I have 3 object files :
main.o
general.o
specific.o
in main.o there is a call to function : void handle(void),
general.o implement a generic functionality to handle() ,
specific.o might or might not have an implementation to handle() ,
I want to specify in my cmake that "search to link handle with specific.o i... | There certainly is nothing in standard C++ which allows this.
For Gcc/clang toolchain you can define handle as a weak symbol in general TU with __attribute__((weak)) and as ordinary symbol in specific.
Be very careful with this though, ensure that handle itself is not called in general. Because if it is, the call might... |
72,534,240 | 72,534,896 | C++ vector sorting and mapping from unsorted to sorted elements | I have to perform the following task. Take a std::vector<float>, sort the elements in descending order and have an indexing that maps the unsorted elements to the sorted ones. Please note that the order really matters: I need a map that, given the i-th element in the unsorted vector, tells me where this element is foun... | You can use the code below.
My version of get_indices does the following:
Create a vector of indices mapping sorted -> unsorted, using code similar to the one in the link you mentioned in your post (C++ sorting and keeping track of indexes).
Then by traversing those indices once, create the sorted vector, and the fin... |
72,534,844 | 72,535,338 | removing alphebatical reordering of key value pairs in nlohmann json | nlohmann::json payload = {{"type", "market"},
{"side", "buy"},
{"product_id",market},
{"funds", size}};
std::cout << payload.dump() << std::endl;
out : {"funds":"10","product_id":"BTC-USD","side":"buy","type":"market"}
As you can see json is alphabetically reordered, which I d... | You can use nlohmann::ordered_json instead of nlohmann::json to preserve the original insertion order:
nlohmann::ordered_json payload = {{"type", "market"},
{"side", "buy"},
{"product_id","market"},
{"funds", "size"}};
std::cout << payload.dump() << std::endl;
Re... |
72,534,881 | 72,535,261 | Macro expansion ignores some tokens in MSVC | I have some problems with macro expansion in msvc compiler.
I expect the following code to be expanded to F x, which it does on gcc and clang.
But msvc expands it to just F ignoring x token. What's going on here?
#define S(s) s
#define F()
#define M() S(S(F) x)
M() // expands to 'F' on msvc
However, without defining... | Use /Zc:preprocessor to switch to the new, standard-conformant preprocessor. It behaves as you expect.
|
72,535,005 | 72,535,109 | Lifetime extension of temporary objects: what is the full expression containing a function call? | Introduction
Say there is a Container class which stores Widget objects.
There is an iterator class in charge of navigating such container. This iterator class (MyIterator) takes a const-reference to a vector of Stuff in its constructor, which it needs to iterate over the right elements in the container. The code may l... | Yes, the whole std::copy_if call is the full-expression and the temporary std::vector<Stuff> will be destroyed only after the call returns.
This is different from by-value function parameters. If the constructor took a std::vector<Stuff> instead of a const std::vector<Stuff>&, then it would be implementation-defined wh... |
72,536,308 | 72,536,531 | C++ How can I convert a string to enum to use it in a switch? | I have a list of commands that if a user inputs then it will call separate functions. Talking to a friend he said I should use switch, which is faster and easier to read over "if, else if, else" statements.
When checking how to implement this I realised that I wouldn't be able to because the input is a string and for a... | Why not have a map of string to function.
Then you don't need to convert to an enum.
using Action = void(std::vector<std::string>);
using ActionFunc = std::function<Action>;
using ActionMap = std::map<std::string, ActionFunc>;
void MIN(std::vector<std::string>){}
... etc
ActionMap inMap
{
{ "min", MIN ... |
72,536,465 | 72,536,725 | std::transform with variant | I have two vectors: A vector of a type that acts as a union, whose type I can retrieve.
The other vector is a vector of variants of another type.
I want to use std::transform to do a conversion to one of my variant types.
However, I receive a compile error that std::transform or rather the lambda can not deduce the ret... | Add a trailing return type specifier to your lambda:
// vvvvvvvv -- Add This
[](baz& bazzer) -> entry {
// ...
}
A lambda, like any function, has to return one single type. As it currently stands it returns different types though depending on which case gets chosen: either bar in case 0 or foo in cas... |
72,536,471 | 72,536,949 | Using Designated Initializer on member of inherited base class | I created a class Something which holds a member variable.
I am able to do this, which works as intended:
struct Something
{
bool Works;
};
int main()
{
Something s = {
.Works = false,
};
}
Now, I want to created a struct inherited from Something, named Something2, and want to do the same thing, b... | C++ is much stricter when it comes to designated initializers than C.
cppreference:
out-of-order designated initialization, nested designated initialization, mixing of designated initializers and regular initializers, and designated initialization of arrays are all supported in the C programming language, but are not ... |
72,536,995 | 72,538,587 | candidate template ignored: could not match 'const char' against 'const char' | I am using a sequence of string from this link: here
template<typename Char, Char... Cs>
struct char_sequence
{
static constexpr const Char c_str[] = {Cs..., 0};
};
// That template uses the extension
template<typename Char, Char... Cs>
constexpr auto operator"" _cs() -> char_sequence<Char, Cs...> {
return {};
... | Once I fixed the many typos in your code (please don't post rubbish), the fix was simple enough.
Just change this:
constexpr auto operator"" _cs() -> char_sequence<Cs...> { ...
to this:
constexpr auto operator"" _cs() -> char_sequence<Char, Cs...> { ...
// ^^^^
and then i... |
72,537,103 | 72,537,151 | How to resolve ambiguous overload for 'operator=' in string | I am trying to create a class that can be implicity cast to a variety of different types, both primitives and custom defined classes. One of the types that I want to be able to cast to is an std::string. Below is an example class that can cast to various different types. It throws the error "error: ambiguous overloa... | std::string has several overloaded operator=s with following parameters: std::string, const char *, char, std::initializer_list.
For your code to work, the compiler needs to choose one, but at least two are potentially suitable: the std::string one; and the char one, using an implicit conversion from one of your scalar... |
72,537,141 | 72,537,179 | C++: Always-Throw function in conditional expression | Conditional expressions allow throw expressions as operands. I would like to have a conditional expression where one of the operands is an always-throw function, however it appears that this is not possible.
#include<exception>
[[ noreturn ]] void foo() {
throw std::exception();
}
int main() {
int a = true ? ... | You can use the comma operator like so:
int a = true ? 1 : (throw std::exception(), 0);
int b = true ? 1 : (foo(), 0);
See it working on godbolt.org.
|
72,537,523 | 72,537,681 | Supporting custom hooks in existing cpp class | I am designing support for custom hooks in existing C++ class.
class NotMyClass {
public:
void DoSomething() {
// Needs custom logic here.
hook_.DoSomethingCustom();
}
protected:
Hook hook_;
int not_my_class_inner_variable_1_;
Node not_my_class_inner_variable_2_;
...... More Cl... | The problem cannot be solved as stated, i.e., without breaking the Open-Closed-Principle (OCP), which says that "classes (and other things) should be open for extension but closed for modification." In this case, this means that you shouldn't try to both (a) leave MyClass unchanged and (b) access its private or protect... |
72,537,705 | 72,537,802 | Why don't elements from my list get erased | I have to write a function that erases an element out of the list if it's bigger than the previous element.(The previous element is the one which points to the next element before deletion)
I think I've basically finished it but I don't know why it doesn't erase 5 out of my list.
void deleteBigger(list<int> s){
lis... | There are three problems with your code:
Your list is passed by value, not reference. So you are changing a copy of your list and it doesn't alter the original container
You try to remove an element from a list while iterating it. Edit: As @Remy Lebeau mentioned in the comments, to be more precise it's a problem becau... |
72,537,928 | 72,538,158 | Writing a custom input manipulator | I need to make a custom istream manipulator that reads 5 characters from input, then skip 5 characters from input, and does it to the end of the string. Example:
string line;
cin >> skipchar >> line;
This is that I did, but it doesn't work for some reason. Also, it would be better, if I don't use <sstream>
struct memb... | You did not show your input, but I don't think getline() would be appropriate to use in this situation. operator>> is meant to read a single word, not a whole line.
In any case, you are leaking both char[] arrays that you allocate. You need to delete[] them when you are done using them. For the str array (which FYI, ... |
72,538,132 | 72,546,882 | Is there a way to see what's inside a ".rodata+(memory location)" in an object file? | So I'm taking a class where I am given a single object file and need to reverse engineer it into c++ code. The command I'm told to use is "gdb assignment6_1.o" to open it in gdb, and "disass main" to see assembly code.
I'm also using "objdump -dr assignment6_1.o" myself since it outputs a little more information.
The p... |
Is there a way to see what's inside a ".rodata+(memory location)" in an object file?
Sure. Both objdump and readelf can dump contents of any section.
Example:
// x.c
#include <stdio.h>
int foo() { return printf("AA.\n") + printf("BBBB.\n"); }
gcc -c x.c
objdump -dr x.o
...
9: 48 8d 05 00 00 00 00 lea 0x... |
72,538,291 | 72,538,338 | What am I missing to make this int to char conversion produce the intended effect? | I am making a game in SDL2, and I've decided to add an FPS counter. The number for the counter needs to update every second, and here's how I've accomplished that
bool updateFPS() {
if (fpsDTime == 1) { // time between update has been one second
frameCounterS++; // add an extra frame
... | I suspect you're just seeing uninitialized bytes from SframeCounterS. You should either clear the buffer with a memset(SframeCounterS, 0, sizeof(SframeCounterS));, or work with a string, which would simplify the code as well:
TTF_RenderText_Blended(HPusab, std::to_string(frameCounterS).c_str(), White);
|
72,538,652 | 72,538,665 | Type mismatch when returning an int value from an int function with str parameter | I have the following functions:
// Created by onur on 06/06/22.
#include <iostream>
#include <fstream>
#include <opencv2/opencv.hpp>
#include <opencv2/videoio.hpp>
#include "VideoProcessing.h"
VideoProcessing::VideoProcessing() = default;
int VideoProcessing::getFPS(const std::string& video_path) {
int FPS; //... | You are using a multicharacter literal that has the type int (and conditionally supported) instead of a string literal in these calls
int fps = vid.getFPS('mesh.mp4');
unsigned long size = vid.getSize('mesh.mp4');
Instead write
int fps = vid.getFPS( "mesh.mp4" );
unsigned long size = vid.getSize( "mesh.mp4" );
|
72,538,967 | 72,539,477 | C++ Map with customized comparator does not work correctly | Map with a customized comparator does not work as expected.
Code:
struct Comp {
const bool operator()(const int x, const int y) const {
return abs(x) < abs(y);
}
};
map<int, int, Comp> func(vector<int>& arr) {
map<int, int, Comp> mp;
for (int x : arr) {
mp[x]++;
}
return mp;
};
... | map uses the comparator to test ordering, but also to know if two keys are equal, i.e., if comp(a,b) == false and comp(b,a) == false, then it means that the 2 keys are equal and that they should be considered the same, even though the bits in memory are different.
In your case, comp(-2,2) and comp(2,-2) are both false ... |
72,539,619 | 72,539,712 | Is there a way to get the methods of a class if you send class as <T>? | I've the following code
class Person {
public:
string fname, lname;
string getName() {
return fname + " " + lname;
}
};
template<class T> class A {
...
};
int main() {
A<Person>* a = new A<Person>();
}
Since for template class A, I have T saved as Person. Is there any way I can use the m... | Have you tried? I see no problem with this code. Templates are not like Java's generics, you can use the types directly as if it was normal code.
#include <string>
#include <iostream>
class Person{
public:
std::string fname, lname;
std::string getName(){
return fname + " " + lname;
}
};
template<c... |
72,540,612 | 72,546,807 | Eligible special member functions and triviality | Consider the following code:
#include <type_traits>
template<typename T>
concept Int = std::is_same_v<T, int>;
template<typename T>
concept Float = std::is_same_v<T, float>;
template<typename T>
struct Foo
{
Foo() requires Int<T> = default; // #1
Foo() requires Int<T> || Float<T> = default; // #2
};
static_... |
So, is my analysis correct?
Definitely. My intent in writing this wording in P0848 was very much that #2 is eligible - that's the one overload resolution would pick and it's not deleted, so it should be eligible.
I opened a CWG issue request which is now CWG 2595.
|
72,541,077 | 72,541,172 | Converting std::list<int> iterator to an CString (MFC) | Newbie in world of MFC and MS Windows C++.
I am trying to populate a ComboBox dynamically. But I am not able to convert the iterator pointer to CString or an std::string. Here is my sample code:
bool single_digit (const int& value) { return (value >= 60); }
int numArr[] = {10,20,30,40};
int size = sizeof(numArr)/sizeo... | This is essentially asking how to convert an integer to its string representation. The simplest way to go about this is to call std::to_wstring, that provides an overload taking an int value.
The following code does what you're looking for:
for(std::list<int>::iterator it=numList.begin(); it!=numList.end(); ++it)
{
... |
72,541,591 | 72,541,754 | n is 0 after passing it as an argument to the function, What seems to be the problem here? | Here the question is to put all the zeroes to the end of the array.
I've written the code below, but after passing (arr, n) to the pushzero() function, when I try to print the array, it does nothing, and the value of n changes to zero after calling the pushzero() function.
#include <bits/stdc++.h>
using namespace std;... | You could do it by using 0 as a pivot element and whenever you see a non zero element you will swap it with the pivot element. So all the non zero element will come at the beginning.
void pushzero(int arr[], int n) {
int j =0;
for (int i = 0; i < n; i++) {
if(arr[i] != 0) {
swap(arr[i]... |
72,542,365 | 72,543,175 | two vector same pointer, delete, memory loss | https://github.com/gameprogcpp/code/blob/master/Chapter02/Game.cpp
std::vector<Actor*> deadActors;
for (auto actor : mActors)
{
if (actor->GetState() == Actor::EDead)
{
deadActors.emplace_back(actor);
}
}
// Delete dead actors (which removes them from mActors)
for (auto actor : deadActors)
{
de... | // Delete dead actors (which removes them from mActors)
This is incorrect; deleting the Actors does not modify the original vector. It only results in dereferencing the pointers to those Actors to be undefined behaviour.
You'd need an additional step removing the pointers from the original vector for this reason.
You ... |
72,542,616 | 72,546,131 | C++: can I get a "generic" (non-template) pointer (or reference) to a template class? | I have the following problem:
I have a class template where each instance represents an array of values (type of values is the template argument, of course).
each instance has a name and that name is stored in the instance itself and in a static std::map
Something along the lines:
#include <cstddef>
#include <string>... | I went through the exercise of deriving from a base class.
Here is a piece of code actually compiling:
#ifndef AWBLOCK_H_
#define AWBLOCK_H_
#include <stdexcept>
#include <cstddef>
#include <string>
#include <map>
namespace AW {
class generic_block {
private:
static std::map<std::string, generic_block*> block... |
72,542,649 | 72,545,369 | How can i divide a Boost Polygon into regions to get random points in c++? | I have a Boost Polygon made like this :
Polygon2D create_polygon(Point2D const& p1, Point2D const& p2, Point2D const& p3, Point2D const& p4) {
return {{p1, p2, p3, p4, p1}};
}
int main() {
auto const& polygon = create_polygon({0., 0.}, {0., 4.}, {7., 4.}, {7., 0.});
return 0;
}
(not exactly my code but re... | If you only want to use the subdivision to get the random points in your polygon, you can avoid that by combining the idea of marching squares with Monte Carlo:
Take the bounding box of your polygon and divide it into squares of equal size.
For each square, determine if it is wholly or partially inside the polygon.
Ge... |
72,543,119 | 72,557,127 | Hide a rectangular block temporarily from the main window in QML | I created a nested rectangular block i.e. a rectangle inside a main rectangular block in QML. Now I have to hide the inner rectangular block on some operation and once the operation is finished make it visible again. I am trying the following:
Rectangle {
id: window
width: 450
height: 550
... | This seems to work. I'm hiding the Rectangle containing the ToolButton when onClicked is triggered and show it again inside the callback assigned to grabToImage(callback, targetSize). Adding the RowLayout was just to make the ToolButton horizontally centered in the Rectangle.
import QtQuick
import QtQuick.Controls
impo... |
72,544,065 | 72,558,644 | Edit file (html) in a stream (C++) | I'm looking for some help for my new project and I'm absolute new in programming in C++.
I've a html template (size ~ 8kb) with some placeholders inside. My task is to read this template edit the placeholders and add some or less containers depending on my source.
I tried different ways but always get stucked on a diff... | I found a solution or better the problem. I always test the first point by using the debug function. And always stop at the line after
out_file << str;
But to this position, for whatever reason (maybe someone can explain!?), only a part of the file was written. So I had never run my code to the end. Now I have run it ... |
72,544,399 | 72,544,468 | Using a static_cast on non-pointer related types | I discover this compiler trick and I cannot find a name for. Have you any idea?
On an Intel processor, I can cast a variable from its base class to an inherited class. It works with MSVC, gcc and clang and I am very confused.
#include <string>
#include <iostream>
class A
{
public:
virtual std::string print() const... | Yes, static_cast can cast a class to a reference to a derived class. That is not a trick or compiler-specific. That is one of the specified purposes of static_cast in the C++ standard.
However, this cast has undefined behavior if the object isn't actually a base subobject of a derived class object.
In your case here yo... |
72,544,712 | 72,544,866 | confused with the fowarding reference | In the c++ std type_traits file below the first overloaded function, the comment says:
forward an lvalue as either an lvalue or an rvalue
However the return value is just an rvalue reference, I wonder how it could be either an lavlue or an rvalue? Does it mean the returned value is a universal reference? If so what d... | If _Ty is either a rvalue reference or a non-reference, then _Ty&& is (by reference collapsing rules) a rvalue reference. Hence the function call expression will be a xvalue (a kind of rvalue).
If _Ty is however an lvalue reference to type T, i.e. _Ty = T&, then the reference collapsing rules imply that also _Ty&& = T ... |
72,545,509 | 72,545,701 | Is it still valid when the variable passed to `std::async` is out of scope? | Is the code snippet below legal? What worries me is when factorial is invoked the fut_num may be already out of scope.
#include <future>
#include <vector>
#include <iostream>
//int factorial(std::future<int> fut) //works, because there is a move constructor
int factorial(std::future<int>&& fut)
{
int res = 1;
... | The first one is fine, the second one is not.
std::async with std::launch::async uses the same procedure of invoking the thread function as the constructor of std::thread does. Both effectively execute
std::invoke(auto(std::forward<F>(f)), auto(std::forward<Args>(args))...);
in the new thread, but with the auto(...) ... |
72,545,760 | 72,546,047 | How to solve the DLL cannot be found issue | In my C# Wpf project, I need some funtion from C++. So I make my own C++ DLL project named LibC. And the Wpf app can run normally in my computer. But on the tester's computer, the log says:
Unable to load DLL 'LibC.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
And I checked that t... | Your users will need to install the visual c++ runtime. The typical way to do this would be with an installer that does this silently. As far as I know they cannot be compiled into your program, and that the license prohibit distribution of lose dlls outside the redistribution package.
Note that you may need to update ... |
72,545,923 | 72,546,120 | error: explicit specialization of undeclared template class | I have this interface:
template <class T>
class Builder {
public:
// Virtual destructor
virtual ~Builder(){}
// Builds a concrete instance of the implementor
virtual T build() const =0;
};
and the following concrete implementation:
template <class T>
... | The correct syntax to inherit from Builder<T> while defining the ConcreteBuilder template would be as shown below:
template <class T>
//-------------------v------------------->removed <T> from here
class ConcreteBuilder : Builder<T> {
public:
// Virtual destructor
virtual ~ConcreteBuilder(){}
... |
72,546,623 | 72,547,243 | C++: Values of both objects changes after a Copy Constructor | I have written a simple c++ code to understand the concepts of Copy Constructor/Operator Overloading. A snippet of the code is shown below.
In the code I am creating an object vec v2 and then creating a new object v4 and assign vec v2. Next I called the overloaded operator[] to change the values of v4[0] and v4[1].
My ... | The issue is the misuse of the std::memcpy function:
std::memcpy(&data, &(v.data), v.elements);
Since data and v.data are already pointers to the data, getting the address of those pointers results in the incorrect pointer values being used for those arguments.
The other issue is that the third argument v.elements shou... |
72,546,683 | 72,547,352 | Plus sign at the beginning of a new line and the code compiles | The code below is compilable (VS2019 and cpp.sh) whereas the last line begins with a "+". I noticed this bug when I saw that the header of my CSV file was missing a column. In C++, I just checked that this line of code is also correct : + 3 + 5 so it works with integers too (the + at the beginning of 3 might siganl tha... | The field delimiter type is char (integral type), so + s_fieldDelimiter is an int (the + sign is to signal that the number is positive just like in maths) and this last can be used to do pointer arithmetic since the string literal type is a "const char*".
|
72,546,764 | 72,546,908 | Is C++ implementation of executor finalized? How to compile it? | I'm trying to use C++ executor. This is the code I found in https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p0443r14.html. It should be supported by gcc 11.
I compiled this code with command
g++-11 main.cpp -ltbb
#include <iostream>
#include <execution>
using namespace std::execution;
int main() {
std::sta... | This is just a proposal for addition to the C++ standard. It was never adopted.
See https://github.com/cplusplus/papers/issues/102 regarding the progress of this proposal which was closed and https://github.com/cplusplus/papers/issues/1054 for the executor proposal which is currently still under consideration for C++26... |
72,546,934 | 72,560,526 | QImage loadFromData doesn't load the data of my images | I'm new to Qt and I have been trying to develop a simple video streaming application.
While developing my app, I've been facing a problem I thought could be ignored at first, but that's not the case. In fact, this problem is slowing down my whole application and is making it not working.
Here's my problem: When I'm try... | You haven't provided any value for the format parameter for loadFromData() (default value is nullptr) so most likely QImage tries to find a image header, doesn't find any and gives up, not being able to handle the following data.
The loader attempts to read the image using the specified format, e.g., PNG or JPG. If fo... |
72,547,193 | 72,567,289 | Optimal place to call __syncthreads() | Given that the code is correct, is there some potential performance benefit in calling __syncthreads as late as possible, as early as possible, or does it not matter? Here's an example with comments that demonstrate the question:
__global__ void kernel(const float* data) {
__shared__ float shared_data[64];
if ... | What you are facing is a split between where the writes are made and where they should be visible to the entire block.
NVIDIA has recently introduced a mechanism for just that: arrive + wait.
You start with initializing a barrier:
void __mbarrier_init(__mbarrier_t* bar, uint32_t expected_count);
Then you arrive at yo... |
72,547,211 | 72,547,259 | How to print out all the strings within an array within an ncurses window? | I'm trying to display an array of multiple random generated strings within a ncurses window. At first, I thought this was going to be simple and I can print the array as I would with any other array: putting it through a loop and displaying each string that it comes across within the array. When I tried this, all the w... | Don't use printf, use ncurses' functions like waddstr() instead.
|
72,547,643 | 72,548,391 | Using the same vertex array object for different shader programs | my goal is to pack all mesh data into a C++ class, with the possibility of using an object of such a class with more than one GLSL shader program.
I've stuck with this problem: if I understand it well the way of how in GLSL vertex data are passed from CPU to GPU is based on using Vertex Array Objects which:
are made o... |
additionally one can make an Element Buffer Object to store indices
another extra elements necessary to draw an object are textures which are made separately
Just to be clear, that's you being lazy and/or uninformed. OpenGL strongly encourages you to use a single buffer for both vertex and index data. Vulkan goes a s... |
72,547,644 | 72,554,541 | Pybind11 compiles with c++98 despite specification | I am trying to expose some c++ code to Python with pybind11. I specifically would like to enforce a certain c++ standard (say c++11), as the same .cpp file would need to be compiled on different systems. Following the official example to compile with setuptools in this repository, I modified part of the code as follows... | You did not build using C++98 on Windows.
You got confused because by default MSVC always reports __cplusplus as 199711, no matter what standard it is using, for compatibility reasons.
This behavior can be disabled with the /Zc:__cplusplus switch.
Alternatively, you can use _MSVC_LANG predefined macro. If it is defined... |
72,547,656 | 72,548,627 | TSAN thread race error detected with Boost intrusive_ptr use | Below code generates a TSAN error(race condition).
Is this a valid error ? or a false positive ?
Object is destroyed only after ref count becomes zero(after all other thread memory operations are visible - with atomic_thread_fence)
If I use a std::shared_ptr instead of boost::intrusive_ptr, then TSAN error disappears.
... | it seems using memory_order_acq_rel resolves the issue. (May be https://www.boost.org/doc/libs/1_72_0/doc/html/atomic/usage_examples.html example is in-correct)
friend void intrusive_ptr_add_ref(const Shared * x)
{
x->refcount_.fetch_add(1, boost::memory_order_acq_rel);
}
... |
72,548,027 | 72,548,303 | Compile same source with diffrent aliases | TLDR: Can you compile the same source code with different headers defining diffrent aliases?
I have created a library, with a set of functions coded using a couple of aliased type in the header.
algorithm_2d.h
using Point = Eigen::Vector2d;
using Vector = Eigen::Vector2d;
algorithm.cpp
Vector& scale_vector(
Vector... | Given the following template file: (call it algorithm.cpp.tmpl)
using Point = @_flavor@;
using Vector = @_flavor@;
#include "algorithm.cpp"
You can have CMake generate flavors automatically and build them as part of some_target:
set(FLAVORS Eigen::Vector2d Eigen::Vector3d)
foreach(_flavor ${FLAVORS})
string(MAKE_C_I... |
72,548,170 | 72,548,424 | Why using erase and unique function to remove duplicate vectors from a 2d vector is adding an extra empty vector in 2d vector? | I am using the below code to remove duplicate vectors from a 2d vector
sort(final_vec.begin(), final_vec.end());
final_vec.erase(unique(final_vec.begin(), final_vec.end()));
Can someone explain me why this is happening and what change should I make.
| To make it clearer what exactly is going wrong, I'm going to introduce an intermediate variable to store the iterator returned by std::unique.
Your code is equivalent to:
sort(final_vec.begin(), final_vec.end());
auto new_ending_iterator = unique(final_vec.begin(), final_vec.end())
final_vec.erase(new_ending_iterator);... |
72,548,689 | 72,549,678 | Why do `std::ranges::size` require a non-const method when using ADL? |
Otherwise, size(t) converted to its decayed type, if ranges::disable_sized_range<std::remove_cv_t<T>> is false, and the converted expression is valid and has an integer-like type, where the overload resolution is performed with the following candidates:
void size(auto&) = delete;
void size(const auto&) = delete;
1
... |
Why is there such a constraint of std::ranges::size? (Seems it's only
performed for non-member version.)
Although the size method does not modify the range, some ranges do not have a const-qualified member begin(), which allows only non-const-qualified objects to model a range.
This also makes some range adaptors in ... |
72,548,768 | 72,548,833 | How can I assign element-wise to a tuple using fold expressions? | I have a type effectively wrapping a variadic std::tuple like this:
#include <iostream>
#include <tuple>
template <typename ...Args>
struct Foo {
std::tuple<Args...> t;
Foo(Args&&... a)
: t{ std::forward<Args>(a)... }
{ }
Foo& operator +=(const Foo& f) {
std::apply([&](auto&&... ts) {... | lambda capture are const by default, you need to add mutable to mutate it.
std::apply([...ts = std::forward<decltype(ts)>(ts)](auto&&... fts) mutable { ... }
although I don't see why you capture it by value here, to me it seems like you actually want to capture them by reference.
std::apply([&](auto&&... fts){ ... }
|
72,548,868 | 72,549,373 | Remove duplicates from array C++ | Input: int arr[] = {10, 20, 20, 30, 40, 40, 40, 50, 50}
Output: 10, 30
My code:
int removeDup(int arr[], int n)
{
int temp;
bool dupFound = false;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(arr[i] == arr[j]){
if(!dupFound){
temp = arr[i];
... | Instead of trying to do everything at once, let us focus on correctness first:
int removeDup(int* arr, int n) {
// Note: No i++! This depends on whether we find a duplicate.
for (int i = 0; i < n;) {
int v = arr[i];
bool dupFound = false;
for (int j = i+1; j < n; j++) {
if (v == arr[j]) {
... |
72,549,449 | 72,549,538 | undeclared indentifier on the same scope C++ | Playing with C++ 20 modules, I have the following snippet:
export {
template<class T>
class Suite {
private:
std::vector<ConcreteBuilder<T>> things {};
};
template <class T>
class ConcreteBuilder : Builder<T> {
private:
// A collection of things of function ... | The compiler compiles the file from the top down, not all at once. It is hitting the definition of std::vector<ConcreteBuilder<T>> before it gets to the definition of class ConcreteBuilder.
So, you need to move your definition of Suite after the definition of ConcreteBuilder, so the compiler knows what it is when you u... |
72,549,463 | 72,549,714 | Compiling with PGI PGCC with LAPACK and LBLAS libraries? | I'm trying to compile my OpenACC parallel C++ program that makes use of dgemm (BLAS) and dgesvd (LAPACK) functions.
I'm trying to compile the program with PGI PGCC compiler, linking it with the libraries like this (the program is called "VD"):
# Target rules
LIBRARIES := -lblas -llapack -lm
CC = gcc
CFLAGS = -O3
PG... | The BLAS and LAPACK are written in Fortran, hence the error you’re seeing is due to missing the Fortran runtime libraries on the link line.
To fix, add “-fortranlibs” on your link line so these libraries are added.
|
72,549,590 | 72,549,749 | Constructer Calling order | I know when a constructer is being called, then it gets created in the memory, and when it gets out of the block it gets destroyed unless it's static.
Know I have this code:
#include <iostream>
#include <string>
using namespace std;
class CreateSample
{
private:
int id;
public:
CreateSample(int i)
{
... | CreateSample o5(5); calls the constructor CreateSample(int). fuct2(o5); and CreateSample o6 = o; call the implicitly-defined default copy constructor CreateSample(CreateSample const&). All three of these variables (o6, o, and o5) call the destructor ~CreateSample() when their scope is exited.
The fix is to follow the r... |
72,549,715 | 72,550,021 | Which undefined behavior allows this optimization? | I'm working on a virtual machine which uses a typical Smi (small integer) encoding where integers are represented as tagged pointers. More precisely, pointers are tagged and integers are just shifted.
This is the same approach as taken by V8 and Dart: https://github.com/v8/v8/blob/main/src/objects/smi.h#L17
In our impl... | It's simple: dereferencing invalid or null o would cause UB, so after the dereference, o supposedly can't be null.
Calling is_smi() counts as dereferencing, even if it actually doesn't access the memory.
Make is_smi() a free function (since this only applies to this, not pointer parameters). I'd also make Object an opa... |
72,549,927 | 72,550,033 | Casting operator ignored? | Having such simple code:
DWORD i = 0xFFFFFFF5; // == 4294967285(signed) == -11(unsigned)
if((unsigned)i == -11)
OutputDebugString(L"equal");
else
OutputDebugString(L"not equal");
The condition is meet - i'm getting "equal" output.
My question is WHY is that happen since in the condition we have
f... | DWORD is unsigned or equivalent, a 32-bit unsigned integer in your C++ implementation. DWORD i = 0xFFFFFFF5; initializes i to FFFFFFF516 = 4,294,967,285.
In (unsigned)i == -11, i is converted to unsigned, which yields the same value, 4,294,967,285. The other operand, -11, has type int and value −11.
When two numbers ar... |
72,549,975 | 72,549,989 | c++ code will not return my trigonometry table (beginner) | I am currently in an introduction to programming class, and still don't know much. My current assignment is to write a program that returns a table that gives the cosine, sine, and tangent for every 15 angles from 0 to 90. I don't believe my code has any bugs, but the code won't run. I'm not sure if my computer is just... | Here's a bug
while (ang_deg < 91);
should be
while (ang_deg < 91)
Your version is an empty while loop, because the loop is empty ang_deg never changes and so the loop never terminates. That's why your program seemed not to run (in fact it did run, but it never finished).
Sometimes the smallest things can be errors.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.