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,606,772 | 72,607,196 | How does CoffeeCatch jump back to the COFFEE_CATCH clause? | I recently discovered CoffeeCatch, which I want to use to log the C/C++ native crashes on Android. I haven't managed, but still I am curious about how it works internally.
My understanding is that it basically catches and emitted signal (e.g. SIGSEGV) and allows the user to do something with it; in my case I would like... | siglongjmp jumps back to where sigsetjmp was called, and makes it look like sigsetjmp returned the value that siglongjmp was passed. So in this case, if siglongjmp is called with a non-zero value, then it will jump back to the sigsetjmp(*coffeecatch_get_ctx(), 1) == 0 condition, which will evaluate to false and thus t... |
72,606,999 | 72,607,621 | Changing the lambda function but the lambda argument and return type stays the same | I am using std::semiregular to hold some functors in a class. Ideally, what I really want is to be able to instantiate such template class, but define the lambda implementation at a later stage using the register function. However, I am struggling to find a way do that.
Even the simplest case down below does not seem t... | That's because the type of the lambdas are different. You could use a function pointer, or a std::function.
I believe the following change is valid, and should be the only required one:
RestApiImpl<void(*)(int,float)> api(get);
The only difference from your code is the template parameter type is explicitly specified.
... |
72,608,088 | 72,608,257 | SFINAE when using lvalue ref but success when using rvalue ref | I searched but really couldn't find an answer why SFINAE happens only when the argument is passed by lvalue ref, but the build succeeds when the arg is passed by rvalue ref:
template <typename T>
class A {
public:
using member_type = T;
};
template <typename AType>
typename AType::member_type f(AType&& m) {
typen... | When you have
template <typename AType>
typename AType::member_type f(AType&& m)
You have what is called a forwarding reference. Even though it looks like an rvalue reference, this reference type can bind to lvalues or rvalues. The way it works is when you pass an lvalue to f, AType gets deduced to being T&, and when... |
72,608,807 | 72,609,287 | Attempting to use OpenCV 2.4 C++ library when .so files installed in a non-standard location | I've read some other posts about doing something similar to this, and I know about the existence of the -L and -l flags for G++, however I can't seem to get it right. All of the .so files for opencv 2.4 are currently installed in $HOME/.local/lib, since this is a VM I do not have root access to, and cannot get the admi... | Question resolved in comments, the command that successfully compiles my project is:
g++ -I$HOME/.local/include -L$HOME/.local/lib -lopencv_calib3d -lopencv_contrib -lopencv_core -lopencv_features2d -lopencv_flann -lopencv_gpu -lopencv_highgui -lopencv_imgproc -lopencv_legacy -lopencv_ml -lopencv_nonfree -lopencv_objde... |
72,608,845 | 72,609,088 | C++ concept: Requiring a static variable to be present in a policy class | I want to constraint the template parameters of a policy class.
That is, when I call Foo<policy>, I want the compiler to stop here if the policy class does not fulfill the requirements I want.
Complete non-working example
To simplify the problem, let's consider just the requirement that the policy class has to declare ... | I'm not familiar with this library, but my guess is that the Acceleration concept rejects references.
{ expr } -> concept requirements determine the type as if by decltype((expr)), which for your variable yields an lvalue reference.
decltype inspects the value category of the expression, and adds & to types of lvalues... |
72,608,991 | 72,609,142 | Why can't I use std::optional with Boost Asio sockets without moving them | I'm creating a simple network game in c++.
I have a server class where a single socket is stored for usage. The socket is not known at the creation of the class, so I've chosen to use a std::optional<tcp::socket> (is this the correct way or is there a better one?) which is initialized to std::nullopt and later a socket... | Simply put, sockets aren't copyable because it's not clear what a copy of a socket would be. When the remote end sends data which socket instance would receive that data; the original or the copy? What happens when you close the original what should happen to the copy? You could design a socket class that acts as a ... |
72,609,121 | 72,794,470 | Installed C++ with VS Build Tools, but can't find CL.exe | We have a Jenkins build agent based on docker pull mcr.microsoft.com/dotnet/framework/sdk:4.8
Part of the Docker file for the container pulls in additional workloads as follows
vs_buildtools.exe --quiet --wait --norestart --nocache modify \
--installPath "%ProgramFiles(x86)%\Microsoft Visual Studio\2022\BuildTools" \
-... | You also need to pass either --includeRecommended or --add Microsoft.VisualStudio.Component.VC.Tools.x86.x64 as an argument.
MSVC v143 - VS 2022 C++ x64/x86 build tools (Latest) is listed among
Components included by VCTools workload as Recommended
and thus is not installed with Microsoft.VisualStudio.Workload.VCTools ... |
72,609,196 | 72,610,195 | WriteProcessMemory, program's value + user's input value at the same time | There is a program that stores a value in memory, like 100. I read that value using ReadProcessMemory():
ReadProcessMemory(processHandle, (LPVOID)(programBaseAddress + offsetProgramToBaseAdress), &baseAddress, sizeof(baseAddress), NULL);
After ReadProcessMemory(), baseaddress contains 100.
With this code:
int value{}... | You need to read the value first, then add the user's input to the value, then write the value back. Those are separate operations, don't try to mix them together (ie, &baseAddress + value doesn't do what you think it does).
Try something like this instead:
int32_t value{};
ReadProcessMemory(processHandle, (LPVOID)(pr... |
72,609,454 | 72,614,418 | Using enable_if to decide the type of a member variable | template <typename ...T>
class BaseEvent
{
BaseEvent(const unsigned int index, const uint8_t id, const std::variant<T...> data) : m_index(index), m_id(id), m_data(m_data){};
virtual ~BaseEvent();
template <typename V>
const V get()
{
static_assert(constexpr std::is_same_v<V, T...>);
... | I have done exactly what you want to do, so I know what you need. To handle both single message and multiple message types, use std::variant<std::monostate, T...>. In addition, your use of is_same_v<> is incorrect. You can only use 1 type, not multiple types there.
So you need a code like this:
template <typename ...T>... |
72,610,082 | 72,610,118 | How to use CreateCompatibleDC(), SetPixel(), and BitBlt() to display an image? | I'm trying to draw and display an image(s) on a device context (variable: dc) by using CreateCompatibleDC(), SetPixel(), and BitBlt() as seen in the code below:
HDC Layout = CreateCompatibleDC(0);
HBITMAP image = CreateCompatibleBitmap(Layout, symbol->bitmap_width, symbol->bitmap_height);
// Draw the i... | CreateCompatibleDC() creates an in-memory HDC with a 1x1 monochrome HBITMAP assigned to it by default. You need to use SelectObject() to replace that default HBITMAP with your own HBITMAP before you then use SetPixel() to change the HDC's pixels, eg:
// create an HDC...
HDC Layout = CreateCompatibleDC(0);
// create a ... |
72,610,264 | 72,610,373 | Custom destructor x default constructors in C++ | I have a class with four member and no implemented Destructor by my part. If I delete the object, the 4 members will be deleted by the default destructor, right? If I make a blank custom destructor none of them will be deleted?If I make a custom destructor that only deletes one of them, will the other three be deleted ... | Strictly answering your questions
I don't think that answering your question actually helps you because the way you framed the problem doesn't help you. But here it is anyway:
If I delete the object, the 4 members will be deleted by the default constructor, right?
Right
If I make a blank custom destructor none of th... |
72,610,677 | 72,611,180 | What for are JSON schemas practically used? | Reference: Getting started with JSON schema
I have been reading about JSON schema. I understand that
When you’re talking about a data format, you want to have metadata
about what keys mean, including the valid inputs for those keys. JSON
Schema is a proposed IETF standard how to answer those questions for
data.
Alrig... | One use is validation. More than pass/fail you get a meaningful error message like e.g. "unexpected value W for field A.B.C, allowed values are X, Y, Z" or "invalid type for field A.B.C, expected date, found int", "missing field A.B.C" etc.
They can also serve as self documentation.
They are also used for autocomplete.... |
72,610,959 | 72,611,001 | How to understand Using :: (Scope resolution operator) to access a in-class class (nested class) or typedef | I'm trying to understand Scope resolution operator ::
I know I can only access static class member via Scope resolution operator.
But I can use it to access typedef or a nested class thing like this:
class test{
public:
class testinner{
public:
int _val;
testinner(){}
testinner(... |
I can't access non-static members via :: such as line 4
False. The problem is that you cannot access non-static members without an object. If you have an object, you can use a qualified name (with ::).
int main()
{
test t;
t.test::s = 5;
//^^^^^^
}
Is that mean an in-class class and typedef is a static ... |
72,611,080 | 72,614,035 | How to add a callback in an event handler in a legacy MFC code? | This is a toy implementation of a legacy code using MFC. OnBnClickedButton is an event handler but it contains codes which are executed asynchronously in a different thread ( may be a bad idea). The declaration syntax is accepted by the message map.
//declaration
afx_msg void OnBnClickedButton();
//message map
ON_BN_C... | The function signatures and return values for entries in MFC message maps are fixed. You have to follow the protocol; it doesn't offer any customization points. In case of the ON_BN_CLICKED button handler the prototype must abide to the following signature
afx_msg void memberFxn();
It doesn't accept or return any valu... |
72,611,116 | 72,611,206 | "If the deriving class does not inherit the base class virtually, then all virtual methods must be defined".How to understand that in the right way? | As per the wiki, which says that[emphasise mine]:
Note the code snippet in the quotaion is seen here.
Suppose a pure virtual method is defined in the base class. If a
deriving class inherits the base class virtually, then the pure
virtual method does not need to be defined in that deriving class.
However, if the deriv... | The description in the wikipedia article is wrong/misleading.
"If the deriving class does not inherit the base class virtually, then all virtual methods must be defined" is only true if the deriving class gets instantiated. A mere declaration, without instantiation, does not require definition of pure virtual methods.
... |
72,611,170 | 72,611,285 | Breaking a module into multiple implementation files | C++20 modules question.
Let's say I have the following code files, where '.ixx' are module files.
Main.cc, A.ixx, B.ixx, ..., Z.ixx, Group.ixx
If I want to make all the files [A-Z] part of the same module, 'TheModule', does each file need a unique module partition name? ie:
// A.ixx
export module TheModule:A
// B.ixx
... |
If I want to make all the files [A-Z] part of the same module, 'TheModule', does each file need a unique module partition name?
Yes. Any module unit that can be independently imported either is the primary module interface unit or is a module partition. In both cases, it must have a name. A unique name.
Is there a w... |
72,611,247 | 72,621,838 | Register width and parsing for a fast-loading file format | For the past approx. 20 years I've been working on a program for 3D graphics that implements a METAFONT-like language. It's in C++. I now have started working on a format and functions for writing the data for the 3D objects to a binary file and then reading them in again. It is intended for saving and fast-loading ... |
Does it pay at all to read data into objects smaller than 64 bit, i.e., chars, ints or floats?
This is dependent of the architecture. On most platform this is very cheap, like 1 cycle if not even free regarding the exact target code. For more information about this, please read Should I keep using unsigned ints in th... |
72,611,565 | 72,613,499 | CMake dependencies between libraries and programs | I'm a beginner with CMake and since yesterday I try something without result :-(
I explain my goal... I've a C++ project with dynamic libraries and programs using these libraries.
Here is the structure of my project:
libA
libB
program1
program2
program3
Inside each directory, I've an include and a src directory.
libB... |
how to define dependencies between them.
Just, in respective CMakeLists:
target_link_libraries(program1 PRIVATE libA libB)
target_link_libraries(program2 PRIVATE libA libB)
target_link_libraries(program3 PRIVATE libA libB)
target_link_libraries(libB PUBLIC LIBA)
|
72,611,859 | 72,625,772 | Is there a portable way to implement variadic CHECK and PROBE macros for detecting the number of macro arguments in C++? | In C Preprocessor tricks, tips, and idioms, it suggests the following macros which detect the number of arguments created by a macro:
#define CHECK_N(x, n, ...) n
#define CHECK(...) CHECK_N(__VA_ARGS__, 0,)
#define PROBE(x) x, 1,
and then states that:
CHECK(PROBE(~)) // Expands to 1
CHECK(xxx) // Expands to 0
Ho... | After some more digging I found this answer from the VS Developer Community, which provides the solution: an extra layer of indirection and some funky rebracketing. Rewriting to match the original question:
#define CHECK_N(x, n, ...) n
#define CHECK_IMPL(tuple) CHECK_N tuple //note no brackets here
#define CHEC... |
72,612,034 | 72,613,153 | Is there a way to get or notice the default arguments of the function? | Example I have a lots of class, each have it own constructor with defaut arguments, and each have a fake_constructor function which have same arguments as the constructor so I can take the function pointer from it.
class someRandomClass
{
public:
someRandomClass(int a = 0, float b = 0.f, double c = 0.0, const char*... | std::is_constructible traits might help (And you might get rid of fake_constructor :-) ):
template<typename Cls, typename... Ts>
// requires(std::is_constructible_v<Cls, Ts&&...>) // C++20,
// or SFINAE for previous version
void callClassConstructor(Ts&&... args)
{
... |
72,612,340 | 72,612,539 | the class that i defined as student is storing the variable but not processing it and doing the desired action | #include <iostream>
#include <string>
class student {
public :
int total_percentage {};
public:
int eng_marks {31};
int maths_marks {64};
int sst_marks {98};
int comp_marks {89};
int sports_marks {56};
public:
int percentage(){
total_percentage = ((eng_marks + ma... | You are performing an integer division. Following division will produce incorrect results.
total_percentage = ((eng_marks + maths_marks + sst_marks + comp_marks + sports_marks)/500)*100;
Since all variables involved are integer, compiler will perform the following division.
total_percentage = ( (31+64+98+89+56) / 500 ... |
72,612,451 | 72,612,718 | How to get a second cin to work when the first has a while loop to take in an unknown size input | I have been trying to figure out how to get a simple program to work, however I am getting hung up on taking user input from the console. I am able to take in a list of integers (eg. 3 5 3 2 1 8 9) into a vector, however I need to also take in one more user input for the number I need to check if it is inside the vecto... | Your while loop is reading integers from the input stream std::cin, so if you enter a letter std::cin goes into an error state and will remain there until you explicitly clear the error state.
To clear the error state, call cin.clear(). But invalid input remains in the stream. To ignore all the remaining characters in ... |
72,612,665 | 72,612,792 | Can I edit a global vector using multiple threads in C++? | I currently have a code which works well, but I am learning C++, and hence would like to rid myself of any newbie mistakes. Basically the code is
vector<vector<float>> gAbs;
void functionThatAddsEntryTogAbs(){
...
gAbs.pushback(value);
}
int main(){
thread thread1 = thread(functionThatAddsEntryTogAbs,args... | You can access and modify global resources, including containers from different threads, but you have to protect them from doing that at the same time. Some exceptions are: no modifications are possible, the container itself is not changed and the threads are working on separate entries.
In your code, entries are added... |
72,612,728 | 72,613,688 | GCC but not Clang changes ref-qualifier of function type for a pointer to qualified member function | Following snippet compiles in Clang but not in GCC 12.
// function type (c style)
//typedef int fun_type() const&;
// C++ style
using fun_type = int() const&;
struct S {
fun_type fun;
};
int S::fun() const& {
return 0;
}
int main()
{
fun_type S::* f = &S::fun;
}
Produces error in GCC:
prog.cc: In... |
Which compiler is correct standard-wise?
Clang is correct in accepting the program. The program is well-formed as fun_type S::* f is equivalent to writing:
int (S::*f)() const &
which can be initialized by the initializer &S::fun.
|
72,613,068 | 72,613,172 | Lifetime of the returned range-v3 object in C++ | I want to make a function that works like np.arange(). With range-v3, the code is
auto arange(double start, double end, double step){
assert(step != 0);
const auto element_count = static_cast<int>((end - start) / step) + 1;
return ranges::views::iota(0, element_count) | ranges::views::transform([&](auto i)... | You fell victim to Undefined Behaviour due to capturing of local variables via [&].
If you capture by value [start, step](auto i){ return start + step * i; }, the code will work correctly.
Note that views are always non-owning, can be copied around and are generally O(1) in their storage. Since iota is a generating vie... |
72,613,136 | 72,613,620 | How to check if a parameter pack contain all elements of other paraments pack | Example:
I have function A with some default arguments, and I want a function that take all the arguments of that function A to check with all arguments I giving. If function A contains all that arguments, then it will call function A with that arguments
Here my sample code:
void A(int a = 0, float b = 0.f, double c = ... | As state in comment, when passing T1(*func)(Arg1...), you lose default parameters.
So instead of passing function pointer, you might pass functor:
[](auto... args) -> decltype(A(args...)){ return A(args...); }
and then std::is_invocable might be used:
template<typename F, typename... Ts>
void call(F func, Ts...args)
{... |
72,613,849 | 72,613,974 | Max Pairwise Product problem integer overflow | #include<algorithm>
#include <iostream>
#include<vector>
using namespace std;
long long MaxPairwise(const std::vector<int>& nums){
long long product = 0;
int n;
n=nums.size();
int index1=-1;
for(int i=0;i<n;i++){
if(index1==-1 || nums[index1]<nums[i]){
index1=i;
}
... | product = 1LL * nums[index2] * nums[index1]; forces conversion of the coefficients on the right hand side to the long long type.
Otherwise the type of the product is an int, with possible overflow effects.
Using std::vector<long long> is another option.
Note that nums.size(); is a std::vector<int>::size_type type. That... |
72,614,028 | 72,614,092 | C++ Unix and Windows support | I want to make my project available for Linux.
Therefore, I need to substitute functions from windows.h library.
In my terminal.cpp I highlight error messages in red. This step I only want to do in windows OS (ANSI don't work for my console, so i don't have a cross-platform solution for this).
On windows it works, but ... | Header files are supposed to contain declarations. By adding the {} you made a definition and C++ does not allow multiple definitions of the same function with identical signatures.
Either remove the {} and provide a definition in a separately-compiled .cpp file, OR by marking the function as inline.
|
72,614,417 | 72,616,562 | How to use arc co-ordinates from .slib file to draw an arc in Qt? | I am trying to generate various gate symbols ( AND,NOT,XNOR,MUX etc) by reading .slib file.
But I faced a problem while reading an arc related co-ordinate from .slib file.
I am not understanding how to use those co-ordinates and draw an arc ?
The format of an arc in .slib file is confusing.
Here is the example:
.sli... | It looks like the first two coordinate pairs are two points on an imaginary circle and the third pair is the center of that circle. Together, those describe a circle arc section. For this to work with arcTo, we construct a QRectF bounding the circle, ie with the given center and side 2*radius.
Thus, the following ought... |
72,615,134 | 72,615,233 | Ranges algorithm in LLVM 14 libc++ | I have this snippet.
#include <algorithm>
#include <vector>
int main() {
std::vector<int> v1 = {1, 2, 3};
std::vector<int> v2 = {4, 5, 6};
return std::ranges::equal(v1, v2);
}
I compile it with GCC 10 (Debian stable) and everything's alright:
$ g++ -std=c++20 test.cpp -o test
<compiles fine>
I compile i... | You can find an exhaustive table for implementations feature support here: https://en.cppreference.com/w/cpp/compiler_support
For C++20s "The One Ranges Proposal" where std::equal is part of the table says "13 (partial)".
There is another overview for clang here: https://clang.llvm.org/cxx_status.html#cxx20. Though it ... |
72,616,930 | 72,620,163 | Is extracting the binaries from a GLSL shader a standard, supported operation? If so, how do we build glad.c to support it? | We have been working on an OpenGL program where glad was built two summers ago, working on Linux and windows on cards such as NVIDIA 2060 under Ubuntu 20.04LTS, Intel on Windows and Ubuntu, GeForce 940mx, and others.
On Linux the driver I personally am using is nouveau on this laptop.
*-display
desc... |
Is extracting binary from shader programs a standard feature that will work on all modern openGL and drivers? Let's say windows/Intel,
windows/NVIDIA, linux/Intel, linux/NVIDIA Neuveau, and/or Linux/NVDIA
with an NVIDIA driver.
Retrieving the binary represantation of a compiled shader program is specified in the AR... |
72,618,271 | 72,618,412 | C++ class templates can be implicity specialized and instantiated without angle brackets? | This actually compiles and works, but it's unclear to me why.
#include <iostream>
template <class T>
class LikeA
{
T m_val{};
public:
LikeA() = default;
explicit LikeA(T iv): m_val(std::move(iv)) {}
LikeA(LikeA<T> const &) = default;
LikeA(LikeA<T> &&) noexcept = default;
~LikeA() noexcept ... | Since C++17, compiler can automatically deduce the argument type of a template by using class template argument deduction (CTAD). You can skip defining the templates arguments explicitly if the constructor is able to deduce all template parameters.
So you simply write
int main()
{
std::vector v{2, 4, 6, 8}; //... |
72,619,077 | 72,620,192 | How to get the actual size of a protocol buffer message before serialization? | I defined a message in *.proto file and set the values using reflection.
I need to find out how many bytes are parsed per second with SerializeToString() API.
Is it possible to get the actual size of the message before calling SerializeToString?
| It depends on which size you're interested in.
If you want to know how large the serialized protobuf message returned by MessageLite::SerializeToString() is going to be you can use Message::ByteSizeLong().
Example:
ExampleMessage msg;
msg.set_example(12);
std::size_t expectedSize = msg.ByteSizeLong();
std::string res... |
72,619,779 | 72,621,553 | Correct calling convention for exporting windows DLL functions for Excel VBA without mangled names | I am writing a DLL to export functions to be used in Excel VBA - I have found a way to be able to pass parameters in but with mangled names. If I set up without name mangling then I can not pass parameters and get a calling convention error
I use the standard declaration for calling DLL exported functions from VBA:
VBA... | Per Microsoft's documentation:
https://learn.microsoft.com/en-us/office/client-developer/excel/developing-dlls
When compilers compile source code, in general, they change the names of the functions from their appearance in the source code. They usually do this by adding to the beginning and/or end of the name, in a pr... |
72,620,283 | 72,620,314 | How does std::is_polymorphic identify polymorphism? | I tried to understand the working of std::is_polymorphc in C++.
This is defined in type_traits.h:
template <class _Ty>
struct is_polymorphic : bool_constant<__is_polymorphic(_Ty)> {}; // determine whether _Ty is a polymorphic type
template <class _Ty>
_INLINE_VAR constexpr bool is_polymorphic_v = __is_polymorphic(_Ty)... | __is_polymorphic is a reserved keyword, so it's built-in to the compiler i.e. it's not implemented in library, it's implemented directly in the compiler. So, there is no source code to see, unless you look at the compiler's source code.
On cppreference, you can see a possible implementation:
namespace detail {
templ... |
72,620,480 | 72,620,573 | bubble sort not sorting properly | Im trying to sort this random generated array, but my output isincorrect it looks like this:
sorted round: 0: 87
sorted round: 0: 78
sorted round: 0: 16
sorted round: 0: 94
sorted round: 0: 36
sorted round: 0: 93
sorted round: 0: 50
sorted round: 0: 22
sorted round: 0: 63
sorted round: 0: 28
sorted round: 0: 91
sorted... | In these nested for loops
for (i; i < size; i++) {
for (j; j < size - i; j++)
{
for(k; k<20; k++)
{
cout<<"sorted round: "<<j<<": "<<random_array[k]<<endl;
}
if (random_array[j] > random_array[j + 1]) {
swap(random_array[j], random_array[j + 1]);
... |
72,620,535 | 72,620,643 | \K operator does not work in std::regex_replace regex | The value of name is: regex101: build, test, and debug regex - 3 running windows
im trying to remove everything forward the last -
std::wstring name = accvector[i].name;
std::wregex regexp(L".*\\K( -\\s+\\d+\\srunning.*$)");
name = std::regex_replace(name, regexp, L"");
nothing is being replace, whats wrong?
| You should keep in mind that \K operator is not supported by ECMAScript regex flavor (used by default in std::wregex/std::regex). It is mainly supported by PCRE, Boost, Onigmo, Python PyPi regex library.
Here, you may use
(.*) -\s+\d+\srunning.*
The replacement pattern should be $1.
See the C++ demo:
#include <iostrea... |
72,622,304 | 72,622,612 | Can I use std::copy to copy arrays allocated on heap? | I am using Qt6, C++ 11, I declare two 2d arrays of dynamic sizes:
int **A; int **B;
A = new int*[rowCount]();
for(int i = 0; i < rowCount; i++)
{
A[i] = new int[colCount](); //Same for B
}
// Then feed A with some incoming values
and I want to copy all A's values to B, I know that using std::copy is faster and c... | You cannot use std::copy to copy your array as a single chunk because you do not have a single array. What you have is a pointer to the first element of an array of pointers to the first element of arrays of ints. That is, assuming rowCount and colCount are both 3, you have this:
A
┌───┐
│ │
│ │ │
│ │ │
└─┼─┘
│
... |
72,622,310 | 72,623,613 | Should I clean up beast::flat_buffer when I see errors on on_read? | http_client_async_ssl
class session : public std::enable_shared_from_this<session>
{
...
beast::flat_buffer buffer_; // (Must persist between reads)
http::response<http::string_body> res_;
...
}
void on_write(beast::error_code ec, std::size_t bytes_transferred) {
if (ec)
{
fail(ec, "write");
... | // Should we do the cleanup here too?
That's asking the wrong question entirely.
One obvious question that comes first is "should we cleanup the read buffer at all".
And the more important question is: what do you do with the connection?
The buffer belongs to the connection, as it represents stream data.
The example ... |
72,622,349 | 72,622,399 | Trying to copy lines from text file to array of strings (char**) | This is my code for allocating memory for the array of strings:
FileReader::FileReader()
{
readBuffer = (char**)malloc(100 * sizeof(char*));
for (int i = 0; i < 100; i++)
{
readBuffer[i] = (char*)malloc(200 * sizeof(char));
}
}
Im alocating 100 strings for 100 lines then allocating 200 chars f... | Replace
readBuffer[i] = (char*)tmpString.c_str();
with
strcpy(readBuffer[i], tmpString.c_str());
Your version just saves a pointers to tmpString in your array. When tmpString changes then that pointer points at the new contents of tmpString (and that's just the best possible outcome). However strcpy actually copies t... |
72,622,621 | 72,634,790 | How do I capture(trap) a mouse in a window in c++? | I am writing a tile map editor in SFML and C++. I have been having all sorts of troubles with the mouse. I am using the built in SFML Mouse:: static functions and recently managed to get a custom cursor moving on the screen and pointing accurately to a tile by doing as follows:`
Sprite cursor;
bool focus = false;
Re... | There is already a method for that.
void setMouseCursorGrabbed (bool grabbed)
// Grab or release the mouse cursor.
You can also use these methods to convert your screen coordinates to mouse coordinates and vice versa.
Vector2f mapPixelToCoords (const Vector2i &point) const
// Convert a point from target coordina... |
72,622,767 | 72,622,798 | "unresolved external symbol" when including a single-header library | When I try to include any single-header library in my project (here I am using HTTPRequest), it keeps giving me the LNK2019 error.
This is my code:
#include "HTTPRequest.hpp"
void main()
{
http::Request request{ "http://test.com/test" };
const auto response = request.send("GET");
std::cout << std::string{... | Those error messages are referring to socket API functions which the HTTP library is using. You need to link your project to your platform's socket library, ie ws2_32.lib on Windows, etc.
|
72,622,921 | 72,624,515 | Python print() corrupting memory allocated by ctypes | I'm working on some code to act as a Python wrapper for a rather large C++ project. I have created a class wrapper with the associated function wrappers which make direct calls to the DLL. Since it is a C++ project, it needs a C wrapper as well, which is implemented and working correctly.
const char* MyClass::GetName()... | It appears the C++ code (not shown) is storing a pointer to name being passed. In the breaking case, the bytes object whose internal buffer that pointer references goes out of scope, freeing the buffer and creating undefined behavior.
In the OP's original problem, it is likely the allocation for 'hi' ended up at the s... |
72,623,633 | 72,623,659 | Error in map with 2 classes: "binary '<': 'const _Ty' does not define this operator or a conversion to a type acceptable to the predefined operator" | I'm having a weird error while declaring this map:
std::map<LoggedUser, GameData> m_players;
I've looked at many possible solutions, but couldn't find anything that works. I can't find the problem that causes this.
The error:
C2676 binary '<': 'const _Ty' does not define this operator or a conversion to a type accept... | std::map is a sorted container. It uses operator< by default to compare keys for sorting and matching (you can optionally specify your own comparitor to override this behavior).
The error message is complaining that your LoggedUser class does not implement an operator< for comparing the map's keys.
|
72,623,761 | 72,623,825 | Writing to a file using FILE* and fprintf in c++ won't work as expected | Not to bother anyone, but i have ran into an issue with a class of mine, somehow when i write to a file with the FILE* and fprintf() function i don't get any text in my text file that i created, i have searched all over youtube and i don't know what i'm doing wrong, because my code is the same.
Heres a copy of my .c++ ... | Main issue:
To fix your issue, you have to remove the local fp variable that shadows the class member.
When the compiler sees FILE *fp in your method, it uses a separate variable and is not referring to the one in your class instance.
Change the method definition to:
write_file(const char *file_name) {
fp =... |
72,623,896 | 72,638,056 | Java foreign function interface (FFI) interop with C++? | As of Java 18 the incubating foreign function interface doesn't appear to have a good way to handle C++ code. I am working on a project that requires bindings to C++ and I would like to know how to avoid creating a thunk library in C.
One of the C++ classes looks something like this:
namespace library {
typedef uint8_... | So the general answer seems to be "just create a shim library" because the C++ ABI is far more fluid and not supported by Java.
As for the answers at the end:
You just do it like normal, but with void* pointers
Pass in this as a void* and treat it as an opaque pointer
Handled automatically in the shim, from what I gat... |
72,623,961 | 72,623,981 | What is the difference between calling foo() and ::foo() within a C++ class member function? | I am looking at someone else's C++ code (note I am not fluent in C++).
Within the class, there is this member function:
void ClassYaba::funcname()
{
...
::foo();
...
}
There is no member function within that class's namespace named foo, but aside from that, what is the difference between ::foo() and foo() ... | When you call
foo();
C++ will search for something named foo in the following order:
Is there something with this name declared within the class?
Is there something with this name in a base class?
Is there something with that name in the namespace in which the class was declared? (And, if not, is there something with... |
72,624,023 | 72,624,722 | Implementing task primitives based on asio::awaitable | I'm looking for a way to implement task primitives like whenAll, whenAny, taskFromResult on top of (boost) asios awaitable<T> coroutine type.
What I've got so far is a function that creates an awaitable<T> from a completion callback. However I'm unsure how I'm supposed to run multiple tasks in parallel on the specified... | You can use the experimental operator overloads to combine awaitables.
E.g.
Live On Coliru
#include <boost/asio.hpp>
#include <boost/asio/awaitable.hpp>
#include <boost/asio/detached.hpp>
#include <boost/asio/experimental/awaitable_operators.hpp>
#include <boost/asio/use_awaitable.hpp>
#include <iostream>
using namespa... |
72,625,089 | 72,682,646 | Best way to design a time-measuring structure in C++? | I am struggling to do the following in the best way possible:
I have to measure the execution time of a C++ functionality implemented in C++. I have access to the code, so I can extend/modify it. The structure of what I have to do would be something like:
for (int k=0;k<nbatches;k++) {
//Set parameters from config f... | The std::chrono library gives you all what you need.
Please see here.
With that, you could write a very simple wrapper for your requirement.
We will define a timer class with a start and a stop function. "start" uses now to get the current time. "stop" will calculate the elapsed time, between start and the time, when "... |
72,625,624 | 72,625,711 | C++ using vector<vector> to represent matrix with continuous data buffer | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<float>> func(int M)
{
// res = matrix size MxM
vector<vector<float>> res;
float* buffer = static_cast<float*>(malloc(M * M * sizeof(float)));
res.reserve(M);
for (int i=0; i<M; i++) {
res.emplace_b... | The code doesn't do what you think it does.
The line
res.emplace_back(buffer + i * M, buffer + (i + 1) * M);
creates a new std::vector<float> to add to res. This std::vector<float> will allocate its own memory to hold a copy of the data in the range [buffer + i * M, buffer + (i + 1) * M), which also causes undefined b... |
72,625,758 | 72,626,014 | Why is my code giving segmentation fault error? | Step By Knight problem:
Given a square chessboard, the initial position of Knight and position of a target. Find out the minimum steps a Knight will take to reach the target position.
Note:
The initial and the target position coordinates of Knight have been given according to 1-base indexing.
#include<bits/stdc++.h>
u... | Your issue is a stack overflow because each level of recursion has no knowledge of what positions have already been checked. Consider this simple example to illustrate:
The knight makes a move of +2,-1, and you make a recursive call to test this new position.
While checking this position, the function will test a move... |
72,626,340 | 72,627,253 | How to use Gtk::EntryCompletion::set_match_func on GTKMM C++? | i want to search something for every sub string. I've been looking for GTK completion example on internet but i couldn't find the example with set_match_func. The documentation says i need to specify SlotMatch, but I don't understand how to use SlotMatch.
m_completion->set_text_column(0);
m_completion->set_minimum_... | The first line in the documentation, right after the inheritance diagram
typedef sigc::slot< bool(const Glib::ustring&, const TreeModel::const_iterator&)> SlotMatch;
Further reading reaches the example
For example, bool on_match(const Glib::ustring& key, const TreeModel::const_iterator& iter);
In gtkmm
m_completio... |
72,626,664 | 72,638,039 | Why is this program timing out without any network traffic? | I am trying to create a simple c++ program that hides the differences between Linux and Windows when making sockets and connecting to servers
The Linux part of this code compiles without any warnings or errors but times out after resolving the host IP and does not connect to the server running (nc -lvnp 7777)
Using tc... | As commented by @user253751, this line:
server_addr.sin_port = port;
should be changed to:
server_addr.sin_port = htons(port);
|
72,627,522 | 72,627,643 | How to add command line option to ELF binary using cmake and gcc? | I have a C++ based application and building the binary for it using cmake and make. Now, I want to show the version of my binary with something like --version flag. In the end I want to achieve ex_app -v should show the binary version. In one of the header files I could see a #define APP_VERSION "1.0" and this version ... | You can use the CMake configure_file directive to generate a header file with APP_VERSION macro.
CMakeLists.txt:
...
configure_file(${CMAKE_SOURCE_DIR}/version.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/version.h)
...
version.h.cmake:
...
#define APP_VERSION "@PROJECT_VERSION@"
...
This will take version.h.cmake (template) ... |
72,628,666 | 72,628,915 | Given an `int A` Is there a strong guarantee that `A == (int) (double) A`? | I need a strong guarantee that int x = (int) std::round(y) will always give the correct results (y is finite and "humanly", e.g. -50000 to 50000).
std::round(4.1) can give 4.000000000001 or 3.99999999999. In the latter case, casting to int gives 3, right?
To manage this, I reinvented the wheel with this ugly function:
... | Assuming int is 32 bits wide and double is 64 bits wide (and assuming IEEE 754), all values of int are exactly representable in a double.
That means std::round(4.1) returns exactly 4. Nothing more nothing less. And casting that number to int is always 4 exactly.
|
72,629,731 | 72,629,959 | c++11 two critical sections can use nested lock_guard? | If I have two critical sections, and I make two corresponding mutex to protect each of them.(I think it is necessary to precisely control when to lock because they use in different times and scenario, Q1:is it really so?)
For example:
bool a;//ignore atomic_bool, because in actual, the data structure is more complex
mu... | I think a problem here is that
if (bool x = true)
{
// x is in scope
}
else
{
// x is STILL in scope!
x = false;
}
So the first lock on mut_a is still held in the else block. Which might be your intention, but I would consider this not an optimal way to write it for readability if that were so.
Also, if it... |
72,630,190 | 72,630,352 | My object is being called has different values even though I had assigned value for it | I am currently doing my homework that requires me to create a dispenser machine system, which the below code is only a part extracted from my actual code, but it contains the core of the problem i faced.
Console Result:
enter image description here
As shown in the console, the dispenser show 50 50 50 50 which is the de... | The variable dt in main() and in staffDispenser are two distinct variables. The changes done to dt variable in staffDispenser are local to that function, it is not reflected into the main.
If you want to update the dt variable of main in staffDispenser function you need to pass it by reference.
void staffDispenser(disp... |
72,630,439 | 72,630,555 | Including specific paths when using CMake | I have the following code structure:
--src
|--common--include--common---datatype--a_h_file.hpp
| |
| --src
|
|--main_lib
| |--------include-----one---one.hpp
| |
| |---src--------one----one.cpp
| CMakeLists.txt
|---main.cpp
CMakeLists.t... | First, define an INTERFACE target for your common directory in the top-level CMakeLists.txt:
add_library(Common INTERFACE)
target_include_directories(Common INTERFACE common/include)
Then just link against it in your targets, which will propagate the include directories:
target_link_libraries(mainpub PUBLIC Common)
|
72,630,561 | 74,148,683 | boost::asio::steady_timer get stuck at WaitForSingleObject when built as a DLL | I've just encountered a weird and devastating problem that I couldn't find any information about it anywhere.
asio::steady_timer timer(m_context);
This asio::steady_timer works perfectly fine if I'm building it as an EXE, but if it's built as a DLL it will be stuck waiting for WaitForSingleObject (in win_thread.ipp f... | This was solved by making these two class members or global variables and not initializing them in the entry point of the DLL.
asio::io_context context;
asio::steady_timer timer(context);
|
72,630,872 | 72,722,875 | Having a dificult time with Directx11 dynamic texture Map/Unmap | I have been trying to upload a dynamic texture with Map/Unmap but no luck so far.
Here's the code im working with
D3D11_MAPPED_SUBRESOURCE subResource = {};
ImmediateContext->Map(dx11Texture, 0, D3D11_MAP_WRITE_DISCARD, 0, &subResource);
Memory::copy(subResource.pData, (const void*)desc.DataSet[0], texture->get_width(... | When using map, the subResource rowPitch that is returned by the map function is the one that is expected for you to perform the copy (you can notice that you never send it back to the deviceContext, so it's read only).
It is generally a power of 2, for memory alignment purposes.
When you provide initial data in an (im... |
72,631,196 | 72,724,434 | Enable exception support in Emscripten | I am using Bazel (5.2.0) to build an emscripten app. My setup looks like this:
main.cpp:
#include "emscripten.h"
#include <iostream>
int main(int argc, char **argv) {
throw std::runtime_error("error!");
}
BUILD.bazel:
load("@rules_cc//cc:defs.bzl", "cc_binary")
load("@emsdk//emscripten_toolchain:wasm_rules.bzl",... | You should set Enable C++ Exceptions option to Yes and Enable Objective-C Exceptions to Yes. If you still have the problem then refer
|
72,632,162 | 72,632,478 | std::conditional for compile time inheritance paired with std::enable_if for compile time methods | I wanted do design a template class with two arguments that at compile time inherited based on the template arguments one of two mutually exclusive base classes.
I wanted to keep it simple for me so came up with this working example. The inheritance condition i got with std::conditional based on the template arguments.... | In my opinion you're much better of partially specializing the template, since the entire implementation for both versions are completely independent. This way you can also not inherit any class instead of inheriting an empty class.
template<typename T>
class NonEmpty {
protected:
std::vector<T> mObjects;
};
templ... |
72,632,309 | 72,632,908 | Is there any problem using a reference to a std::set key to erase itself? | Consider the following code
std::set<int> int_set = {1, 2, 3, 4};
for(const auto& key : int_set)
{
if(key == 2)
{
int_set.erase(key);
break;
}
}
The code runs as expected, but is it safe?
It feels wrong to be using a reference to a key to erase itself from a set, as presumably once the era... | This is safe in the code provided since you break out of the loop without attempting to use the reference (key) again (nor implicitly advance the underlying iterator that for-each loops are implemented in terms of, which would happen if you did not break/return/throw/exit()/crash, when you looped back to the top of the... |
72,632,973 | 72,639,273 | Make failing with not used function | I am trying to build my code.
After I do cmake .. from a build directory I do make -j8 and I get
[ 90%] Building CXX object common/CMakeFiles/common.dir/src/utils/path_util.cpp.o
[ 95%] Linking CXX executable myproj
CMakeFiles/myproj.dir/main.cpp.o: In function `cv::String::~String()':
main.cpp:(.text._ZN2cv6StringD2Ev... | First, thanks @fabian for the help and pointers
I finally realized that the problem was not in my main.cpp but in a hpp file that main calls. This one.hpp file included another hpp file that was the one that caused the problem (When I commented it, the problem disapeared)
So what I did was change the CMakeLists.txt of ... |
72,633,758 | 72,634,064 | Is there a way to static_assert a variable reference given in a template parameter? | struct Config
{
int version = 1;
};
template<Config& config /* , ... */>
struct Peripheral
{
const Config config_ = config;
static_assert(config_.version > 1, "Config version must be greater than 1");
/* ... */
};
Config myConfig;
int main()
{
myConfig.version = 5;
Peripheral<myConfig> peri... | If you want the value of myConfig to be used at compile-time, then you should mark it constexpr and give it its value directly in the initializer. Whether it is a static or automatic storage duration variable is then secondary:
constexpr Config myConfig = { .version = 5 };
// alternatively before C++20 for example
// c... |
72,634,961 | 72,656,463 | Template with STL algorithms slows down function a lot | because pre-computing some keys into a std::vector saved me some time on the followed std::sort(before that the keys were recomputed every time) and I wanted to reuse it on different places, I tried to template this code:
void myFunction() {
QList<const Object*> objects = getObjectsList();
const SomeCapturedTyp... | Ok so I changed my template to this for more generalization:
template <class T1, class T2, class Lambda> void transformThenSortList(QList<T1>& objects, Lambda&& transformLambda) {
typedef std::pair<T2, T1> Pair;
typedef std::vector<Pair> Transformed;
Transformed transformed = Transformed(objects.length());
... |
72,635,511 | 72,635,729 | I can copy or pass by value unique pointers, how is this possible? | What I've read from multiple sources states that, An unique_ptr cannot be copied to another unique_ptr, passed by value to a function, or used in any C++ Standard Library algorithm that requires copies to be made. However, I can seem to be able to do all those things.
#include <iostream>
#include <memory>
int test(int... | You indeed can't copy a unique pointer, this won't compile:
std::unique_ptr<int> uniquePtr1(new int(4));
std::unique_ptr<int> uniquePtr2(uniquePtr1);
You'd need to move uniquePtr1 into uniquePtr2:
std::unique_ptr<int> uniquePtr2(std::move(uniquePtr1));
What your code is doing is copying the value pointed to by the po... |
72,635,668 | 72,636,109 | A Simple Gradient Effect | I need to code the fragment shader so that the triangle has a simple gradient effect. That is, so that its transparency decreases from left to right.
I tried this but it fails:
#version 120
uniform float startX = gl_FragCoord.x;
void main(void) {
gl_FragColor[0] = 0.0;
gl_FragColor[1] = 0.0;
gl_FragColor[2]... | vYou can not initialize a uniform with gl_FragCoord.x. A uniform initialization is determined at link time.
uniform float startX = gl_FragCoord.x;
uniform float startX;
You have to set the unform with glUniform1f.
gl_FragCoord.xy are not the vertex coordinates. gl_FragCoord.xy are the window coordinate in pixels. You... |
72,635,920 | 72,649,934 | Extra memory consumption b/w l +=c and l = c+l? | I was solving a question in which I have to add a single character in front of a string multiple times so I just use
string l ="";
char c = 'x';
l = c+l;
but when I run it, it shows the memory limit is exceeded?
Instead when I used
string l ="";
char c = 'x';
l += c;
reverse(l.begin(),l.end());
It was compiled succes... | As others have mentioned adding a char to the front of the string will create a new string and copy every single time while adding a char to the back will grow the capacity in larger steps and only copy occasionally.
But both ways use <= 2N memory. The used memory for both ways isn't too different. The issue with addin... |
72,635,933 | 72,636,053 | Why cant we declare std::function with auto | I got following code:
template<typename T>
concept con1 = requires(T t, std::string s){
{ t[s] } -> std::same_as<std::string>;
};
using function_signature = std::function<void ( con1 auto functor)>; // ERROR!
while the compiler has no problem me defining the lambda directly:
auto lambda_1 = [](con1 auto functor... | auto in a lambda parameter list doesn't represent one single automatically-inferred type like it would in a variable initialization, it represents that the lambda has a templated operator() which has a whole parameterized family of function signatures.
You can't instantiate a template that expects a concrete type (and ... |
72,636,331 | 72,636,683 | Using nested class as parent class template parameter? | I have a nested class definition that I wanted to pass down as the parent class (class containing the nested class, not the class that's being inherited) template parameter. Since the template does not seem to be aware of the nested class's existance, I tried to pass it down as an incomplete type, only to read later th... | There is no solution for your specific case with the requirements you gave, as far as I can tell.
Directly using C as template argument can't work in any way, simply because at that point the compiler hasn't seen yet that C is declared as a member class of A and because there is no way to declare the nested class befor... |
72,636,361 | 72,636,392 | Edit Object in Vector and return Vector | I am new to programming. I am trying to make a Banking application, where a User enters their name and gets a Username set.
I am messing around with Classes for the first time.
I am trying to pass a std::vector to a function to add Data into it. Do I have to return the values that I want to set into the Vector? Or can... | You can pass a non-const reference of your vector to your function, e.g.
void add_value(std::vector<int>& values, int value) {
values.push_back(value);
}
// later
std::vector<int> values;
add_value(values, 5);
// values now contains {5}
If you have a vector of objects you can first index one of them, then call a ... |
72,637,060 | 72,637,347 | Temporary lifetime extension mixed with copy elision object on clang | I have an issue in a project of mine that uses aggregate types to extend the lifetime of temporaries in a relatively safe manner by making aggregates that contain references uncopyable and unmovable, however mandatory copy/move elision (C++17) don't care if an object is copyable or movable. This is all well and good as... | This looks like a bug in Clang.
With mandatory copy elision B b = B{ K{} }; should be fully equivalent to B b{K{}}; and lifetime extension of the K object to the lifetime of b applies there since it is aggregate initialization. No other temporary B object exists which could contain a reference which is bound to the tem... |
72,637,402 | 72,639,636 | How do I write a hash function for an unordered_map that takes a pair as key, but return the same value if I switch the order of the pairs members? | I'm trying to create an std::unordered_map that takes a std::pair as key, and returns a size_t as value. The tricky part for me is that I want custom hash function for my map to disregard the order of the members of the key std::pair. I.e:
std::pair<int,int> p1 = std::make_pair<3,4>;
std::pair<int,int> p2 = std::make_p... | Using a custom class for equality testing:
class Equal_point_pair
{
public:
bool operator(
const std::pair<Point *, Point *> p1,
const std::pair<Point *, Point *> p2) const
{
// Verify if both pair are in the same order
const bool p1Asc = p1->first-> id < p1->second-> id;
... |
72,637,849 | 72,639,008 | googletest SetUpTestSuite() does not run | From : https://google.github.io/googletest/advanced.html#sharing-resources-between-tests-in-the-same-test-suite . I am using 1.11 googletest version.
I am trying to utilize this feature in the following tests:
Game_test.h
class Game_test : public :: testing :: Test
{
protected:
Game_test() = default;
virtua... | Several things:
The example is SetUpTestSuite, not SetUpTestCase.
SetUpTestSuite should be a static member.
field should be a static member of the class if used in SetUpTestSuite.
SetUpTestSuite runs once per test suite, not once per test case.
If you want something to run once per test case, use SetUp, which is a non... |
72,638,117 | 72,638,280 | Different ways of opening and binding a UDP socket with Boost Asio c++ | I'm trying to create a simple UDP broadcast class in c++ using the Boost Asio library.
Specifically, in the main class I'd like to instantiate a socket to both send and receive data. But I've seen three different ways of doing so, and I wanted to ask if anyone knew the difference? These are the methods I've seen:
The f... | The first method will create a socket without binding to a specific port. This is fine if you don't care about someone initiating the messages with you. IE: You send a message to a recipent, they can reply back because they received the sender's IP and Port along with the message.
If you want someone to be able to mess... |
72,638,289 | 72,653,736 | ESP32 SPI - SPI.h library provided by Arduino | I got a question regarding the SPI.h driver which is available in Arduino IDE examples. it seems there is only a function for transmission and there is no function for receiving data using SPI.
Here is the function used for transfer:
uint8_t transfer(uint8_t data);
which is defined in this class:
uint8_t SPIClass::tra... | Short answer is yes, that could be the data send back from the Slave.
A more detail answer:
The function transfer() in SPI is bi-directional, as SPI has separate output (MOSI) and input (MISO) line, when you clock-out one byte, it also clock-in one byte from Slave. Technically you can receiving data while sending data.... |
72,638,308 | 72,651,964 | How do I simulate C#'s {get; set;} in C++? | I am experimenting with lambda functions and managed to recreate a "get" functionality in C++. I can get the return value of a function without using parentheses. This is an example class, where I implement this:
using namespace std;
struct Vector2 {
float x;
float y;
float length = [&]()-> float {return s... | While other solutions also seem to be possible, this one seems to be the most elegant :P
using namespace std;
struct Vector2 {
float x;
float y;
float init_length = [&]()-> float {return sqrt(x * x + y * y); }();
float init_angle = [&]()-> float {return atan2(y, x); }();
__declspec(property(get = ... |
72,638,320 | 72,639,121 | How to check if characters forming string are different length | I want to create a function that takes in a string as a parameter and checks if the number of occurrences of the individual letters are different.
"OBDO" should display NO, because O occurs twice, but B and D occur once.
"AABBB" should display YES, because A occurs twice, and B occurs three times.
My code seems to work... | You can reduce the whole thing (if I understood the question correctly) to just a few rather simple steps:
Sort the input string, so duplicate characters end up next to each other.
produce a list (or vector) of the occurrence counts of each distinct character.
test, if the list (or vector) of those occurrence counts c... |
72,638,416 | 72,638,655 | Destructor of child class not being called | I'm currently working on a game as a project for my University. It's being made in C++ with SDL2.
I have a vector that holds pointers of the class Enemies, which is an abstract parent class of the Plant class. In the constructor of my enemy manager, I am pushing back a pointer to a Plant object into the enemies vector.... | I got the answer from Philipp's comment!
I had forgotten about virtual destructors, thanks for that!
And for everyone that is mentioning "smart pointers", we haven't covered them in our course so I am not allowed to use them :/.
|
72,638,542 | 72,639,412 | Return Type Resolver and ambiguous overload for 'operator=' | I've copied code from this wiki and it works.
The problem occurs when I make this code:
int main()
{
std::set<int> random_s = getRandomN(10);
std::vector<int> random_v;
random_v = getRandomN(10);
std::list<int> random_l = getRandomN(10);
}
My compiler (gcc trunk) prints out this error:
error: ambiguous overloa... | The issue is that, from the conversion operator's signature alone, the compiler can't tell if it should convert getRandomN(10) to a std::initializer_list<int> and then assign that to random_v or convert getRandomN(10) to a std::vector<int> and then assign that to random_v. Both involve exactly one user-defined convers... |
72,638,625 | 72,638,749 | C++ function to check whether value exists in tuple | I'm a total beginner to C++, and I am trying to code a program that checks user input to make sure it is a valid option.
Here's my code so far:
#include <iostream>
#include <string>
#include <tuple>
int UserInputCheck() {
int x;
cout << "Options: 1,2,3 or q. \n \n Choose an option:";
cin >> x;
tuple<in... | static inline bool isValid(int input) {
static const std::vector<int> valids = {1, 2, 3};
return std::any_of(valids.begin(), valids.end(),
[&input](const auto &s) { return input == s; });
}
This function can do the coffee
EDIT:
String version
static inline bool isV... |
72,638,827 | 72,638,946 | How to detect block devices on Linux? | With C++ on Linux, how does one detect block devices? Right now, I'm using this code:
for (const auto &entry : std::filesystem::directory_iterator("/dev/"))
{
std::string name = entry.path().filename().string();
if (name.find("sd") == 0 || name.find("nvme") == 0 || name.find("hd") == 0 || name.find("vd") == 0 |... | std::filesystem::directory_entry has an is_block_file() method for this exact purpose:
Checks whether the pointed-to object is a block device.
For example:
for (const auto &entry : std::filesystem::directory_iterator("/dev/"))
{
if (entry.is_block_file())
{
std::cout << "Found device: " << entry.path(... |
72,638,829 | 72,638,934 | Interpretation of access decoration of member functions | In C++11 and later, one can decorate the member function with &, const&, oe && (or other combinations).
If one has several overloads, and at least one is specified like this, the others must follow the same convention.
Pre C++11 style:
struct A {
void f() const {} // #1
void f() {} // #2
};
C++11 and lat... | The qualifiers have the exact same meaning as if they were the qualifiers on the hypothetical implicit object parameter which is passed the object expression of the member access expression.
So, #4 can not be called on a prvalue, because a non-const lvalue reference can not bind to a prvalue, explaining why A{}.f(); do... |
72,639,072 | 72,663,388 | Can't get correct value with QSettings and custom type | I am trying to read a small struct from my ini file using QSettings. Writing works fine, but when I try to read it back I always get the default value out of QVariant.
This is the structure definition:
struct CellSize {
int font;
int cell;
};
inline QDataStream& operator<<(QDataStream& out, const CharTableView... | I solved the issue! I had to add qRegisterMetaType<CharTableView::CellSize>() inside CharTableView constructor.
|
72,639,533 | 72,641,309 | Writing to file using overloaded operator << - problem with recursion | I´m currently learning C++ and I decided to try to write my own "log tool". My goal is, that I can write just something like this:
logger<<"log message";
I have this problem - when I wrote operator << overloading function, the IDE compiler warned me, that it is infinite recursion.
Here is the code of operator overload... | In order to invoke your overloaded operator<< from anywhere, you need a Logger object on the left side and a char* pointer (BTW, it should be const char* instead) on the right side.
Inside your overloaded operator<<, this statement:
logger << message
is trying to invoke an operator<< with a Logger object on the left si... |
72,640,089 | 72,640,750 | Getting huge random numbers in c++ | for my final OOP project i have to create a "Streaming service" in c++, i am basically done with the whole program, i just have one problem. I give a rating to each movie, but when i print this rating, i just get some huge random numbers instead of the actual rating.
here is my movie class and the definition of the fun... | You forgot to set rating to anything in your constructor. That's why its value is 'random'
Change this
movie::movie(int _id, std::string _name, int _length, std::string
_genre, int _rating) : video(_id, _name, _length, _genre){}
to this
movie::movie(int _id, std::string _name, int _length, std::string
_genre, int _r... |
72,640,180 | 72,640,510 | Why can't I access private members of class Box in operator<<? | Why can't I access private functions of class Box in ostream& operator<<(ostream& out, const Box& B){cout << B.l << " " << B.b << " " << B.h << endl; }?
#include<bits/stdc++.h>
using namespace std;
class Box{
int l, b, h;
public:
Box(){
l=0;
b=0;
h=0;
}
Box(int l... | The problem is that you don't have any friend declaration for the overloaded operator<< and since l, b and h are private they can't be accessed from inside the overloaded operator<<.
To solve this you can just provide a friend declaration for operator<< as shown below:
class Box{
int l, b, h;
//other code here ... |
72,640,483 | 72,641,828 | How can I declare this function to return a TFuture? UE5 C++ | I have been trying to declare this function in my header file (using ue5 c++) and I get the compiler telling me this error:
Unrecognized type 'TFuture' - type must be a UCLASS, USTRUCT, UENUM, or global delegate. [UnrealHeaderTool ParserError]*
static TFuture<UTexture2D*> ImportImageFromDiskAsync(UObject* Outer, cons... | Okay I figured it out.
TFuture cannot be returned on a function that would be exposed to blueprints. So removing the UFUNCTION() tag above it solves the issue.
|
72,640,793 | 72,641,198 | not terminating scanf() or gets() after taking newline | I have to take three inputs in a single string.
The code to take the input is:
char msg_send[1000];
gets(msg_send);
The input is like
GET /api HTTP/1.1
id=1&name=phoenix&mail=bringchills@ppks.com
That means there is a newline after the fist line GET /api HTTP/1.1. The next line is an empty newline. The input takin... | In cases like these, you should just use getchar in a loop:
#define MAX_MSG_BUF 1000
char char msg_send[MAX_MSG_BUF];
// you should wrap the below code in a function, like get3lines(buf, buf_size)
unsigned index = 0;
unsigned line_count = 0;
const unsigned buf_size = MAX_MSG_BUF;
do {
int tmp = getchar();
... |
72,640,804 | 72,640,924 | How to avoid errors in Vscode for putting header files in a separate directory than src | Ok so I am having an issue with errors in VSCode. Basically I decided to reorganize and move my header files into a separate folder, "include". My directory put simply is as follows:
-build
-include
|-SDL2
|-SDL2_Image
|-someHeaderFile1.h
|-someHeaderFile2.h
-src
|-main.cpp
|-someCppFile.cpp
-Makefile
My Makefil... | You need to put that folder's path to the Include path. One way to do that is shown below. The screenshots are attached with each steps so that it(the process) would be more clear.
Step 1
Press Ctrl + Shift + P
This will open up a prompt having different options. You have to select the option saying Edit Configurations... |
72,641,269 | 72,646,827 | Vulkan Image export handle to Win32 or fd. How to reverse win32 handle to obtain image information? | When I export a Win32 handle from the Vulkan image. Vulkan for another process. At this time, how to find the information of Vulkan Image according to win32 Handle reversely?
I created a Handle with Vulkan in a process and created OpenGL's texture according to the Handle. It is then shared with another process. So ... |
I don't know what the information of image is.
Yes, you do. You created it in Vulkan. You know its size. You know its format. You know everything about the image.
If you can pass a handle to this function to create an OpenGL texture, then you can pass the other information too.
There is no API to retrieve any informa... |
72,641,526 | 72,641,592 | type trait with enum as specialisation | I would like to have a type trait that would be false for any parameter T except for the enum value Http::Get
template<typename T>
struct isGet : public std::false_type{};
template<>
struct isGet<Http::Get> : public std::true_type {};
However, it seems that the c++ compiler does not allow me to specialise a templ... | typename and class expect types. Http::Get is (presumably) not a type, but a value, like any other constant (42, 'A', false etc.). And you obviously cannot pass a value when a type is expected.
The solution would be different depending on your use cases. For example:
#include <type_traits>
enum class Http {
Post,
... |
72,642,840 | 72,642,948 | Cannot assign reference value to result of std::invoke | I have a lambda that either appends an object and returns it or it returns an already existing object. On GCC, i receive the error:
cannot bind non-const lvalue reference of type 'T&' to an rvalue of type 'T'
Here is an example:
#include <iostream>
#include <cstdlib>
#include <functional>
struct foo {
int a;
};
... | return type of lambda is not a reference by default, you have to specify it with trailling return type( -> foo&, -> decltype(auto)):
[&foos, &new_index, append]()-> foo& { /*..*/ }
or return a type which handles reference (as std::reference_wrapper):
[&foos,&new_index,append]() {
if(append) {
new_index = f... |
72,643,091 | 72,643,313 | How to get an element of type list by index | How can an element of a type list using L = type_list<T1, T2, ...> be retrieved by index, like std::tuple_element, preferrably in a non recursive way?
I want to avoid using tuples as type lists for use cases, that require instantiation for passing a list like f(L{}).
template<typename...> struct type_list {};
using L =... |
I want to avoid using tuples as type lists for use cases, that require
instantiation for passing a list like f(L{})
If you don't want to instanciate std::tuple but you're ok with it in
unevaluated contexts, you may take advantage of std::tuple_element to
implement your typeAt trait:
template <std::size_t I, typename ... |
72,643,141 | 72,643,430 | How to pass array of object pointers to function? | I am having trouble passing an array of object pointers from main() to a function from different class.
I created an array of object pointers listPin main() and I want to modify the array with a function editProduct in class Manager such as adding new or edit object.
Furthermore, I want to pass the whole listP array in... | Since the listP is a pointer to an array of Product, you have the following two option to pass it to the function.
The editProduct can be changed to accept the pointer to an array of size N, where N is the size of the passed pointer to the array, which is known at compile time:
template<std::size_t N>
void editProduct... |
72,644,982 | 72,645,016 | C++ Instantiate Template Variadic Class | I have this code:
#include <iostream>
template<class P>
void processAll() {
P p = P();
p.process();
}
class P1 {
public:
void process() { std::cout << "process1" << std::endl; }
};
int main() {
processAll<P1>();
return 0;
}
Is there a way to inject a second class 'P2' into my function 'processAl... | With fold expression (c++17), you might do:
template<class... Ps>
void processAll()
{
(Ps{}.process(), ...);
}
|
72,645,270 | 72,645,987 | Why does my function only work with lvalues? | I have a function that returns a lowercase string:
constexpr auto string_to_lower_case(const std::string& string) {
return string
| std::views::transform(std::tolower)
| std::views::transform([](const auto& ascii) { return static_cast<char>(ascii); });
}
and I expect that function return the same r... | Some issues:
The temporary std::string that is created when you call the function with a char[] goes out of scope when the function returns and is then destroyed. The view you return can't be used to iterate over the string after that.
You take the address of std::tolower which isn't allowed since it's not on the list... |
72,646,906 | 72,647,015 | C++ Problem with overriding base class variable | I have 3 classes that derive from each other:
class Shape
{
public:
float r;
};
class ThreeDimentional : public Shape
{
public:
virtual float area() = 0;
virtual float volume() = 0;
};
class Sphere : public ThreeDimentional
{
public:
float r;
float area() {
return 4*pi*pow(r, 2);
}
... | You can't override data members. You can override only virtual member functions.
If every Shape is supposed to have a radius, then Sphere shouldn't declare another r (which will just hide the one in Shape depending on the context from where it is named).
If only a Sphere is supposed to have a radius, then it shouldn't ... |
72,647,305 | 72,657,037 | Interrupting the execution of a method | I have a case where I need to call a method that runs for infinite time on specific occasions: obj.run()
The program will have a callback that should start this method or stop it based on a received message.
How can that be achieved?
Obs.: obj doesn't seem to have a destructor and the function is meant to stop only whe... | One way to achieve this is by using boost::thread::interrupt
like in the code from this gist
#include <boost/thread.hpp>
#include <iostream>
using namespace std;
void ThreadFunction() {
int counter = 0;
for (;;) {
cout << "thread iteration " << ++counter << " Press Enter to stop" << endl;
try {
//... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.