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 |
|---|---|---|---|---|
62,638,946 | 62,638,998 | How can I point to data in a file? | So, I've been trying to understand compression for a while, read some articles, watched some videos and the video with the best explanation said that you need to make data point to identical data. I didn't understand this part very good. I have good knowledge of pointers and how they work, but I still don't understand ... | A file is an "array" of bytes. While you cannot have a pointer to this array, you can use the other form of referring to an array element: The index. That is, if the data begins on the third byte of file, then all that you need to locate the data is the name of the file and index of the byte which is 2.
|
62,639,242 | 62,639,426 | Weird bug while reading a file C++ | When I save the playingBoard array, save prints it properly, however when I try importing the file which save created with import, I get weird output - spaces get removed and replaced with 1s with no obvious logic. (examples are provided below)
minimal reproducible example:
#include <iostream>
#include <fstream>
class... | Your problem is that by default, whitespace is skipped with operator >>. You need to use another method of extracting the characters from your file such as the get member function (example below, tested with gcc-9.3.0).
bool import(std::string filename)
{
std::ifstream ifs {filename};
if (!ifs.is_open())
... |
62,639,377 | 62,644,292 | Gtkmm constantly check if the selected date on Gtk::Calendar changes | I have a calendar and next to it I have a list store with events/tasks with deadlines for each task, I want to create a function that constantly checks if the selected date on the calendar changes, so I can sort my events based on the date chosen by the user, I know how to retrieve the date using:
unsigned int y, m, d;... | You have 2 different options:
Listen to the signals that are emitted when a user changes the date. In the callback you provide, you can update your list. For example, calendar.signal_month_changed().connect(your_callback)
Listen to changes of the "year", "month" and "day" properties. For example, calendar.prop_year()... |
62,639,652 | 62,724,451 | File pointer does not works when moved to a class? | So I found this solution to call a python script and it works in Microsoft Visual Studio Professional 2019 Version 16.6.2. I moved the three methods into a separate class and it no longer works. I thought I could figure it out but have just been beating myself up so I am here asking for help from readers who are much ... | You tripped over a non-static member function having a hidden this parameter and not matching the prototype expected for a deleter function.
Instead of void (*)(std::File*), the proposed deleter looks something like void (iTool::*(std::File*)
You can solve the problem by wrapping the function call with a lamda expressi... |
62,639,811 | 62,640,119 | Advantages of arrow syntax in function declaration | what are the advantages of using
template <typename L, typename R>
auto getsum(L l, R r) -> decltype(l + r) {return l + r;}
over
template <typename L, typename R>
auto getsum(L l, R r) {return l + r;}
isn't it compiled into the appropriate type during template instantiation?
|
what are the advantages of using [trailing return type syntax] ?
A possible advantage: the trailing return type is SFINAE friendly.
Your getsum() function, with trailing return type (-> decltype( l + r )), is enabled only when exist an plus operator between l and r.
If you call it with a couple of arguments that does... |
62,640,083 | 62,640,375 | I am looking to define two library with different names that use the same code | I have a c++ library which has an function called ExampleFunction(). This function is documented and is already in use. Unfortunately, the style of the library requires this function to be called exampleFunction() {initial letter is lowercase}.
I need to keep the old name for backwards compatibility but add the new nam... | You could rename the existing function that actually has the implementation to exampleFunction(), since that's what it should be. Then, so users of the old name 1) still have working code, and 2) are told that there's a newer function name to use, you can do this:
[[deprecated("Use exampleFunction() instead")]]
inline ... |
62,640,146 | 62,672,480 | Build only part of a git submodule repository with CMake | I have a C++ project with submodule another_repo:
.
├── CMakeLists.txt
├── ext
│ └── another_repo
│ └── CMakeLists.txt
├── include
└── src
I would like to build only part of another_repo. That said, I need a new, customized CMakeLists.txt to build another_repo, instead of using its original one ./ext/another_r... | If you want to build only a part of another_repo then just create a new target which only build the part you want.
For e.g, another_repo has following files:
another_repo/
│── a.cpp
│── b.cpp
│── c.cpp
And you want to build only a.cpp and b.cpp (assuming they don't depend on c.cpp).
In you root directory CMakeLists.tx... |
62,640,285 | 62,640,633 | Memory leak when using fortify static code analyser for unique_ptr | Using std::unique_ptr in c++11 in fortify Static Code Analyser is giving me a memory leak.
void *httpServerThread(void *arg)
{
std::unique_ptr <int> i(new int(1));
return NULL;
}
Meanwhile, the below code shows no memory leak.
void *httpServerThread(void *arg)
{
int * i = new int(1);
delete i;
... | There is no memory leak in the shown function. The message is a false positive.
Since there is no std::make_unique, there is no way to create std::unique_ptr without new.
Note that you can write your own make_unique. Sure, that function has to use new, but nothing else does.
|
62,640,609 | 62,648,643 | Resolving functions at runtime, not at compilation C++ | I'm writing code in C++ using Visual Studio (2017) and trying to use functions from a 3rd party library.
I have been told that "[library] doesn't provide a linker library, so you need to resolve the functions at runtime, not at compile time".
How can this be done in Visual Studio?
Thanks
Edit: obviously I tried googlin... | If you just need a couple functions
HMODULE hMod = LoadLibrary("C:\\lib\\path\\library.dll");
void* fnPtr = GetProcAddress(hMod, "nameOfExportedFunction");
To call the function you need to know the calling convention and the arguments, here is an example of how to do it:
typedef void* (__cdecl* _Cvar_Get)(const char* ... |
62,640,727 | 62,654,456 | RenderDoc does not show buffer contents while debugging Vulkan | I'm building a game engine which for now is made to render a basic triangle on the screen. It uses a color attachment, depth attachment and the swap chain image view when creating the frame buffer and the render pass is created supporting for those attachments. Vulkan does not show any validation error messages while c... | I found what the error was. I completely forgot that the maximum and minimum bounds are 1.0f and -1.0f. I unintentionally make the z index -1 which renders it on the boundary. Changing it to 0.0f fixed the issue.
Thanks everyone!
|
62,640,742 | 62,640,998 | How to stop a C++ blocking read call | I'm reading CAN-BUS traffic under SocketCAN and C++ in GNU/Linux. I've found that the read call is blocking, and I'm struggling to figure out how to stop my program properly when I don't want to keep reading.
Of course, I could hit Ctrl+C if I've invoked the program from the terminal, but the point is to find a way to ... | Read is always blocking... you want to only read if data is waiting... so consider doing a poll on the socket first to see if data is available and if so THEN read it. You can loop over doing the poll until you no longer want to read anymore...
bool pollIn(int fd)
{
bool returnValue{false};
struct pollfd *pf... |
62,641,187 | 62,645,587 | Boost, get UTC time in minutes precision | I want the UTC time in minutes and I don't want seconds. I am doing...
auto timeUTC = boost::posix_time::second_clock::universal_time();
std::cout << to_iso_extended_string(timeUTC) << std::endl;
This will print the time as 2020-06-29T23:06:30
I want the seconds part to be removed form the ptime object, example 2020-0... | You can use a custom facet and just drop the "seconds" flag (%S) from the format:
#include <iostream>
#include "boost/date_time/posix_time/posix_time.hpp"
using boost::posix_time::time_facet;
int main()
{
auto timeUTC = boost::posix_time::second_clock::universal_time();
std::cout << "iso extended string: \n\t"... |
62,641,364 | 62,641,483 | C++ division of unsigned shorts results in int | Why is the result of the division of two unsigned short of type int in C++? I have created an example which can easily be tested in e.g. http://cpp.sh/
// Example program
#include <iostream>
#include <string>
#include <typeinfo>
int main(){
unsigned short a = 1;
unsigned short b = 1;
auto c = a/b;
std::cout<<... | From Implicit conversions / Numeric promotions / Integral promotion:
prvalues of small integral types (such as char) may be converted to prvalues of larger integral types (such as int). In particular, arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically appl... |
62,641,368 | 62,641,605 | std::find, alternative method that returns all found values instead of just the first for vector where duplicate exists | I've been doing some testing with std::find in vectors with duplicate values
I have noticed that std::find will always return the first value out of a duplicate e.g. when I look for the value 2 in the vector vecDup:
std::vector<int> vecDup = { 0, 5, 1, 2, 2, 4 };
auto valIterator = (std::find(vecDup.begin(), vecDup.en... | If I have you correct, you want to have different iterator pointing to every duplicate of a particular element in the vector. Then, always go for the good ol' for loop:
std::vector<std::vector<int>::iterator> vec_of_dup_iters;
auto it = vecDup.begin();
for(it = std::find(it, vecDup.end(), elem); it != vecDup.end(); it ... |
62,642,158 | 62,642,231 | No matching function to call: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘f (...)’, e.g. ‘(... ->* f) (...)’ | I'm trying to call a non-static member function from a thread pool. The submit function tells me error: must use ‘.’ or ‘->’ to call pointer-to-member function in ‘f (...)’, e.g. ‘(... ->* f) (...)’ for the std::future<decltype(f(args...)) portion on the first line. I'm trying to not create a static function. I've trie... | To correctly get the result type of a call to a member function or a normal function you must use std::invoke_result_t:
auto submit(F&& f, Args&&... args) -> std::future<std::invoke_result_t<F, Args...>> {
// ...
}
That way, both member function and non member function will work.
Consider that when sending a membe... |
62,642,405 | 62,642,532 | dynamic_cast<> question using Stroustrup example | I'm testing a dynamic_cast<> example in Stroustrup C++ 4th Ed Page 642 and it does not compile. I'm using the following picture directly from the book trying to learn how it works. Does anyone know if this is Eratta (its not in his published errata doc) or I have misread something?
Stroustrup Graphic, dashed line repr... | The error explains what is wrong. Dynamic cast is only allowed for polymorphic types (except when casting upwards in inheritance hierarchy).
A class is polymorphic only if it has at least one virtual function. I does not have any virtual functions. Therefore it is not polymorphic. You must add a virtual function to I i... |
62,642,473 | 62,642,902 | QPainter set QBrush to drawText in QT/C++ | I posted before about text not displaying - I got that working but by a slightly different method - setting a stylesheet(around the constructor). The thing is - I am trying to set up a fadeout by setting the brush color to a calculated and decreasing fraction of the total color at initial display(#bbbbbb). What I see... | qt use QPen for drawing text. Set a pen instead of brush for QPainter:
painter.setPen(QPen(QColor(iColorComponent, iColorComponent, iColorComponent), Qt::SolidPattern));
painter.drawText(245, 330, 125, 15, Qt::AlignCenter, tr("Ready"));
|
62,642,541 | 62,642,776 | C++: Need help understanding operator-overloading error | I got this code:
1 #include <iostream>
2 using namespace std;
3
4 class B {
5 private:
6 int n;
7 public:
8 B(int x) : n(x) {}
9 B operator +(B& b) {
10 return B(n+b.n);
11 }
12 friend ostream& operator <<(ostream &out, const B& b) {
13 out << "B: " << b.n;
14 return out;
... | The result of (b2 + b3) is a temporary. That is it's an object of type B that is created and destroyed as part of executing the larger expression.
C++ has a rule that you cannot bind a non-const reference to a temporary. But that is exactly what your code was trying to do. Hence the need for const.
Incidentally the cor... |
62,642,741 | 62,642,888 | std::bad_variant_access error when trying to store value to std::variant in map | I'm parsing a file into a map with std::variant (to support two types of values) and I can't figure out the right way to store the value into the map.
I'm getting an:
std::bad_variant_access
what(): unexpected index
This is the map definition:
typedef struct op{
std::string name;
map<std::string, std::variant<uin... | You are looking for std::variant::emplace(). In you code:
if (key.compare("factor") == 0){
op.params[key].emplace<float>(std::stof(value));
} else {
op.params[key].emplace<uint16>(std::stoi(value));
}
But I don't know what uint16 is – are you actually using uint16_t?
|
62,642,804 | 62,642,948 | What happens when std::move() is called without assignment | What happens when I just use std::move without any assignment?
std::string s = "Moving";
std::move(s); //What happens on this line to s?
//is s still valid here?
| std::move() doesn't move the passed object by itself; it just possibly enables move semantics for the object. It consists of a cast whose result you can use to select – if possible – the proper overload that supports move semantics. Therefore, in your code:
std::string s = "Moving";
std::move(s);
std::move(s) above ca... |
62,642,869 | 62,642,932 | Scope of objects created inside a function - Will they be valid if references are stored and accessed outside the function? | The following code works. But i am not sure if it is really OK to write it this way.
class A {
private:
struct packet {
string header;
string data;
}
vector<packet > packets;
public:
void add_packet(string h, string d) {
struct packet p1; // Isnt this variable on stack and will be des... | You cannot judge what a function will do with a parameter just by it's signature. Even though you are calling
void push_back (const value_type& val);
push_back is actually going to make a copy of val and store that copy in the vector. This means there is no dangling reference.
|
62,643,765 | 62,643,885 | how to use array data member of struct in main in C++? | If i have a struct Emp have 2 data member no_of_emp[5]; and department_name how i use no of emp array in main i am little confuse about please help me. may be my question are not good.
struct emp
{
int no_of_emp[5];
string department_name;
}
| You can use it in your main with brace initialisers:
std::vector<emp> employers =
{
{
{0, 1, 2, 3, 4},
"department1"
},
{
{5, 6, 7, 8, 9},
"department2"
}
};
then you can use your list of employers, for example:
for (const auto& x: employers)
{
for (const auto num: x... |
62,643,867 | 62,646,033 | How to resolve error 'overriding virtual function has less restrictive exception specification than base class virtual member function' | I know this 'If a virtual function has an exception-specification, all declarations, including the definition, of any function that overrides that virtual function in any derived class shall only allow exceptions that are allowed by the exception-specification of the base class virtual function.'
But the problem is I a... | In the base class the line virtual LONG A() throw() means that a function A is introduced that takes no parameters and returns LONG. The function is specified to not throw exceptions. In modern C++ you would replace throw() with noexcept.
In your derived class the function is overriden as LONG A(). This function also t... |
62,644,023 | 62,644,103 | Loops not executing in functions C++ | Here's my code. Whenever I run the program, I expect that the cout statement in the for loop in the function Binary() to execute. But whenever I input something, it gives me 0
#include<iostream>
#include<math.h>
using namespace std;
long int Binary(int x){
int temp=0,res=0;
for(int i=x;i<0;i--){
temp... | I think the condition in your for loop is the opposite way round than your expect it. You seem to want it to continue looping until i<0. But it will actually loop while i<0. The condition is already not true when you enter the loop, so it will finish immediately without doing any iterations.
|
62,644,070 | 62,644,127 | Differences between std::is_convertible and std::convertible_to (in practice)? | According to en.cppreference.com (from what I can gather):
std::is_convertible is a trait class requiring types From & To to be such that a function with return type To that returns a From value can compile.
std::convertible_to is a concept requiring types From & To to be as explained above, AND such that an r-value r... | std::is_convertible<From, To> (the type trait) checks is type From is implicitly convertible to type To.
std::convertible_to<From, To> (the concept) checks that From is both implicitly and explicitly convertible to To. It's rare that this is not the case, such types are ridiculous, but it's nice in generic code to just... |
62,644,163 | 62,648,353 | How to make a more complex wxWidgets save system | I'm making a desktop app with wxWidgets but I can't figure out how it can have a more complex save system. For example, a project in Sony Vegas is saved in one file, and it's a (.veg). My save system will have to save mostly text from user, but in different areas. To be able to do this, do I need to save each thing I n... | Saving data to one or more files depends on how you organize your app.
It may read data from a file only when needed. Different tasks may use different files.
It may store everything in a single file. Read it all once. Or read parts of it for different tasks. If the file is too much big (my opinion, greater than 50 MB... |
62,644,361 | 62,644,779 | C++: What is the order of destructor call with methods? | I got this code:
Edit: The full code:
#include <iostream>
using namespace std;
class A {
public:
A() {}
A(const A& a) {
cout << "A copy ctor" << endl;
}
virtual ~A() {
cout << "A dtor" << endl;
}
virtual void type() const {
cout << "This is A" << endl;
}
}... | When you do f(*pa).type();, the Copy Constructor of A is called with an A object, so it will create an A to pass into your f function. When f returns, it is a different A being returned, since it's not by ref, however, it is NOT immediately destroyed, and instead uses copy-elision to stick around until after the .type(... |
62,644,557 | 62,645,348 | Linking SDL2 with CMake | I'm having problems linking SDL2 to my project, which probably are because I'm new to CMake, and I don't fully know how to create new projects with it. Every time and method I've tried to fix this problem has resulted in one of the following problems:
"Cannot locate WinMain@16"
Multiple undefined reference errors
unde... | Oof. Everything about your CMakeLists is wrong.
Never set CMAKE_CXX_FLAGS in your CMakeLists.txt
Never use include_directories or link_directories
Never use target_link_libraries without a visibility specifier.
Never set paths to libs manually.
Don't set your target names equal to the project name. It's pointless comp... |
62,645,464 | 62,654,053 | Trying to understand error upon using deleted on imported static method | I am trying to understand behavior of pointer in my code here, my question is toward the bottom code that i have commented out and None of the information I found answered following question that I have. My questions is why compiler giving me error that uninitialized variable app is used, and also what will be the goo... | Thanks for everyone's contribution
Test::Application app;
app.Run();
^ This works because it's not a pointer, it's an object which is initialized.
Test::Application* app;
app->Run();
^ This does work, and it made me confused because it is working, and visual studio is not giving any warning or error either, its a beg... |
62,645,630 | 62,645,753 | Specify function return type as template parameter in c++ | I'm trying to give my function a return type of its template parameter(to improve type checking), which is a function reference.
Here is what I have attempted so far:
#include <Windows.h>
template <typename func>
decltype(auto) proxyFunction(LPCSTR dllPath, LPCSTR functionName){
auto funcType = decltype(func);
... | Your func template parameter is already the type you want to return, so just use it as-is, there is no need to use decltype(auto). And your use of auto funcType = decltype(func); is just plain wrong.
Try this instead:
template <typename funcType>
funcType proxyFunction(LPCSTR dllPath, LPCSTR functionName)
{
funcTy... |
62,646,053 | 62,648,539 | GitHub repository created but unable to upload VS solution | I tried uploading a C++ project from Visual Studio 2019 onto my GitHub account.
The repository gets created when I do this however, none of my codes gets uploaded onto the repository.
Only the files ".gitattributes" and ".gitignore" appear in my repository.
Please could I have any suggestions on what I could do to fix ... | Close VS
Go to your local repository folder (the solution folder)
This will add all the files and commit them
git add .
git commit -m 'added files'
alternatively you can use "git add ___" to add one file at a time
Make sure you commit the changes and then do
"git push"
Re-open VS and everything should be setup now.
He... |
62,646,177 | 62,646,422 | Doees the 'this' pointer participate in a virtual function's polymorphic behavior | I'm implementing the Visitor pattern, and I have an accept() function that is only defined in the base visitable class. This system works just fine, but Alexandresku states in his book that the this pointer has static typing.
Is this code flawed and/or has a bug, but my output is not catching it?
I have tried to change... | This isn't actually working like you think it's working. The only visitor being called is void WidgetVisitor::visit(Widget& w) but since the Widget::text() method is virtual, all of the visitor methods effectively have the same behavior.
Change the implementations to output the name of the reference argument's type an... |
62,646,491 | 62,646,756 | Why does numeric_limits<atomic<X>> not fail to compile? | I just created a bug by testing a value against the following expression:
std::numeric_limits<decltype(allocationCount)>::max()
In this context, allocationCount is a std::atomic<std::size_t>.
Apparently, the above mentioned expression compiles and evaluates to 0 on both Clang 10 and GCC 10:
#include <atomic>
#include ... | This is the default behavior. From [numeric.limits]
For all members declared static constexpr in the numeric_limits template, specializations shall define these values in such a way that they are usable as constant expressions.
The default numeric_limits<T> template shall have all members, but with 0 or false valu... |
62,646,976 | 62,647,153 | How to have access using pointers on two type definition vectors | I'm trying to learn how I can use the different typedef vector, and after creating them how I can access the variables. I have commented as I wrote the code
#include <iostream>
#include <vector>
//#include <stdlib.h>
using namespace std;
//Here I wanted to created a structure where I ... | Here is the code that would work (assuming A and B are the same length):
size_t jj = 0;
for (List::iterator it = A.begin(); it != A.end(); it++) {
cout << it->pos<<endl;
cout << (B.begin() + jj)->pos<< endl;
jj++;
}
Note that A and B are not pointers so you access their methods normally. By the way, if y... |
62,647,060 | 62,647,159 | How can I conditionally instantiate an object? | I'm trying to do some conditional work like so:
Type object;
if (cond) {
doSomeStuff();
object = getObject();
doMoreStuff();
} else {
doSomeOtherStuff();
object = getDifferentObject();
doEvenMoreStuff();
}
use(object);
The only way I can think of solving this is the duplicate the use code (whic... | You can use an IIILE (immediately invoked initializing lambda expression):
auto object = [&] {
if (cond) {
doSomeStuff();
auto object = getObject();
doMoreStuff();
return object;
} else {
doSomeOtherStuff();
auto object = getDifferentObject();
doEvenMoreStuff();
return object;
}
}(... |
62,647,338 | 62,647,540 | C++ Warning: Assigning newly created gsl::owner<> to non-owner | When I use the following code, I get a warning (From applying cppcoreguideline).
Code:
SampleClass *object = nullptr;
object = new SampleClass();
Warning:
warning: assigning newly created 'gsl::owner<>' to non-owner 'SampleClass *' [cppcoreguidelines-owning-memory]
When I searched and get to this link
https://rele... | gsl::owner<T*> is meant to designate that whoever holds this object is the owner of the underlying T object and is responsible for freeing the memory later. Note that an explicit delete operation is still required — the GSL annotation is meant to assist static analysis tools. (For more on ownership, see this post.)
Whe... |
62,647,589 | 62,649,375 | Deducing a template function within a template function (using C++ concepts) | This code leads to an error, error: no matching function to call to 'put'.
#include <concepts>
#include <type_traits> // for is_invocable_r_v
#include <iostream>
template <typename T>
T add(T a, T b)
{
return a + b;
}
template <typename T, typename F>
requires std::is_invocable_r_v<T, F, T, T>
void put(T& r,... | with an extra overload you get the compiler to resolve add and you still support function objects.
template <typename T>
T add(T a, T b)
{
return a + b;
}
template <typename T, typename F>
requires std::is_invocable_r_v<T, F, T, T>
void put(T& r, T a, T b, F f)
{
r = f(a, b);
}
template <typename T>
void... |
62,647,907 | 62,648,208 | Why would an incorrect memory allocation to a buffer only cause crashes when compiled in Release mode and not in Debug mode? | This is my first ever project that I've managed to complete so I'm a bit unsure of how to reference an executable vs a project being worked on and debugged in "debug mode" or whether there's multiple ways to do so etc, etc.
To be more specific, however, I encountered a heap corruption issue that only occurred when Visu... | Docs explain the behavior:
When you request a memory block, the debug heap manager allocates from the base heap a slightly larger block of memory than requested and returns a pointer to your portion of that block. For example, suppose your application contains the call: malloc( 10 ). In a Release build, malloc would c... |
62,647,948 | 62,680,009 | How to sort data in decreasing order of cgpa in structure with dynamic memory allocation? | Structure and DMA. I want to retrieve all the inserted record in decreasing order of cgpa.
Without sorting it give the result as shown below image.
#include<iostream>
#include<string>
using namespace std;
struct student {
string name;
int age;
float cgpa;
};
void main()
{
student *ptr;
int size;
... | #include<iostream>
#include<string>
using namespace std;
struct student {
string name;
int age;
float cgpa;
};
void main() {
student *ptr;
int size;
cout << "enter size \n"; cin >> size;
ptr = new student[size];
for (int i = 0; i < size; i++)
{
cout << "enter student " << i +... |
62,648,265 | 62,648,294 | Binary Exponentiation is not working properly when the base is a float/double | I learned how to implement binary exponentiation in c++ from this site. I used the recursive algorithm:
long long binpow(long long a, long long b) {
if (b == 0)
return 1;
long long res = binpow(a, b / 2);
if (b % 2)
return res * res * a;
else
return res * res;
}
In my situation,... | You are converting the result of binpow to a long long here:
long long res = binpow(a, b / 2);
which changes the result.
Instead, you need to do:
double res = binpow(a, b / 2);
or even better
auto res = binpow(a, b / 2); // so res has the same type that binpow returns
which fixes the issue. Here's a demo.
|
62,648,339 | 62,648,519 | Cap'n'proto premature destruction of interface? | Let's say I have a streaming API like this:
interface MyInterface {
addListener @0 (listener: Listener) -> (registration: RegisteredListener);
interface Listener {
update @0 () -> stream;
}
interface RegisteredListener {
}
}
I'm having a challenge where the destructor for the server implementation of My... | I recommend having Registered class hold a MyInterface::Client pointing to the parent, in addition to the plain pointer it currently holds.
MyInterfaceImpl *parent_;
MyInterface::Client ownParent_;
uint64_t id_;
This ensures that as long as a Registered still exists, the MyInterfaceImpl won't be destroyed.
Inside the ... |
62,648,411 | 62,648,488 | Spaceship Operator on NaN | How does C++ treat floating-point NaN when doing space-ship comparison operations? We know that the usual compares always return false, so how does this change with NaN?
std::numeric_limits<double>::quiet_NaN() <=> std::numeric_limits<double>::quiet_NaN()
| According to cppreference, in the case of floating point arguments to the built-in <=> operator:
[...] the operator yields a prvalue of type std::partial_ordering. The expression a <=> b yields
std::partial_ordering::less if a is less than b
std::partial_ordering::greater if a is greater than b
std::partial_ordering:... |
62,648,419 | 62,649,330 | WinAPI Creating a second dialogbox after clicking a button control on the first dialogbox and destroying the first | I'm trying to make a second dialogbox prompt the user after they click OK on the first dialogbox while destroying the first dialogbox in the process.
This is my first dialogbox that pops up after the user click a button on the main window itself.
void displayDialogW(HWND hWnd)
{
HWND hDlg = CreateWindowW(L"myDialog... | The second dialog cannot have the first dialog as a parent if that's going to be destroyed right away. You could, instead, open the second dialog with the parent set to the same parent as the first one, then the first dialog can be safely destroyed.
case IDOK: // assuming hWnd i... |
62,648,607 | 62,667,107 | Should Qt builds run on other computers? | I made a desktop application based on Qt 5.12 on Debian 10 32 bits. Because Qt 5.12 isn’t available via apt-get (I need 2D chart features introduced on 5.12) I compiled Qt from source.
That application is supposed to run on another computer, also Debian 10 32 bits. So I copied the required Qt dependencies from the deve... | Qt, like other shared libraries, need not be compiled on each computer. It is fine to compile on one machine and then deploy to other machines; this is what distributions such as Debian do.
However, having said that, if you're going to deploy the application to multiple machines, you'll want to do more packaging than ... |
62,648,718 | 62,648,754 | Why move() of string changes underlying data position in memory? | I'm trying to save some string via string_view to second data container but run into some difficulties.
It turns out that string changes its underlying data storage after move()'ing it.
And my question is, why does it happen?
Example:
#include <iostream>
#include <string>
#include <string_view>
using namespace std;
in... | What you are seeing is a consequence of short string optimization. In the most basic sense, there is an array in the string object to save a call to new for small strings. Since the array is a member of the class, it has to have it's own address in each object and when you move a string that is in the array, a copy ha... |
62,648,759 | 62,649,017 | about function typedef in c++ | typedef bool list_less_func (const struct list_elem *a,
const struct list_elem *b,
void *aux);
void
list_sort (struct list *list, list_less_func *less, void *aux)
{
size_t output_run_cnt; /* Number of runs output in current pass. */
ASSERT (list != ... | You are calling an uninitialized function pointer. That causes undefined behavior. You have to define a function and assign the function's address to the function pointer:
struct list_elem {};
typedef bool list_less_func (const list_elem *a,
const list_elem *b,
... |
62,649,111 | 62,649,156 | Writing multiple lines to a .txt using a loop | The assignment calls for me to use nested loops to write to a textfile. I am sure it has something do with the way I am opening and closing the ofstream object within the nested loops but I am stumped as to where/why.
Martha 1 1 1 1
Leela 2 2 2 2
Jorge 3 3 3 3
But instead I am getting
Martha 1 1 1 1Leela 2 2 2 2Jorge ... | You aren't adding a new line anywhere. You need to outFile << '\n' after the second loop
outFile.open("C:\\data\\agentSales.txt");
for (numRealtor; numRealtor > 0; numRealtor--) {
std::cout << "\nEnter realtor's name: ";
std::getline(std::cin, realtorName);
outFile << realtorName;
for (... |
62,649,356 | 62,650,156 | How to properly cast char ** x to const char ** | I have the following variable.
char **arr
Then I want to perform some modification on array which means it can't be declared as a constant.
Now I have a function that accepts the argument of type const char ** arr. But I have no control over the signature of this function.
Now when I cast arr to const char ** arr g++ g... | Allowing a cast from char** to const char** provides a loophole to modify a const char or a const char*.
Sample code:
const char c = 'A';
void foo(const char** ptr)
{
*ptr = &c; // Perfectly legal.
}
int main()
{
char* ptr = nullptr;
foo(&ptr); // When the function returns, ptr points to c, which is a const... |
62,649,633 | 62,649,668 | push_back copy objects even for temps although stating otherwise in it's definition? | one of push_back definition is
push_back(const value_type& __x)
so Having my_vector2.push_back( obj ); will result in passing object obj by reference( No copy during passing object) still it call the copy constructor in the body of push_back somewhere so why not just pass it by value ie;
push_back(const value_typ... | push_back predates move semantics, so the best std::vector can do is copy. While it could have changed with C++11, this would also be a change of behavior, which might break code in some cases (weird cases, but still valid ones).
If you want to avoid copies when dealing with temporaries, then you actually want emplace... |
62,649,664 | 62,650,158 | How to remove 'all duplicated ' values? | There`s a lot of tutorials exist for removing duplicate values and I have checked all
like
{1,2,3,4,1,2,3,4,5} -> {1,2,3,4,5}
by using sort(), unique() function.
but if I want to remove 'all duplicated' values
like
{1,2,3,4,1,2,3,4,5} -> {5}
How to implement it?
I have manually split the original vector into two parts ... | #include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> list = { 1,2,3,4,1,2,3,4,5 };
vector<int> rest;
for (int i = 0; i < list.size(); i++) {
int count = 0;
for (int j = 0; j < list.size(); j++) {
if (list[i] == list[j]) {
count... |
62,650,034 | 62,657,935 | Stuck in loop during std::getline and std::cin during while loop | So I'm new to C++ and I'm supposed to get a vector in integers from stdin. I tried using std::cin and std::getline and other functions, but everytime I try entering a sentinel (e.g. not an integer) or when there is a "count" variable that reaches an increment, I end up in a hung state. I can enter inputs, but no more p... | cin controls input from a stream buffer, which put your input characters in a stream buffer, then it was passed to getline.
cin ends input when you signaled EOF with Ctrl+D, Ctrl+Z, or Enter.
See this link
detecting end of input with cin.
getline extracts characters from input and appends them to str until it meet one... |
62,650,304 | 62,660,963 | How do I remove element pointed to by iterator in a C++ list? | How do I remove element pointed to by iterator in a C++ list? why does not this work?
int main()
{
list<int> l;
l.push_back(5);
l.push_back(6);
for(auto &it: l)
{
l.erase(*it);
}
return 0;
}
| Why
for(auto &it: l){
l.erase(*it);
}
fails to work:
it is not an iterator. In a range-based for loop, the variable declared before the colon, the range_declaration, will receive an item in the container, an int in this case. Since it will receive an int, auto will infer a type of int resulting in
for(int &it: l)... |
62,650,516 | 62,651,298 | How to write outline constructor that has been inheritance? | I'm trying to write OUTLINE inheritance constructor in c++.
I am not sure that's possible.
I have only written inline inheritance constructor.
If there are some way to write, can you share it.
Thanks.
Here's my code.
18 public:
19 FullTimeEmployee(int eid, string name, int salary):Employee(eid, name);
20 ... | on the line 19, you don't have to declare to add the derived :Employee(eid, name) anymore. simply make it like this
FullTimeEmployee(int eid, string name, int salary);
so the code would probably like this if it is a whole program
#include <iostream>
using namespace std;
class Employee{
public:
Employee(int... |
62,650,577 | 62,651,040 | How to encapsulate a function so that it can be called by only one other function within the same class? | There is a function that we would like only one other function to be the sole caller of:
void bar(){
}
void foo(){
}
void baz(){
}
All three functions are located within the same class. We would like foo() to be able to call bar(), but not allow baz() to call bar().
So far, this answer seems to suggest the soluti... | There are basically 6 areas where you can find out, which function is calling which or is called by another function.
Potentially by the linker
Definitely by the compiler
By the editor. A smart editor can show cross references
By 3rd party static code analysis tool
Unfortunately not by the C++ language with the code a... |
62,650,865 | 62,651,910 | Can we use iOS framework like coremotion in c++ code | I need to build a library in C++, which have to get data from motion sensors. And then library in both android and iOS. It looks like it is possible to do it for android but I am struggling to find an answer for iOS.
| You would be needing bridges for ios and android separately. Like for android you need different wrapper / JNI Bridge and different wrapper for ios Objective-c (.mm) files to used the sensor values. Ofcourse you can't share the sensor its different for each platform.
You can check this open source repository to get an ... |
62,651,055 | 62,672,229 | Will the old_head be updated after the 'do-while'loop and before 'while' loop? | In 《c++ concurrency in action》page 217,
Will the old_head be updated after the do-while and before while?
Then the hazard pointer is set to the wrong old_head?
| You have two nested loops:
node* old_head = head.load();
do {
node* temp;
do {
temp = old_head;
hp.store(old_head); // write hazard pointer
old_head = head.load(); // reload head to ensure it has not changed
} while (old_head != temp); // if head has changed -> retry
// try to remove head
} while (ol... |
62,651,366 | 62,651,630 | How to use int point to struct in c | i use int8_t* to point the struct,and i can use cout to print the "num" data, but how to print the "b" data?
here is my code
struct A_T{
int num;
char *b;
};
int main()
{
A_T *a=new A_T();
a->num=10;
a->b="aaa";
int8_t *p;
p=(int8_t*)a;
cout<<a->num<<endl;
cout<<*p<<endl;
return ... | You could use from this 'cout << ((A_T *)p)->b<<endl;' instraction inorderto access member b of struct.
|
62,651,555 | 62,671,296 | How to set StyleSheet for an specific label in QMessageBox? | I Want to have a bigger QMessageBox and centered texts in it but when I increase the size of it by stylsheet it'll be like this:
if I could give it Some Padding or margin it would be fixed but I can't.
void MainWindow::showMsg()
{
QMessageBox m_MsgBox;
m_MsgBox.setWindowFlags(Qt::Window | Qt::FramelessWindowHi... | I got this answer in qt forum:
Only answering to your topic title, if you look into the source code of QMessageBox, every label has a object name, so that should be easy to set different style to them by using ID selector.
text: "qt_msgbox_label"
icon: "qt_msgboxex_icon_label"
informativeText: "qt_msgbox_informative... |
62,651,811 | 62,653,147 | Macro expansion problems in MSVC | I wonder why this macro is expanding so much.
#define CONCAT_IMPL(A, B) A##B
#define CONCAT(A, B) CONCAT_IMPL(A, B)
#define EAT(...)
#define TEST(ARG) EXPANDED, ARG) EAT(
#define GET_LAST(A, B) B
int result = 0;
result = GET_LAST(CONCAT(TEST, (1)), 2); // result is 2
result = GET_LAST(TEST(1), 2); // result is 2
resu... | C11 draft:
The sequence of preprocessing tokens bounded by the outside-most matching parentheses forms the list of arguments for the function-like macro. The individual arguments within the list are separated by comma preprocessing tokens, but comma preprocessing tokens between matching inner parentheses do not separa... |
62,651,837 | 62,652,199 | Trying to find isogram in a string c++ | I am trying to write a code that has two functions: one that determines whether the string is an isogram or not and another one to print the outcome (true or false) to the console (for the purpose of solving the task).
Some of the things are not working correctly though. And I wonder where I need to improve the code (p... | There are some problems here:
1) You always check an empty string:
print_result will just check an empty string, but it's redundant anyway.
void print_result()
{
std::string str; // empty string
if (!find_Isogram (str)) // finding isogram on empty string
{
std::cout << "false" << std::en... |
62,651,930 | 62,653,219 | A problem relevate to bitmask (or operation) and segment | I'm trying to solve this problem:
Given three integers N, L, and R, find the integer M between L and R (inclusive) that maximizes M|N (the bitwise-OR of M and N). If there are multiple such values of M, return the least of them.
For example: N=100,L=50,R=60. The result is 59. Because 100|59 reaches the maximum value ... | Without params validation
uint32_t getM(uint32_t L, uint32_t R, uint32_t N) {
auto M = L;
for (int bit = sizeof(L) * 8; bit > 0;) {
const decltype(L) value = 1 << (--bit);
if (value & N) {
if (value & M) {
decltype(L) check_value = M & (~value);
for ... |
62,652,005 | 62,671,906 | Question for threadsafe queue from three easy pieces | The following is the given code by the book to illustrate a problem:
when there is 1 producer Tp and 2 consumers Tc1,Tc2, the following code will not work.
The reason is when Tp puts data into the queue, it wakes Tc1, and before Tc1 is ran, Tc2 sneaks in and take the only element and thus emptied the queue. Then Tc1 st... | pthread_cond_wait releases the mutex and goes to sleep in "one atomic action". However, getting woken up and re-acquiring the mutex does not happen atomically (how should that work in case of pthread_cond_broadcast where potentially multiple threads are woken up?).
pthread_cond_wait guarantees that upon successful retu... |
62,652,139 | 62,656,861 | Is it an undefined behavior when use the pointer that return from operator new as a pointer to element of array | int main(){
auto* ptr = (int*) ::operator new(sizeof(int)*10, std::align_val_t(alignof(int))); //#1
ptr[1] = 4; //#a
}
Consider the above code, what the standard says are listed in the following:
basic.stc.dynamic.allocation
The pointer returned shall be suitably aligned so that it can be converted to a pointer... | The expression:
::operator new(sizeof(int)*10, std::align_val_t(alignof(int)));
is a function call expression to the global allocation function. It is not using the new expression to allocate storage and construct an object or array of objects. The global allocator functions only return raw storage and do not construc... |
62,652,638 | 62,711,785 | C++ template type circularity and non-template pointer to template instance | For reference, here is the minimal example : http://coliru.stacked-crooked.com/a/75354688a0a6af64
In this example, I have a single problem of template type circularity that, in my view, could be solved in two ways :
make the Controller a template class and the Event member pointer a non-template pointer to a template ... | You cannot fully type erase functor which accept template argument.
But if you know the subset of template argument to handle, std::any/ std::variant might help:
In your case non-supported event do no-op, so "your" controller:
template <typename ... Modules>
class Controller {
public:
std::tuple<Modules...> modules... |
62,653,027 | 62,653,248 | How to get the lowest number of one column in a two dimensional array in C++? | I have a simple program to get from the user the lowest & highest temperature, then I must make the program get the average of the lowest & highest temperature of the day.
I should put the 7days,low,high in a two dimensional arrays name temp `temp[7][2]={0};.
so I made the program and it's work well and this is the cod... | The problem here is that you have init low to 0.
When you first init the 2d array, all values are set to 0. Then you have init low to temp[0][0], which means low is 0 now. Unless your lowest high is actually below 0, then it would never be updated.
Similarly, if your highest low is below 0, you would also notice that t... |
62,653,537 | 62,653,882 | How to write a perfect Abbreviated Function Template? | What are the best practices to write abbreviated function templates?
I understand, that since C++20, the following is valid code:
void f(auto&& val) {...}
Is it essential to use decltype(auto) as the return type of such functions?
In particular, is the following code the right way to write abbreviated function templat... |
Is it essential to use decltype(auto) as the return type of such functions?
Depends on what you're returning. Using an abbreviated template doesn't change anything in this regard.
In particular, is the following code the right way to write abbreviated function templates?
decltype(auto) f(auto&& val) {return std::for... |
62,653,574 | 62,653,912 | How does Runtime infer type at runtime? | Does compiler hard-code the rule in Machine Instructions how to read the memory at runtime?
ex:
int main()
{
int n;
cin >> n;
cout << "n * 4 = " << n * 4 << endl;
return 0;
}
My understanding on cin is it will stream bytes with space/line separated, if so when I give input as 5 the output is n * 4 = 20... | C++ is statically typed.
int n; cin >> n;
will always read an integer (it supports several formats like binary, hex and decimal). When you input anything other than an integer (like 'a') it will fail and (since C++11) set n to 0.
char c; cin >> c;
ont the other hand will always read a char. Now 'a' is a char, just as... |
62,653,751 | 62,653,798 | why can enum class values of type int not be used as int | I wanted to change an old-style enum to enum class : int because of its own scope.
But the compiler complains about using the values in integer arithmetics.
But why - since the enum is explicitly typed as int?
example:
enum class MsgType : int {
Output = 1,
Input = 2,
Debug = 3
};
enum class MsgSen... | That's the feature. Scoped enumerations are not implicitly convertible to integers, so you can't use them in lieu of integers. They are strongly typed by design. If you want the implicit conversion, use unscoped enumerations.
enum MsgType : int {
Output = 1,
Input = 2,
Debug = 3
};
enum MsgSender : int {
A = ... |
62,654,309 | 62,656,137 | gRPC generated code misses service implementation | Following the tutorial I successfully generated the code I expected with protocol buffers:
protoc service.proto --proto_path="../proto/" --cpp_out="../cxx/gen/" --plugin=protoc-gen-grpc=`which grpc_cpp_plugin`
The models are generated as usable classes without error, but the service implementation differs from the one... | I was missing the --grpc_out="../cxx/gen" argument.
With the command
protoc service.proto --proto_path="../proto/" --cpp_out="../cxx/gen/" --grpc_out="../cxx/gen --plugin=protoc-gen-grpc=`which grpc_cpp_plugin`
The service code now generates into the service.grpc.pb.cc file.
|
62,654,629 | 62,654,759 | Initialize Static const array from another static const array (With a small computation) | So I have a bunch of static const arrays of unsigned type. I declare them in the header and initialize them in a cpp file. The arrays are quite large (They are carrier indices of an OFDM based Transmitter). However I have the values from a document. So it is just a matter of copy paste for initialization. So far this w... | I would avoid static initialization depending on each other. You could use a
struct carrier_indices_t {
uint32_t A[288];
uint32_t A_ext[288];
};
class C {
static const carrier_indices_t carrier_indices;
}
And then
const carrier_indices_t C::carrier_indices = foo();
Where foo is a constexpr functio... |
62,654,678 | 62,654,829 | Using armadillo in atom with script | I there a way to compile a c++ file using script in atom that uses armadillo? I couldn't find anything related to it.
I already installed armadillo and tried compiling some basic code using script in atom:
#include <iostream>
#include <armadillo>
int main(int argc, const char **argv) {
arma::arma_rng::set_seed_rando... | If I read the source code for this atom-script thing correctly, it just hardcodes -Wall -include stdio.h as compilation options. You need to add -larmadillo to link it to the Armadillo library.
In short: you cannot use atom-script in combination with custom libraries, unless you edit the extension to hardcode the libra... |
62,655,331 | 62,655,563 | Get exe name that is currently running (Not the path) | hey so i wanted to get name of the exe that is currently running
here is what ive tried doing
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
char filename[ MAX_PATH ];
DWORD size = GetModuleFileNameA( NULL, filename);
if (size)
cout << "EXE file name is: " << filename << "\n";
... | The first command line argument is the name of the current program
#include <iostream>
#include <string>
#include <windows.h>
#include <algorithm>
int main(int argc, char** argv)
{
if (argc > 0)
std::cout << argv[0] << std::endl;
else {
//some other method has to be used, use OP's suggestion
... |
62,655,448 | 62,655,580 | Force a C++ class to have aligned attributes | Consider this class:
class C3
{
public:
uint16_t p1;
uint16_t p2;
uint8_t p3;
};
sizeof(C3) is 6. Is there any compiler routine to bypass alignment and force it's size to be 5? I tried to use alignas without success...
| With the MSVC compiler (you have included the VS-2015 tag), you can use the #pragma pack directive to set padding options for classes and structures. This also allows you to save/restore 'default' settings, using the push and pop options.
The following short example demonstrates this:
#include <iostream>
class C3 {
pu... |
62,656,152 | 62,656,218 | C++ Precedence and Associativity | This piece of code:
int scores[] {1,2,3,4};
int *score_ptr {scores};
//let's say that initial value of score_ptr is 1000
std::cout<<*score_ptr++;
produces the output:
1
As * and ++ have same precedence and then associativity is from right to left shouldn't we apply ++ operator first that is to increase the pointer ... |
As * and ++ have same precedence
No, postfix operator++ has higher precedence than operator*; then *score_ptr++ is equivalent to *(score_ptr++). Note that the postfix operator++ would increment the operand and return the original value, then *(score_ptr++) would give the value 1.
The result is prvalue copy of the or... |
62,656,874 | 62,656,925 | Value-initialization of std::array inside std::unordered_map | Consider the code:
#include <unordered_map>
#include <array>
#include <iostream>
int main () {
std::unordered_map<int, std::array<int, 5>> map;
map[42][0] = 1;
for (int i = 0; i < 5; i++) {
std::cout << map[42][i] << " ";
}
}
This prints 1 0 0 0 0 on my system. The cont... | operator [] inserts value_type(key, T()) if the key does not exist. This function is equivalent to return insert(std::make_pair(key, T()))
T() means default initialization
since c++17
This function is equivalent to return this->try_emplace(key).first->second
emplace/try_emplace constructs default-initalized value in ca... |
62,657,428 | 62,657,662 | Align C++ array of structs on 64-bit boundaries? | I have an array of 64-bit structs that I'd like to align on 64-bit boundaries:
struct AStruct
{
int x;
int y;
};
std::array<AStruct, 1000> array; // I'd like to align this on 64-bit boundary
I know the attribute is __attribute__((__aligned__(64)) but I'm unsure whether I need to align each individual struct... | You need to align the array only:
alignas(8) std::array<AStruct, 1000> array; //aligned on 64-bit boundary
See: alignas
|
62,657,466 | 63,676,599 | Using Q_ENUM and Q_PROPERTY for enum class in qml | There is a class for storing enums
class EnumerationStorage
{
Q_GADGET
Q_CLASSINFO("RegisterEnumClassesUnscoped", "false")
public:
EnumerationStorage() = delete;
enum class A
{
state1,
state2,
};
Q_ENUM(A)
};
There is another class in which I want to use enum
class Client ... | I resolved this issue!!!! You need to specify the full type with all namespaces in Q_PROPERTY
|
62,657,738 | 62,658,358 | How to implement async waiting loop with packaged_task in C++? | Let us say, that we use packaged_task for implementing async work in a program.
#include <map>
#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>
#include <iterator>
#include <future>
#include <thread>
#include <chrono>
int main()
{
std::packaged_task<int()> packagedTaskOne([]()
... | If you don't want to use futureResultOne.get(); to avoid blocking, the following is a way to check if your task has finished or not in the main (you can use an independent one of course) thread.
#include <iostream>
#include <future>
#include <thread>
#include <chrono>
#include <condition_variable>
using namespace std:... |
62,657,864 | 62,658,072 | Showing Only Shared Drive and Folders in QTreeView | I have written the following code which can show the shared folder based UNC path in QTreeView widget. However, QTreeView shows a shared folder with my local drive contents. I wanted to remove local drive from that representation. How should I do that?
void MainWindow::ListDirectory(QString arg_smb_path)
{
o_direct... | Implement a QSortProxyFilterModel as an intermediate between filesystem model and the tree view.
E.g. like this:
class FilterSharedFoldersModel : QSortFilterProxyModel {
protected:
bool filterAcceptsRow(int row, const QModelIndex &parent) const override;
};
Now in the implementation of filterAcceptsRow(), check th... |
62,658,141 | 62,658,344 | Class doesn't define properly. Needs identifier | so I've just tried my hand with classes in c++. They seemed straightforward enough, until i tried defining one for use in a vector.
Then all of the sudden it doesn't work. Class is:
class throw{
public:
string thrower;
int longit;
int latit;
};
which is exactly how the tutorial told me to do it, but it... | Either tutorial is wrong and you'd better find a better one or you need to rename your class to Throw, because C++ is case sensitive, and throw is a reserved keyword.
|
62,658,315 | 62,658,373 | change combined classed variable in c++ | I have a class called Factory with a variable named balance. I made an object from it called f. In the other hand I have a class called Medicine that must change balance in f. I made two object of Medicine named med1 and med2.
med1 adds f's balance by 10. med2 adds f balance by 5. But these changes don't add with each ... | It can be done using references.
#include <iostream>
#include <string>
using namespace std;
class Factory
{
public:
Factory() {};
void addbalance(int x)
{
bal += x;
}
void show()
{
cout << bal;
}
private:
int bal = 0;
};
class Medicine
{
public:
// now cannot be in... |
62,658,395 | 62,659,523 | Boost buffer_cast cannot convert from void* to PointerToPodType | I am interested in Socket communication and use boost library. When i got a message from server and try to convert it atomic<uint8_t>* it gaves me an error that 'static_cast': cannot convert from 'const void*' to 'PointerToPodType'. I could not understand why it gaves me that error.
Code sample
atomic<uint8_t>* buffer... | It's not C, don't use new, malloc (or delete or free).
Specically, I see pointers to sockets, pointers to everything. You leak the entire buffer allocated with new if you made the assignment work.
Here's a simpler take, cutting the double-buffering (streambuf adds little):
uint8_t buffer[10000];
auto transferred = boo... |
62,658,765 | 62,659,777 | How do I access a map of vector<int> to int? | I have a piece of code, where I created a map from vector to int.
I iterate over the map with auto but even though I can access the size of the vector, I cannot push to the key.
Is that not allowed?
int numberOfArithmeticSlices(vector<int>& A) {
map<vector<int>, int> m;
for(int i=0; i<A.size(); i++)... | You cannot change the value of a key in std :: map once it has been added to the map. The only way out is to erase the key and re-insert it after making the changes.
Look this up to know how to erase a key from a std :: map.
|
62,658,972 | 62,659,141 | Why return expression in while loop doesn't work | the code below is count int m can be consist by which number in array data, but the return 0; expression for exit doesn't work, it will occur stack corrupt, I have to use exit(0);, why?
#include <iostream>
#include <cstdlib>
void increase(bool seq[], int size);
constexpr int n = 5;
int main()
{
int m, data[n];
... | This code is incorrect
void increase(bool array[], int size)
{
bool isCarry = true;
for (int i = size; i >= 0; --i) {
if (isCarry) {
isCarry = array[i];
array[i] = !array[i];
}
}
}
it should be
void increase(bool array[], int size)
{
bool isCarry = true;
for ... |
62,659,297 | 62,660,716 | Incorrect rotation and scaling of shape objects C++ | (Please help, still unable to solve) After doing some rotation and scaling of my polygon shaped objects, I managed to render an image but it's different from the correct image as shown below(Correct image). I am puzzled by why that is. I have found the center of the vertices and scaled and rotated my polygon shaped obj... | Seems like you should rotate around the centroid, so I don't see why you are using _pivotPt.x() when computing new coordinates. It should be
_xn = (center.x() + std::cos(angle) * xn - std::sin(angle) * yn);
_yn = (center.y() + std::sin(angle) * xn + std::cos(angle) * yn);
edit : Seems like center and _pivotPt shoul... |
62,659,686 | 62,660,496 | Error using boost::asio::deadline_timer while execution | I am trying to implement a basic deadline timer using this code:
class Example
{
Example(boost::asio::io_service& ios, config& cfg)
: ios_(ios), cfg_(cfg), tcp_client_(ios) {
state = new State();
boost::asio::deadline_timer t... | You don't show the mutex - so we can't answer.
That said, about everything is going wrong with respect to async that can go wrong:
you have a memory leak (state is an owned pointer member, but you defaulted the destructor? https://www.google.com/search?q=cppreference+rule+of+three&oq=cppreference+rule+of+three&aqs=chr... |
62,659,801 | 62,676,829 | Constrained member functions and explicit template instantiation | G++ and Clang++ agree that the following snippet is not valid C++:
template<int dim, int rank>
struct Tensor {};
template<int dim>
double InnerProduct(Tensor<dim, 1> const &, Tensor<dim, 1> const &)
{ return 0.0; }
template<int dim>
double DoubleInnerProduct(Tensor<dim, 2> const &, Tensor<dim, 2> const &)
{ retur... | This is a bug of the c++20 experimental implementation of both GCC and Clang.
This is reported as GCC bug #77595.
In the c++20 paragraph [temp.explicit]/11:
An explicit instantiation that names a class template specialization is also an explicit instantiation of the same kind (declaration or definition) of each of its... |
62,660,083 | 62,660,279 | store sub arrays on different length in C++ | How do you store sub arrays of different length in C++?
I know you can store a sub arrays of fixed size length, by specifying the the number of elements in the [] brackets. For example here I specify the parent array will have 10 sub arrays, and each sub array will have 2 elements units[10][2].
string units[10][2] = {
... | This is where a std::vector comes in handy:
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::vector<std::string>> units = {
{"0", "z", "e", "r", "o"},
{"1", "o", "n", "e"},
{"2", "t", "w", "o"},
{"3", "t", "h", "r", "e", "e"},
... |
62,660,229 | 62,660,377 | Looking for a pointer ignoring instruction when null | I use a monitoring class Progress. In a lot of functions, I update the progress if given. The progress variable is optional and given by pointer that could be null. A lot of part of my code look like this:
void do_the_job(Progress* progress)
{
do_part_1();
if((bool)progress)
progress->set(0.25f);
do_part_2();... | The function should not have to bother with a null pointer so design the Progress such that it can be used like this:
void do_the_job(XProgress& progress)
{
do_part_1();
progress.set(0.25f);
do_part_2();
progress.set(1.0f);
}
Getting there is simple:
struct XProgress {
std::shared_ptr<Progress> instance;
... |
62,660,417 | 62,663,043 | Casting complex, non-primitive C++ data types into Erlang/Elixir format, to export methods using NIF | I'm writting a library in C++ which I'll use in Elixir/Erlang. There're C++ methods that accept and return, including via out parameters, and involving pointers, data structures or library from std library such as: tuples, vectors, priority queues, bitsets and so forth. And also methods that accept or return generics.... | In Erlang, types are what are defined in here. Internal Erlang and C/C++ std representations do not match, you cannot return a, for example, int64_t from C and use it directly from Erlang.
Same for complex structures, is PrioryQueue an Erlang's list() or a {list(), pos_integer()}?
This means that you need to transform ... |
62,660,441 | 62,854,034 | How to pass a function as a parameter in c++? | I have this file
Matrix.h:
#ifndef MTM_MATRIX_H_
#define MTM_MATRIX_H_
#include <assert.h>
namespace mtm
{
template<class T>
class Matrix
{
T** data;
int col;
int row;
public:
Matrix(int row,int col, T intial=0);
T& operator()(int row, int col);
const T& oper... | the solution was to declare the function in the class like this
template<typename Function>
Matrix<T> apply(Function function);
and then write it's body and use it this way:
template<class T>
template<typename Function>
Matrix<T> Matrix<T>::apply(Function function)
{
int k=3;
int n=function(k);
}
|
62,660,997 | 62,661,071 | Are non-virtual methods of the baseclass guaranteed to be available through objects of the derived class? | Please consider the following code:
#include <iostream>
class Base {
public:
void Print() { std::cout << "a\n"; }
};
class Derived : public Base {
};
int main() {
Derived d;
d.Print();
}
It prints a as expected. However, I'd like to make sure this is indeed valid use of C++ and I'm not accidently running i... | From the reference (emphasis mine):
When a class uses public member access specifier to derive from a base, all public members of the base class are accessible as public members of the derived class and all protected members of the base class are accessible as protected members of the derived class
So yes, in your ca... |
62,661,589 | 62,662,104 | Problem with C++ header file and class implementation | first of all thank you to anyone that reads my question and special thanks to anyone that can offer advice.
I’m in the second week of CS 162 right now and our professor has just introduced us to classes. After following along to his code I have been completely unable to compile or use a class that I create.
In an attem... | I think that with john(4) you meant to call the setter function; you can replace it with
john.setTomato(4);
Also, the way you use it later is incorrect, you can do
std::cout << john.getTomato(); // do not forget ()
Finally you should be able to compile your example with:
g++ -c tomato_imp.cpp -o tomato_imp.o
g++ toma... |
62,661,658 | 62,662,031 | how to change sizeof(std::string) | I save my table data in a file with a certain pattern. I will do it with x86 and read it with same pattern. It is correct.
But if a change compiler to x64 i can't read the data from file because std::string allocation size is changing.
in x86 build:
printf("string size: %d\n", sizeof(std::string)); // output is "string... | There is no way to change the size of the std::string class. Nor would changing the size of std::string or even knowing that size be useful in storing data in a file because std::string is not trivially copyable.
You need to do proper serialisation. One simple approach is to store the content of buffer that std::string... |
62,661,778 | 62,668,886 | Is there any way I can give my app an icon? | I am using Visual Studio and C++ to create a console app. I want the exe file to have a custom icon instead of the default windows icon.
| You could right click your project and select add->resource->Icon->import, then you could import your icon. Because the Windows shell - normally Explorer - will use the icon with lowest ID or name as the default icon. So, you could check if the ID of the icon is the lowest. If not, you could change it.
Also, you could ... |
62,662,155 | 62,662,201 | ISO C++ forbids declaration of ‘setInputNombre’ with no type | This is my class
class PrimeThread : public QThread
{
private:
long inputNombre;
virtual void run() Q_DECL_OVERRIDE
{
ifstream primeFile("premier.txt", std::ios::in);
long primeLigne;
primeFile.close();
primeFile.open("premier.txt", std::ifstream::in);
cout << input... | Your setInputNombre does not have a type. What should it return? If you don't care, void is the answer:
void setInputNombre(long inputnb) {
// ...
}
|
62,662,214 | 62,662,694 | c++ class using a lambda in constructor | Using c++11
I want to create a class that uses a lambda as part of a calculation.
//contrived sample of potential usage
void random_class::some_function(void)
{
auto an_object = new my_custom_object(5, [this](){ return random_class_member * 5; });
an_object.do_some_processing();
random_class_member++;
an_object.do_... | There are two approaches you could take.
Use a type-erased std::function
For example:
class my_custom_object {
public:
my_custom_object(int a, std::function<void()> p)
{
privatea = a;
privatep = p;
}
void do_some_processing()
{
privatea += privatep();
}
private:
int ... |
62,662,505 | 62,663,117 | Intersection of two std::unordered_map | I have two std::unordered_map
std::unordered_map<int, int> mp1;
std::unordered_map<int, int> mp2;
I need to find the intersection of key-value pairs and store it in another map of the form.
std::unordered_map<int, int> mp;
How can i do this??
| You could use std::set_intersection to fill a new container containing the key, value pairs that exists in both maps. set_intersection needs the ranges to be sorted (which is exactly what you won't get from an unordered_map) so either, replace the unordered_maps with map or create temporary maps (or temporary std::set<... |
62,662,606 | 62,948,106 | Win32 SendInput mousemove lag and freeze | I am trying to move the mouse (on Windows 10) using SendInput when I perform a physical mouse click. It works fine if I click once or twice, but if clicking for examples 6 times in quick succession the mouse lags for a few seconds then the program stops responding.
Is there any obvious reason why this is happening?
(Ed... | Using Raw Input sample:
#include <windows.h>
#include <iostream>
using namespace std;
BOOL registerTouchpadForInput(HWND hWnd)
{
RAWINPUTDEVICE rid;
rid.dwFlags = RIDEV_NOLEGACY | RIDEV_INPUTSINK;
rid.usUsagePage = 1;
rid.usUsage = 2;
rid.hwndTarget = hWnd;
return Re... |
62,662,679 | 62,680,673 | Is boost::serialization::base_object required every time I do inheritance? | I have:
non-polymorphic (no virtual methods) class hierarchy;
base class already contains serialize;
child classes are serialized directly;
class A
{
private:
int x;
int y;
template<typename Archive>
void serialize(Archive& ar, const unsigned int)
{
ar & x & y;
}
... | No. If you don't want to serialize data from the base, you may not need it.
However, in polymorphic hierarchies you do need it if only to tell the archive about the registered types.
See https://www.boost.org/doc/libs/1_73_0/libs/serialization/doc/serialization.html
See here for lots of examples: https://stackoverflow.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.