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 |
|---|---|---|---|---|
68,168,085 | 68,168,150 | What changed with "converting constructor"s at C++11? | Today I was surprised by this paragraph at cppreference:
Converting constructor
A constructor that is not declared with the specifier explicit and which can be called with a single parameter (until C++11) is called a converting constructor.
The "(until C++11)" bit seems to be referring to the phrase "which can be cal... | An example with two parameters is given later in the page you cited:
A a4 = {4, 5}; // OK: copy-list-initialization selects A::A(int, int)
|
68,168,182 | 72,864,525 | How to connect to websocket server using boost C++ | My websocket server URL is ws://localhost/webstream/wsocket
Iam trying to create a C++ websocket client that connects to this server using boost
tcp::resolver resolver{ioc};
_pws = new websocket::stream<tcp::socket>(ioc);
// Look up the domain name
// my server is http://localhost/webstream/wsocket
_host = "localhost"... | Similar to this issue
The right way to access the websocket url: ws://localhost:5000/webstream/wsocket , you need to set
host_ = "localhost";
port_ = 5000;
after resolve the endpoint and connect, the path /webstream/wsocket was needed at handshake
_pws->handshake(host, "/webstream/wsocket")
In this way you may succ... |
68,168,479 | 68,168,578 | Matching constness of function argument for return type with concepts | C++ containers do not hold const elements, e.g. you have const std::vector<int>, not std::vector<const int>.
This is a bit unfortunate when I am trying to adjust type of return value of a function based of if passed container was const or not.
Here is motivating example, please do not focus too much on algorithm or use... | Ranges already gives us a way to get the correct reference type of any range:
std::ranges::range_reference_t<R>
If R is vector<int>, that's int&. If R is vector<int> const, that's int const&. If R is span<int> const, that's... still int& because span is shallow-const (which is something your trait gets wrong, because ... |
68,168,587 | 68,169,111 | Specifying deduction guides for template classes with function pointers | I have the following template class:
double* createSomething(){return new double{};}
template<typename T>
class B {
public:
using BuilderFcnT = T (*)();
explicit B(BuilderFcnT a) : ab(a) {}
private:
BuilderFcnT ab;
};
//This did not work:
//template<typename T> B(typename B<T>::BuilderFcnT) -... | The issue with B(typename B<T>::BuilderFcnT) is you are trying to use a type that depends on T, but you are in the process of deducing T. It's like the chicken and egg problem. In this case you just need
template<typename T> B(T(*)()) -> B<T>;
|
68,168,887 | 68,169,486 | C++ I'm trying to end this infinite loop to find even numbers between 0 and the users entered value | This program is supposed to find the even numbers between 0 and the users entered value like 500 for example. I can only use for and if loops.
#include <iostream>
using namespace std;
int main()
{
int value = 0;
//Ask user to enter a number between 0 and 501
cout << "Please enter a value between 0 and 50... | Your if statement has no use because it is not in a while loop. Meaning that if the user enters a number lower than 0 or higher than 501, the code will execute normally. You can use this instead:
while (true) {
if (value < 0 || value > 501) {
cout << "ERROR! The value you entered is out of range!\n";
cout <... |
68,168,897 | 68,169,044 | How to vector::emplace_back a class that has a shared_mutex? | How can I emplace_back a class that has a shared_mutex?
It looks like that a shared_mutex makes a class no longer MoveConstructible/CopyConstructible.
Compiling my code gives me result type must be constructible from value type of input range. And no matching function for call to construct_at(class_with_lock*&, class_w... | Mutexes are not safe to copy/move in general; it simply doesn't compile, and the action itself doesn't make sense.
If you have a type with a mutex, and you are copy/moving it, you are almost certainly doing something wrong.
A vector of a class with a lock is bad smell, don't do it.
The semantics start acting really, re... |
68,169,599 | 68,169,834 | Convert C++ API to a function in the project | For e.g., rand() is a API for generating random numbers. Now i want to create my own rand() in the code. So the new rand() should overload the API already defined in library.
void getRandomValues () {
int a = rand();
......
......
int b = rand();
}
Above is a sample code.
Now i want to change above code to... | C++ doesn't support function overloading with multiple return types. So if you create a function int rand(), it will have to return an int unless you create other functions with different arguments.
Regarding the creation of random numbers, the STL has a library just for that. Take a look at the <random> header.
Regard... |
68,169,702 | 68,170,274 | Cannot deduce type of indirectly called template function | The following code fragment is a stripped-down version of what should become an optimization algorithm:
template<typename F>
double helper(F f, double x)
{
return x;
}
template<typename F, typename L>
double optimize(F f, double x, L line_search)
{
double y = line_search(f, x);
return y;
}
int main()
{
... | You could add a default type for L which includes F:
template<typename F>
double helper(F f, double x) {
return f(x);
}
template<typename F, typename L = double(*)(F, double)> // <- here
double optimize(F f, double x, L line_search) {
double y = line_search(f, x);
return y;
}
It will then find the correc... |
68,169,744 | 68,169,771 | C++ Multiple Definition on Compilation | I did an exercise in C++ which search for strings inside files and then stores what he found.
My problem is when I had the main() function inside the file "FilesSearcher.cpp" I got no problem during the compilation, after I moved the "main()" function to the file "test_file_searcher.cpp" I'm getting this error:
g++ tes... | const char *SEARCH_MATRIX[] = {"test\0", "prova\0", "lol\0", "asd\0", "lmao\0", "rotfl\0"};
Is defined in a header file. Each time you include this, in a different CPP file, you get that defined in that translation unit.
Put inline in front of these symbols. That is a keyword whose modern meaning is to allow it to be... |
68,170,343 | 68,170,442 | c++ swapping content of array - Selection Sort | I'm new to C++. I was attempting to write a function for selection sort the following way.
void selection_sort(int* m[], int array_size) {
for (int i = 0; i < array_size; i++)
int min_ind = i;
for (int j = i+1; j < array_size; j++){
if (m[min_ind] > m[j]){
min_ind = j;
}
... | You allocated dynamically an array of objects of the type int.
int *sel_nums = new int[n];
This array you are going to pass to the function selection_sort. So the function declaration will look at ;east like
void selection_sort( int m[], int array_size );
The compiler implicitly adjust the parameter having the array... |
68,170,349 | 68,950,405 | Include different file with defining preprocessor variable | I saw very nice example for using different classes using -D compile switch.
However, in my use case, the thing is bit different and I can don't know how to do it.
For multiplexing API, I have 3 classes in 3 different files:
poll.h -> class PollSelector -> generic poll() works everywhere
epoll.h -> class EPollSele... | generic poll() works everywhere
Linux only epoll support
MacOS only kqueue
I guess you intent to do:
#if __LINUX__
#include "selector/kqueue.h"
using MySelector = KqueueSelector;
#elif __OSX__
#include "selector/kqueue.h";
using MySelector = EPollSelector;
#else
#include "selector/poll.h";
using MySelector = PollSelec... |
68,170,395 | 68,170,501 | Out of 3 identical sscanf calls, the middle one does not work | I have no idea what is happening
In my C++ program I wanted to simply read some parameters from the command line.
variables are defined at beginning of main():
uint32_t sampling_frequency;
uint32_t samples_per_pixel;
uint32_t total_samples;
uint16_t amplification;
after some verification of argc, I'... | The PRI* macros are only suitable for printing, not scanning.
If you want to use these macros with sscanf(), you need to use the SCN* versions.
Like so:
sscanf(argv[3], "%" SCNu32, &sampling_frequency);
sscanf(argv[4], "%" SCNu32, &samples_per_pixel);
sscanf(argv[5], "%" SCNu16, &lification);
|
68,170,425 | 68,170,660 | Get the flattened tuple type from an arbitrarily nested tuple type | I would like to have a type trait flatten_tuple_t which can create a flattened tuple type from an arbitrarily nested one. The following code snippet illustrates what is expected from flatten_tuple_t.
template <typename T>
struct flatten_tuple {
using type = T;
};
// The real implementation goes here
// ...
// ...
tem... | You can make std::tuple_cat() do the heavy lifting for you.
The only tricky part is having to wrap the base types in a std::tuple<>. But since we need to use partial specialization to extract the types, we can just use the base template for that instead of leaving it undefined.
template <typename T>
struct flatten_tupl... |
68,170,864 | 68,170,950 | Where does "this" point to in parent class (c++)? | I have one question about C++ programming. If I have two classes called parent and child respectively. The child is derived from the parent. When I create an object either on the stack or the heap, it has to be initialized by the constructors of both classes. I find that the "this" ptrs are pointing to different addres... | this always points to the beginning of the instance of whatever type it (this) is.
That probably sounds confusing, so let's try to visualize it. Now what I'm about to describe isn't part of the C++ standard, and every implementation is free to change it as they wish or need, but it's generally some form of this:
------... |
68,170,912 | 68,170,996 | std::cin.read() fails to read stream | I'm implementing a native host for a browser extension. I designed my implementation around std::cin instead of C-style getchar()
The issue here is that std::cin not opened in binary mode and this has effects on Windows based hosts because Chrome browser don't work well with Windows style \r\n hence I have to read it i... | Solution:
buffer.reserve(std::size_t(messageLength) + 1);
should be
buffer.resize(std::size_t(messageLength) + 1);
or we can presize the buffer during construction with
std::vector<char> buffer(messageLength +1);
Problem Explanation:
buffer.reserve(std::size_t(messageLength) + 1);
reserves capacity but doesn't chan... |
68,171,999 | 68,172,524 | Replacing the value of map elements isnt working | I'm just Learning about std::map and its functions . I recently got this problem. I tried making a program which prints out a grid type data where I used std::map for the keys and values . The program prints out fine but I wanted to make a program where once I erased a data in that grid, other data above that should mo... | The order of
for (int i = pair.second; i < 20; i++)
{
m_MapData[{pair.first, i}] = m_MapData[{pair.first, i - 1}];
m_MapData[{pair.first, i - 1}] = 0;
}
is element found to the bottom. When you want to move everything above the item removed down one slot, this isn't all that useful. So lets... |
68,172,433 | 68,172,478 | C++ pointer and increment operator (++) | Recently, I begin to learn C++ language for Pointer series, I knew the pointer is the specific var what is used to hold the address of another variable. And when we change the value at the memory area which the pointer is hold, it also change the value of that var. So then i just wrote the code to do it.
#include <iost... | If we break down your code into the important parts, we see:
int n=5; // 1.
int *p = &n; // 2.
p++; // 3.
(*p)++; // 4. Dereference and increment.
You clearly have a good grip on what 1-3 do in this code. But, 4 is a big problem. In 3, you changed the pointer. The pointer previously pointed to n, after incrementing, ... |
68,172,541 | 68,172,842 | C++20 std::ranges: Range adapter to skip every nth element | I'm trying to get more acquainted with C++20's std::ranges implementation, and I've come across a seemingly simple problem of which I cannot find a standard solution without rolling my own implementation.
The problem is simple: I would like to only access and process every Nth element in a range using a C++20 range-ada... | I don't think there is a range adaptor for this in the standard library.
Ranges-v3 library does however have it:
ranges::iota_view{0, 10} | ranges::stride_view(3)
There is a proposal to add such adaptor into the standard: P1899.
Github Issue says:
Discussed by LEWG in Prague.
http://wiki.edg.com/bin/view/Wg21prague/P... |
68,172,567 | 68,172,613 | Print the squared sum from a list of factors c++ | From the list below, im trying to find a list of factors from 9799, so, i got the factors of 9799 which is 1, 41, 239 , 9799
So i squared each of these factors and sum up by calculator
Supposedly the sum of the squared factors are 96079204, and it can be square root to become 9802
supposedly this line of code is execut... | The trouble comes from the float type for the second loop:
for(float i = 1; i <= number; ++i);
Also, the use of this loop is redundant, you don't need here:
for(float i=range2; i<= range2; i++) { // It will iterate only once
squared_sum = 0; // Already 0
// ...
}
You need to change to this:
int main() {
... |
68,173,089 | 68,180,533 | Using MySQL and Windows Forms Application C++ CLI | I am using C++ CLI Windows Forms Application and connecting to MySQL database on my system itself.
I would like to know how to make the connection secure between the application and the database.
I am using the following constring for connection.
String^ constring = L"datasource=localhost;port=3306;username=****;passwo... | In the String you have mentioned SSLMode is required then I suppose it should be secure
|
68,173,166 | 68,173,193 | vector with zero size after insert an empty vector |
example 1
vector<int> a;
vector<vector<int>> b;
cout << b.size() << endl; // 0
b.insert(b.begin(), a);
cout << b.size() << endl; // 1
example 2
vector<vector<int>> b;
cout << b.size() << endl; // 0
b.insert(b.begin(), {});
cout << b.size() << endl; // 0
My questions:
What is the difference between example 1 ... |
What is the difference between example 1 and example 2?
They have arguments of different type. First passes a vector as an argument and invokes following overload:
constexpr iterator insert(
const_iterator pos,
const T& value);
Second passes an initializer list and invokes the following overload:
constexpr i... |
68,173,226 | 68,173,486 | Overriding of const member function in C++ | Consider the following code:
#include <iostream>
#include<string>
using namespace std;
class Base
{
public:
virtual string print() const
{
return "This is Base class";
}
};
class Derived : public Base
{
public:
virtual string print() const
{
return "This is Derived class";
}
... | Your first question is why it did not give you an error because your function is const. Const function does not prohibit you from overriding it. If you want your function to be not overridden by derived classes you can declare that function final.
virtual string print() const final;
Now this will not be overridable by... |
68,173,505 | 68,173,560 | std::map with key as a struct with three int members | I would like to use a struct with three integer members as a key. How can I overload the < operator. I understand that for two members it could be overloaded as:
bool operator < (const CacheKey& a, const CacheKey& b) {
return a.x < b.x || (a.x == b.x && a.y < b.y);
}
| The most direct approach would be:
class Foo {
friend bool operator<(const Foo&, const Foo&);
int a, b, c;
}
bool operator<(const Foo& lhs, const Foo& rhs) {
return (lhs.a < rhs.a) ||
(lhs.a == rhs.a && lhs.b < rhs.b) ||
(lhs.a == rhs.a && lhs.b == rhs.b && lhs.c < rhs.c);
}
|
68,174,105 | 68,202,192 | Openssl library equivalent of java KeyPairGenerator | I'm trying to send a RSA public key to a Java client from a c++ server. Since the client is running Java I believe the key needs to be formatted in X509. I need to get the key as an encoded char array but can't find the right way.
I need to find the c++ openssl library equivalent of the following:
public byte[] getEnco... | This code, edited from @Afshin's post, generates a RSA key pair and populates a std::vector<unsigned char> with the public key's PEM data base64 decoded. The data in the vector is equivalent to the data in the byte[] generated by the java function getEncodedPubKey() posted in the quesiton. The openssl function that sol... |
68,174,447 | 68,174,588 | ranges-v3 join function to join two containers together | I've been trying to understand the Range-v3 join documentation but I'll be honest, I don't understand it. And I've not been able to find any relevant examples either.
Could someone show me how to create a joined view of two deque vectors please. I've already tried these methods but to no avail.
#include <range/v3/all.h... | As a general suggestion, whenever you want the documentation for something which is in Range-v3, you better pray it is in C++20 too and refer to that. That's the case for join (but not for concat, apparently).
You're looking for concat, not join:
#include <range/v3/view/concat.hpp>
#include <iostream>
#include <vector>... |
68,174,660 | 68,174,751 | function pointer - Expression preceding parentheses of apparent call must have (pointer-to-) function type | I have a class:
#include<map>
class myclass {
public:
typedef std::map<std::string, int(myclass::*)()> mymap;
void Foo() {
UpdateMap();
mymap1["AddToa"]();
mymap1["AddTob"]();
}
private:
int a;
int b;
mymap mymap1;
int AddToa(){ std::cout<< "add 2 to a: " << a+... | You seem to want to call the member function pointer on the current class.
(this->*mymap1["AddToa"])();
Resaerch member access operators.
|
68,174,704 | 68,174,772 | Using Cin Keyword as Variable name in C++ | I came across the following question:
#include<iostream>
using namespace std;
int main ()
{
int cin;
cin >> cin;
cout << "cin" << cin;
return 0;
}
The question asks me to find the output of the program, and the given options are:
(A) error in using cin keyword
(B) cin+junk value
(C) cin+inp... | The question you've come across is absolutely evil, and the author has forgotten to include the correct answer.
The local cin variable (which shadows std::cin due to using namespace std;) is uninitialized, and cin >> cin is the binary bitwise shift-right operator on the uninitialized cin variable.
This behaviour is not... |
68,175,069 | 69,221,893 | macOS: DNSSD crash after calling fd_set on its socket | I have the following code, which crashes my program, upon calling FD_SET.
void handleEvents(DNSServiceRef service, const int32_t timeout)
{
if (!service)
return;
const int fd = DNSServiceRefSockFD( service );
const int nfds = fd + 1;
if (fd < 0)
return;
int32_t result = servus::Result... | The actual issue in this case was that I was having too many file descriptors open, which can be solved by increasing the rlimit with the following code:
void setup_min_fd(int min_fds)
{
struct rlimit rlim;
if (getrlimit(RLIMIT_NOFILE, &rlim) != 0)
return;
if (rlim.rlim_cur > rlim_t(min_fds))
return;
... |
68,175,151 | 68,175,932 | How do I pass a member function to a function that expects a function pointer? | I am using a library that expects a function pointer for a callback function but I would like to pass a member function to it.
The way to do this seems to be by using std::bind and passing the target() as a parameter to the function expecting the function pointer, but I must be doing something wrong.
#include <iostream... | The problem here is that a member function expects a "hidden" first argument that is a this pointer. Loosely speaking, a member function
void Func(int a, double b);
is equivalent to a free function
void Func(MyClass* this, int a, double b);
There is no way to pass a this pointer via ClassicFuncPtr, and std::function ... |
68,175,176 | 68,175,427 | Does ranges::lower_bound have different requirements for the comparison than std::lower_bound? | It seems that using the same comparison functor that worked fine with std::lower_bound() does not work with std::ranges::lower_bound() in C++20. The following code does not compile with either Visual Studio 16.10.2 (and /std::c++latest) or gcc 11.1. I can work around the issue by using a projection instead of a compari... | Yes, it is.
std::ranges::lower_bound's Comp must be
std::indirect_strict_weak_order<const double*, std::vector<A>::iterator>
which expands to lots of variations of
std::strict_weak_order<Comp&, const double&, A&>
which expand to
std::predicate<Comp&, const double&, const double&> &&
std::predicate<Comp&, const double... |
68,175,218 | 68,178,561 | WM_SETFOCUS message and NULL wParam | I've a simple Win32 Windows app with a single, main window. Inside the window procedure I'd like to investigate a WM_SETFOCUS message. The doc says:
A handle to the window that has lost the keyboard focus. This
parameter can be NULL.
This is my case - I'm getting just NULL. What does it mean and why dont I get a han... | 32-bit Windows introduced an asynchronous input model. One consequence of this change is that the focus window is now recorded per thread (or input-attached group of threads).
Initially, a thread attached to an input queue doesn't have a focus window, so the first time a program sees a WM_SETFOCUS message, its wParam i... |
68,175,337 | 68,175,485 | Why is this binary output code causing a memory leak | I am new to C++ and I am trying to output a wave file in. I have had success with binary files in both C# and Java but I am not yet comfortable with C++ yet. I know about that arrays and objects should generally be created on the heap.
It is fine with the strings and the first getter
Whenever it gets to the second gett... | This is speculation based on your functions name, but I think this code:
myFile.write(reinterpret_cast<const char *> (GetDwFileLength()),sizeof (GetDwFileLength()));
is incorrect. Assuming GetDwFileLength() return size as value, it is incorrect to cast it to const char *. You need to save it in another argument and po... |
68,175,555 | 68,180,853 | Is it defined behavior to return const references to objects created with ranges transform? | Is it defined behavior to combine a transformation that creates objects with a transformation that extracts attributes from these objects by constant reference? The following code does not work as expected in Visual Studio 16.10.2, but it seems to work with gcc 11.1.
#include <array>
#include <iostream>
#include <range... | I'm going to write out the full pipeline in one go so it's clearer as to what's going on:
auto values = std::array{"a", "b"};
auto results = values
| transform([](const auto& s){ return A{s}; }
| transform([](const auto& a) -> const auto& { return a.s; });
So first, we create a range of prva... |
68,176,091 | 68,176,569 | Showing wrong value of factorial of a number above 12 if I run a C++ program using recursion | I have the following C++ code to find factorial of a number:
#include <iostream>
using namespace std;
int factorial(int n){
if (n<=1)
{return 1;
}
return n*factorial(n-1);
}
int main()
{
int a;
cout<<"Enter a no: ";
cin>>a;
cout<<"The value of "<<a<<"! is "<<factorial(a);
return 0;
}... | Although formally the behaviour on overflowing an int is undefined, modulo arithmetic on a number that's a power of 2 is a common treatment.
A number like 50! has as its many factors a large power of 2. This accounts for the zeros you are getting as output.
The solution is to use an arbitrary precision integer library.... |
68,176,374 | 68,176,781 | Cannot pass std::unique_ptr in std::function<> | #include <functional>
#include <memory>
#include <string>
#include <iostream>
void foo(std::function<void()> f)
{
f();
}
int main()
{
std::unique_ptr<int> handle = std::make_unique<int>(5);
foo(
[h = std::move(handle)]() mutable
{
std::cout << *h << std::endl;
});
}
Following code... | The std::function requires the function object to be Copy-Constructible, so you can't expect a lamdba to be moved to it. On initialization, it attempts to copy the lambda and so the std::unique_ptr with it, which is a member of this lambda, and, expectedly, fails to do so. What you can do is store your lambda in a vari... |
68,176,492 | 68,176,970 | SIGTRAP on delete[] with small arrays | A weird SIGTRAP error appears in a C++ OpenGL program of mine.
First, a float array with the new[] operator is created like so:
std::vector<ObjFace> faces = readObjFile("sphere.obj");
vertexBufferSize = faces.size() * 24;
auto* vertexBuffer = new GLfloat[vertexBufferSize];
Then, the array is filled like this:
for ... | You write 32 floats per face but you seem to have thought you were only writing 24. You're allocating 24 floats per face and skipping forward 24 floats to get to the next face, but you're actually writing 32 floats per face, because you're writing 8 floats per vertex and 4 vertices per face. So you always end up writin... |
68,177,431 | 68,178,035 | How I solve this segmentation fault while I add one relation on the adjacency list? | This is a part of the header file
using namespace std;
namespace graph {
typedef string Name;
typedef bool Male;
typedef string Relation;
typedef int Age;
struct Node;
struct Vertex;
typedef Node* Grafo;
typedef Vertex* AdjacentList;
const Grafo emptyGraph = NULL;
const Adja... | Without more code, one thing that pops up to me is this:
auxFirst -> next = secondHalfEdgeToAdd;
auxFirst -> rel = rel1;
auxFirst -> vertPtr = first;
auxFirst -> next = emptyAdjacentList;
auxFirst -> next = secondHalfEdgeToAdd; than you have auxFirst -> next = emptyAdjacentList;. You are overwriting auxFIrst->next poi... |
68,177,493 | 68,179,062 | QDialog focusOut event triggered when clicking on dialog's children | I have a QMainWindow that shows a QDialog when pressing a button.
I want the shown dialog to lose opacity when not in focus, e.g when interacting with the main window, and regain full opacity when it gets in focus.
I've subclassed QDialog reimplementing focusInEvent() and focusOutEvent()
void DialogSettings::focusInEve... | I managed to achieve the desired behavior by setting up an eventFilter instead of using focusOutEvent/focusInEvent.
DialogSettings::DialogROI(QWidget *parent) :
QDialog(parent),
ui_(new Ui::DialogSettings)
{
ui_->setupUi(this);
installEventFilter(this);
}
bool DialogSettings::eventFilter(QObject* watched, QEve... |
68,177,670 | 68,178,524 | Lua crashed when metatable __index pointing to a function and returned value is not used | I'm trying to use function as metatable __index to achieve more flexibiilty, but it crashed when the returned value is not assigned to some variable in Lua side.
This is the C++ part, it just creates a table variable whose __index is pointing to a C function, the function just returns a fixed number value:
int meta_ind... | The code below does not compile because expressions like a.foo are not statements in Lua:
a = {}
setmetatable(a, test_meta)
a.foo
The error message is
4: syntax error near <eof>
This string is left on the top of the stack after luaL_loadstring. Hence the error attempt to call a string value when you call lua_call.
Bo... |
68,178,059 | 68,182,763 | Cost of changing a value vs. accessing an array in C | This question was closed for being opinion based, so this is an edit to clarify what I meant by it.
Is there any way to make an educated guess regarding whether changing the value of a double will take more or less time than retrieving a double from an array? I understand that what is faster may be situational, the que... | It's true you can't know without measuring, but you run the risk of either measuring wrong, or not measuring some future computer.
Remember too that you could easily be measuring the wrong thing. Programmer time is usually a lot more expensive than machine time. Guessing — even guessing wrong — could be the best stra... |
68,178,487 | 68,178,563 | Instantiation of declared (but undefined) template ['X' has already been instantiated] | I ran into this issue when trying to postpone the definition of a function template. The solution was straightforward, but I am still curious as to why there was an issue in the first place.
// Declaration
template <class T> int foo ();
void bar () { foo<void> (); } // NOK
// template <class T> void bar () { auto f = ... | Unless you actually instantiate a template it is just a ... template. There is no reason for the compiler to issue an error for this code:
template <class T> int foo ();
template <class T> void bar () { auto f = foo <void> (); }
Only when you try to instantiate bar and call it, the linker will complain about a missin... |
68,178,664 | 68,188,167 | Getting null when converting const char* to NSString Objective-C | I'm trying to convert a const char* that I'm getting from a C++ method that I have, to a NSString in a method in Objective-C. This is the method from c++:
#define EXPORT __attribute__((visibility("default")))
EXPORT
string getAudioWmark(const char* _filename)
{
string filename = string(_filename);
string result... | This should help you out.
const char *cString = filename.UTF8String;
But make sure filename has content otherwise it must result in null
|
68,178,807 | 68,179,599 | How to keep taking values from the user in C but stop when the user does not enter any value and presses enter? | int k;
vector<int>v;
while ((scanf("%d", &k)) != EOF) {
if (v.size() > 20) break;
else {
if (k > 0 && k <= 120) v.push_back(k);
}
}
**The above snippet is taken from codechef blogs **
| <rant>Never tag a question both C and C++ on SO again. It is reserved for questions about interoperations or very specific language-lawyer points, and should not be used for code that could be more or less used on both languages. In that latter case choose one in your first question and if you later need it ask a new q... |
68,178,856 | 68,179,305 | Template specialization for template function members combined with class template | Given the following:
class MyClass
{
public:
template <typename T, typename U = T>
void doSomething(T) {}
private:
double parser;
};
template<>
inline void MyClass::doSomething<bool>(bool) {}
template<>
inline void MyClass::doSomething<int, double>(int) {}
int main(int argc, char* argv[])
{
... | To specialize a function that is a member of a templated class, you need two template<> declarations. Furthermore, you need to specify the typename for MyClass:
template<> template<>
inline void MyClass<some_type>::doSomething<bool>(bool) { ... }
template<> template<>
inline void MyClass<some_type>::doSomething<int, do... |
68,180,044 | 68,180,494 | How to write Google test for ternary variable? | I am checking the some configurations conditions to return the type values. This is the piece of function code.
typdef enum{
type1 = 0,
type2,
type3,
type4,
type5
}
#define config (uint8) ((type1_enble()) ? (type1) :
(((type2_enable())? (type2) :
((type3_enable())? (type3):
(type4_enab... | Each time the config macro is expanded, every branch of that compound expression is injected into the code, which means that there's around 125 different code paths through that function.
So to get full coverage of the function as written, you'd need to go over all permutations of typex_enble() for repeated invocations... |
68,180,061 | 68,189,961 | How do I get Visual Studio Code to include non-standard libraries with angle brackets <>? | I am trying to run a program using the ArduinoJson library with the VSC extension Code Runner but I cannot compile it.
There are no markup errors or warnings in VSC but when I try to run this snippet:
#include "../External_Libraries/ArduinoJson/ArduinoJson.h"
#include <iostream>
int main(){
std::cout << "Done.\n";
... | I found a workaround: Instead of Code Runner I installed the Compile Run extension and configured it to use g++ instead of gcc with the compiler argument "-I C:/.../project/External_Libraries/ArduinoJson/src" -> and this works!
In settings.json:
"c-cpp-compile-run.cpp-compiler": "C:/MinGW/bin/g++.exe",
"c-cpp-compile-r... |
68,180,478 | 68,180,554 | is there any way to get debug info like __FILE__ without using macro function in c/c++? | I'm writing a logger module, so I would like to print the debug infos like __FILE__ and __LINE__ in c/c++. So I used macro function like:
/// here's just an example
/// function str_format() returns a std::string in format like printf() in c
#define info(str, ...) (cout << str_format(str, ##__VA_ARGS__) << __FILE__ << ... | As far as __FILE__ and __LINE__ is concerned, C++20 introduced std::source_location for this. There is no equivalent non-macro based solution in prior C++ standards.
As far as a non-macro logging solution overall, the most common approach involves implementing the logging function as a variadic template with a paramete... |
68,180,594 | 68,265,144 | Integration of Armadillo in x86 C++ Application in Microsoft Visual Studio | since last week I'm working with the "Armadillo" C++-library.
I started with a default 64-bit C++ application in Microsoft Visual Studio. For the installation I followed the steps in the post below:
How can I install Armadillo on Windows?
Following these steps, everything worked fine for me.
But now I have to expand my... | Solved it.
For me it works with replacing the x64-bit "libopenblas.lib" and "libopenblas.dll", which are installed from Armadillo by default, with the x86 "libopenblas.lib" and "libopenblas.dll", which are included in the "OpenBLAS-0.3.15-x86.zip" download file from the OpenBlas release page on GitHub:
https://github.c... |
68,180,738 | 68,180,840 | use += several times, changes are reversed c++ | I have implemented a class vl_vector and a deriv class vl_string, which is pretty similar to STL vector (vl_string is for chars and handles the '\0' char).
I have overloaded the += operator for char, char * and another vl_string.
declarations:
vl_string<StaticCapacity> operator+=(const vl_string<StaticCapacity>&vs);
... | The problem with your functions is that they return a copy of the object, not a reference.
Use
vl_string<StaticCapacity>& operator+=(const vl_string<StaticCapacity>&vs);
vl_string<StaticCapacity>& operator+=(const char *str);
vl_string<StaticCapacity>& operator+=(char c);
// ^^^ Reference return t... |
68,181,218 | 68,181,809 | How can I cleanly mimic C++20 barrier behavior in C++14? | C++20 introduces barriers, where a specified number of threads must arrive at the barrier, by calling arrive_and_wait(). Once all have arrived a completion function is called from one thread to reset the barrier. Then all the threads are released, perhaps to iterate and hit the barrier again.
An example of barrier usag... | The sample code uses only arrive_and_wait and the constructor, plus the completion function.
struct Barrier {
mutable std::mutex m;
std::condition_variable cv;
std::size_t size;
std::ptrdiff_t remaining;
std::ptrdiff_t phase = 0;
std::function<void()> completion;
Barrier( std::size_t s, std::function<void... |
68,182,008 | 68,185,452 | cmake property VS_USER_PROPS silently ignored | I try to add several existing props files (property-files come with gstreamer and I'd like to reuse them for Windows-builds instead of adding all dependencies by hand) to a project generated by cmake for Visual Studio 2019.
I've created one user.props file for this:
videolib.deps.props
<?xml version="1.0" encoding="utf... | Try:
set_property(
TARGET videolib
PROPERTY VS_USER_PROPS "${CMAKE_CURRENT_SOURCE_DIR}/videolib.deps.props"
)
Likely it is just searching in the wrong directory.
|
68,182,425 | 68,182,545 | Using structs inside one another | I am trying to define two structs inside a header file that both of them contain each other as objects. More specifically:
typedef struct Dweller {
int id;
int age;
std::string name, lastname;
Room room;
float foodconsume;
float waterconsume;
};
typedef struct Room {
int id;
int WIDT... | Several things:
As Sam said, get rid of the typedefs.
Change the declaration Room room in Dweller to Room* room and vice versa.
To satisfy the compiler, put two forward declarations up front:
struct Dweller;
struct Room;
|
68,182,486 | 68,183,756 | SQLCHAR (or SQL functions) inconsistent between projects | I am using Visual Studio for a project, and in a specific one I needed to use some sql functions, for some reason it was fine with the type SQLCHAR* and not SQLWCHAR*. I then copied the project over because it has some GUI setup and window handling, but I came across errors only related to this. Basically, each error i... | By @RichardCritten, Go to Project Properties > Configuration Properties > Advanced > Character Set > Not Set
|
68,182,538 | 68,183,028 | Offsetting a texture | I'm making a space invader clone, and while generating the the bullet texture it comes out from the ships upper edge.
Here's snippets of my code:
class Bullet{
public:
sf::Sprite shape;
Bullet(sf::Texture *texture, sf::Vector2f pos){
this->shape.setTexture(*texture);
this->shape.setScale(3,3);
... | Image/texture coordinates are usually (but not always) referencing the top left corner as the origin, and then sized by either a bottom right coordinate, or a height and width from that initial offset.
This line will give you that top left offset:
player.shape.getPosition()
So, you should modify it to do something like... |
68,182,754 | 68,185,508 | After make install via cmake - grpc forlders is empty | I try to installing GRPC from sources.
I have Oracle Linux 7.9, GCC 10.2.1 from devtoolset-10 and cmake version 3.21.0-rc1 built from sources.
The way i used:
git clone --recurse-submodules -b v1.37.0 https://github.com/grpc/grpc
cd grpc
mkdir -p cmake/build
pushd cmake/build
cmake -DgRPC_INSTALL=ON \
-DgRPC_B... | The following worked for me:
$ git clone --recurse-submodules -b v1.37.0 https://github.com/grpc/grpc
$ cmake -G Ninja -S grpc/ -B grpc-build \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX=/usr/local \
-DgRPC_INSTALL=ON \
-DgRPC_BUILD_TESTS=OFF
$ cmake --build grp... |
68,183,436 | 68,432,273 | MacOS 12 beta dyld error: file Array.h, line 54 | I wrote an QT application which works well on macOS Big Sur. Recently I upgrade to MacOS 12 beta 2. The compile process still works. But the application can't start. The backtrace stack shows it crashes at dyld process.
dyld[16971]: Assertion failed: (idx < _usedCount), function operator[], file Array.h, line 54.
* thr... | This has been fixed in MacOS Monterey public beta 3.
|
68,183,503 | 68,183,588 | How to use openGL Widget? | I want to put OpenGL in a TabView Widget.
I dragged the openGLWidget in the tabView UI and ran the code.
It is giving me the following error ->
error image:
On clicking the path, It redirects me to ui_test.h file. -> ui_test.h file image:
I am following this tutorial https://www.youtube.com/watch?v=eztKp_1kVJc and di... | In Qt6 you must use QT += openglwidgets as indicated in the docs.
|
68,184,257 | 68,184,331 | How to assign a value in const unordered_map to another const variable - C++ | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
void fun(const unordered_map<int, vector<int>>& direct_paths) {
const int var = direct_paths[1][0];
cout << var;
}
int main()
{
unordered_map<int, vector<int>> a;
a[1] = vector<int> {1,2,3};
fun(a);
return 0;
}
The above code o... | The operator[] of a std::(unordered_)map is a non-const operator only, as it will modify the map to insert a new element if the requested key is not found. But inside of fun(), direct_paths is (a reference to) a const map object, so operator[] cannot be called on it. That is what the compiler is complaining about, as... |
68,184,556 | 68,184,746 | How can I read multiple wstring lines? | Is it possible to read multiple lines of international characters? I can do this with simple ascii strings:
#include <iostream>
#include <string>
void main ()
{
std::string text{};
//I cannot use std::wcin in that manner
//std::wcout << "Enter any arbitrary text terminated by an asterisk:" << std::endl;
... | Here an example using std::wstring, std::wcin and std::wcout
By the way: you shouldn't mix std::cin, std::cout, std::cerr and std::wcin, std::wcout, std::wcerr. if you choose to use std::wcin, use only std::wcin, std::wcout, std::wcerr
EDIT: if you use std::wcin in std::getline, all arguments must be wide, since the st... |
68,184,805 | 68,184,914 | Define template based on parameter pack values | The methods in this class use an index sequence containing a sequence of indices covering the entire data tuple (an index for each argument passed in the parameter pack). Per other answers I've seen, I'm currently templating my methods as such:
#include <tuple>
#include <memory>
#include <vector>
using std::tuple;
te... | With C++17, you might simply use std::apply:
void clear()
{
std::apply([](auto&... vs){ (vs.clear(), ...); }, data);
}
I was wondering if there's a way that I could define Is at a class-level scope
With extra layer:
template <typename Seq, typename...> class FooImpl;
template <std::size_t... Is, typename... Ts>... |
68,185,603 | 68,186,618 | How IMAGE_DOS_HEADER works | PIMAGE_NT_HEADERS ntheaders = (PIMAGE_NT_HEADERS)(PCHAR(virtualpointer) + PIMAGE_DOS_HEADER(virtualpointer)->e_lfanew);
In the code above, virtualpointer points to a memory location that has a PE file loaded.
Why is virtualpointer in brackets in front of PIMAGE_DOS_HEADER?
How does it handle the pointer, and how is e_... | type(value) is a function-style cast, whereas (type)valu is a C-style cast. But they are both just type-casts nonetheless (for purposes of this code, anyway).
So, in this statement:
PIMAGE_NT_HEADERS ntheaders = (PIMAGE_NT_HEADERS)(PCHAR(virtualpointer) + PIMAGE_DOS_HEADER(virtualpointer)->e_lfanew);
PIMAGE_DOS_HEAD... |
68,185,741 | 68,185,859 | Thread local storage processes | i am looking through the documentation on thread local storage but i believe its poorly written.
https://learn.microsoft.com/en-us/windows/win32/procthread/thread-local-storage
It seems like the way they write documentations is in a sporadic order, they will provide an event that happens, then the next sentence they wi... | The TLS slots - the ones in your diagram - are a fixed-size array of LPVOID-sized variables in the thread's information block. Typically they're used to store pointers. The memory pointed to by a pointer stored here is not local to the thread but allocated normally. However since the thread stores the pointer in a TLS ... |
68,186,420 | 68,186,509 | C++ linked lists using pointers - beginner question | I have been learning C++ for the last couple of months, and after going through an online course I have started doing some challenges with using raw pointers. I have successfully created class that can initiate and iterate through linked list, with lots of struggle I managed to create method that deletes its element(s)... | The main issue is:
p = p->next;
remove->next = p->next;
delete remove;
You try to set remove->next to point to the new next element. But remove is going to be deleted. So the element before remove will still point to something deleted. So, after the delete, you'll have a broken list... |
68,186,806 | 68,189,957 | Why does defining functions in header files create multiple definition errors, but not classes? | This question builds off these two stackoverflow posts:
multiple definition in header file
Multiple definition of namespace function
Here's the question: Why doesn't the multiple definition error appear for classes/structs/enums? Why does it only apply to functions or variables?
I wrote some example code in an effort... | Generally when you compile a definition that is namespace scoped (like functions or global variables), your compiler will emit a global symbol for it. If this appears in multiple translation units, there will be a conflict during link-time since there are multiple definitions (which happen to be equivalent, but the lin... |
68,186,842 | 68,186,974 | C++ primer enums and implicit conversion | Hello I have this from C++ primer 5th edition:
// unscoped enumeration; the underlying type is machine dependent
enum Tokens {INLINE = 128, VIRTUAL = 129};
void newf(unsigned char);
void newf(int);
unsigned char uc = VIRTUAL;
newf(VIRTUAL); // calls newf(int)
newf(uc); // calls newf(unsigned char)
The enum Tokens has ... | From cppreference's description of enums:
Values of unscoped enumeration type are implicitly-convertible to integral types. If the underlying type is not fixed, the value is convertible to the first type from the following list able to hold their entire value range: int, unsigned int, long, unsigned long, long long, o... |
68,187,125 | 68,187,137 | Template class object as an argument in a template class method | I think the best way to explain what i want to accomplish will be through code:
template<typename T>
struct Foo {
static void func(Bar<T> obj);
}; // ^ syntax error: identifier 'Bar'
template<typename T>
struct Bar {
T data;
};
| To resolve this, you just need what's called a "forward declaration":
template<typename T>
struct Bar;
template<typename T>
struct Foo {
static void func(Bar<T> obj); //syntax error no more
};
template<typename T>
struct Bar {
T data;
};
At the point where Bar<T> is referenced first the compiler does not have ... |
68,187,377 | 68,187,414 | What does a read lock do in C++? | When using a shared_mutex, there is exclusive access and shared access. Exclusive access only allows one thread to access the resource while others are blocked until the thread holding the lock releases the lock. A shared access is when multiple threads are allowed to access the resource but under a "read lock". What i... | Your guess is very close to being right but there's a slight subtlety.
The read/write distinction shows intent of the locker, it does not limit what the locker actually does. If a read-locker decides to modify the protected resource, it can, and hilarity will ensue. However, that's no different to a thread modifying th... |
68,187,538 | 68,187,594 | C++ Setter doesn't change the object's variable value | I'm trying to run a code that its's meant to change the value of object variables after it creates the object, and it isn't changing, then the variable is returning values like -815470397 and not changing. And when I use breakpoints it's like it jumps the inside part of the setter.
Pessoa.h
#pragma once
using namespace... | You get these strange values due to the fact that your data members are of built-in type and they remain uninitialized when you use them. They remain uninitialized because your setters aren't setting anything. What they actually do is a comparison (the ==).
Pay attention to the difference in these two:
void Pessoa::Set... |
68,187,671 | 68,187,710 | What's wrong with this code?. I just learned programming a few minutes ago and I'm trying to make this | I just learned programming a few minutes ago and I'm trying to make this
#include <iostream>
int main(){
int n, fibo_n, fibo_n1=1, fibo_n2=0
cout<<"Enter the max term of the Fibonacci Sequence: "
for (int i =1; i<n; i++){
fibo_n=fibo_n1+fibo_n2
fibo_n2=fibo_n1
fibo_n1=fibo_n
... | There are two problems with your code one is you are printing addresses of fib0, fib1 instead of their value and the second is you are using only one format specifier while printing two values.
Here is the modified code.
#include <stdio.h>
void Fibonaci(int N);
void main(){
int N;
long hasil;
printf("Ent... |
68,187,764 | 68,187,982 | Will the pure virtual function be assigned a default function? | When a class is instantiated, a virtual table pointer is created to point to its virtual table. And each virtual function is assigned a function address.
Will the pure virtual function be assigned a default function address?
class base {
public:
virtual void func() = 0;
};
class derived : public base {
public:
v... | Calling a method in a deleted object is undefined behaviour, so in principle anything can happen and it’s your fault, but we can explain why you saw this behaviour.
First when you have a pure virtual function, the compiler could store a null pointer into the vtable, and when you call the function it crashes. Your compi... |
68,188,478 | 68,290,378 | Imgui create pop up box removing the grayed out focus screen | when creating a pop up modal in ImGui, I noticed that there is a grey overlay that appears over the rest of the application (to put the focus on the pop up I think).
However, I am wondering if there is a way for me to remove that gray overlay screen so that I can still interact with the rest of the application even whe... | As per the documentation in imgui.h:659
Popups, Modals :
They block normal mouse hovering detection (and therefore most mouse interactions) behind them.
If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE.
Their visibility state (~bool) is held internally instead of being held by ... |
68,188,842 | 68,188,875 | Why C++ forces initialization of member variables to be in the order of the declaration | I know that in C++ the declaration of members in the class header defines the initialization order. Can you tell me why C++ choose this design? Are there any benefits to force the initialize order instead of following the initializer list?
| Constructors could be overloaded while destructor can't. If data members could be initialized in different order for different constructors, then the destructor can't guarantee to perform destruction on data members in the reverse order of their construction (for objects constructed by different constructors).
|
68,188,857 | 68,188,887 | How can I recreate default arguments in C++ like in Python? | I have this class in Python that I am trying to recreate in C++,
class Node:
def __init__(self, data = None, next = None):
self.data = data
self.next= next
So far I have constructed this in C++,
.h
#include<stdlib.h>
#include <iostream>
class Node {
public:
int value;
Node... | You do it the same way, by providing default arguments:
Node(int val = 0, Node* nxt = nullptr) : value(val), next(nxt) {}
This is both the default constructor, and the one that takes an int and a pointer to Node.
As a sidenote:
You may want to have the following form instead, adds flexibility:
Node(Node* nxt = nullpt... |
68,189,123 | 68,222,906 | Build generated cpp in visual studio | I am using visual studio 2019 for a c++ project. In this project, I generate a cpp file on build (pre-build event) and, if needed, modify the .vcxproj in order to add the file to the project. When the file is already present and thus only overwritten, it works perfectly.
However, if I want to generate the file and add ... | I actually found a solution ! Instead of creating a console project, you need to create a MakeFile project which will call a .bat you make. In this .bat you have to call a .exe which will create the visual studio files (.vcxproj, .sln etc...), generate the cpp files (and do all pre-build events I want, basically) then ... |
68,189,240 | 68,189,672 | D3D9 CubeMap texture | I am making a texture cubemap, and the image is output on all 6 sides. How to print a split image on 6 sides? I want to make it without using shaders and I want to know a site where I can study directX Are there any sites you can recommend?
this is my code.
ㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁㅁ
struct CUBEVERTEX
... | Rendering a cubemap directly as a skybox in Direct3D 9 is not achievable, especially with a "no shaders" requirement. In Direct3D 9, you need to create the resource as a cubemap to use in environment scenarios, and then create SIX individual 2D textures to render it as a skybox--which means having two copies of each cu... |
68,189,421 | 68,189,547 | Communicating C++ header file and source files with Windows Form | I am building a windows form app where I need this youtube header and source file (for context) to communicate with a button in a windows form, I am fairly new to this as I just started this a few weeks ago, I already have this cpp file for my button;
//i made this separate file because the windows form header file is ... | First include the header file properly and you are missing a semicolon:
#include "LinkedList.h"
void MovieRentalSystem::Main::btn_clientAddReg_Click(System::Object^ sender, System::EventArgs^ e) {
//I need to call the linked list into here
// the call is also wrong, you want to create a variable here I guess... |
68,189,634 | 68,190,179 | Unexpected number output | I'm trying to create a program that solves the problem of dining philosophers using posix threads. However, I got stuck at the very beginning, since the output of std :: cout << id + 1 << "PHILOSOPHER: thinking" << std :: endl; ++ i; is incorrect and id takes too large values. Please point out my mistake.
pthread_mutex... | thread function uses an address for argument, which you pass as an address to a local variable of function createThread - number. The life span of argument should be not shorter than thread, so exactly same as the mutex. Using your snippets as base, I created an example which works around the issue:
#include <iostream>... |
68,189,940 | 68,190,130 | how to stop name mangling in Qt class? | ultimately my goal is to write a Qt class(my class inherits from QObject and uses Q_OBJECT macro), then build a dll from it. then in python use ctype to access that dll.
when I write the dll normally, method names get mangled so I can't use them directly. instead I have to use getattr which I don't want to use(because ... | I'm going to hazard a guess this might be failing because of this construct:
extern "C"
{
class I_AM_A_CPLUSPLUS_CONCEPT {};
}
Anyhow, this is solvable, but requires a little rethink. To expose the class to C, you will have to jump through a couple of hoops here.
// the C++
class MyClass : public QObject
{
... |
68,190,683 | 68,190,816 | How to ignore a build directory if Boost is not present | The top directory for my project has a configure.ac file for which I have included the following lines in order to include the Boost Test library:
BOOST_REQUIRE([1.48])
BOOST_TEST
I am using the boost.m4 macro.
The configure.ac file also contains the following code:
AC_OUTPUT([
Makefile
include/Makefile
extra/Makefil... | You can use AM_CONDITIONAL to check the existence of boost library. Then in Makefile.am you can use if endif. Here is an example
In configure.ac, I assume you have done boost check macro and store the result in the variable $enable_boost
AM_CONDITIONAL([BOOST_ENABLED], test "$enable_boost" = yes)
In Makefile.am
if BOO... |
68,190,887 | 68,190,946 | C++ Problem: [Error] statement cannot resolve address of overloaded function x2 | I'm a complete noob here in need of help. I'm hoping you guys, who are more experienced than me, can help me out.
Any input is greatly appreciated.
Here is how the code is supposed to go since it's too long:
#include <iostream>
using namespace std;
class Payslip
{
string name, pay_grade;
... | Are you possibly trying to call a method at the object d? Then you need at least add parentheses. as for each function call:
d.payslipdetails();
|
68,191,620 | 68,191,797 | Warnings (or other means) to identify potential unsigned integer overflows | There are some cases where potential unsigned integer overflows might cause issues. This example illustrates one:
struct Image
{
uint32_t width;
uint32_t height;
uint32_t depth;
};
void* allocateMemory(size_t);
...
allocateMemory(f.width * f.height * f.depth);
The x64 disassembly of GCC, clang and MSVC ... | For MSVC, you can enable warnings such as C26451 while building by enabling "Code Analysis" in the project's (or file's) properties1:
Alternatively, you can run that code analysis on an open/active file at any time using the "Run Code Analysis on File" command from the "Build" menu (or Ctrl+Shift+Alt+f7).
You can ena... |
68,191,652 | 68,191,894 | How to use HAVE_BOOST in ax_boost_base | The ax_boost_base page indicates that it sets HAVE_BOOST. So I tried it in my configure.ac file:
AX_BOOST_BASE([1.48],, [AC_MSG_ERROR([libfoo needs Boost, but it was not found in your system])])
AC_MSG_NOTICE(["HAVE_BOOST value"])
AC_MSG_NOTICE([$HAVE_BOOST])
When I run configure, HAVE_BOOST does not seem to have any ... | You missed to set the result back to some variable. You can try this
AX_BOOST_BASE([1.48],
[have_boost=yes],
[AC_MSG_ERROR([libfoo needs Boost, but it was not found in your system])]
)
AC_MSG_NOTICE(["have_boost value"])
AC_MSG_NOTICE([$have_boost])
The HAVE_BOOST is set in the m4 macro ax_boost_base uses AC_DEFINE th... |
68,192,903 | 68,205,547 | How do I add a library from another branch in VS | My task is to make myself familiar with a given code which also includes a dll and a lib file. I tried the advice given in this post : How to add additional libraries to Visual Studio project? but apparently the lib file I included cannot be opened. I tried to include it at the linker, as suggested in the other post an... | For more details about how to link the .lib, I suggest you could follow the following steps:
1,Add the path to the header file to the Additional Include Directories(property - >c/c++ -> General -> Additional Include Directories)
2,Add the path to the .lib file to the Additional Library Directories (property -> linker -... |
68,192,950 | 68,193,722 | Modify INCS in makefile depending on target? | I have a makefile where I want to make a new target. Now basically the version of a third party library being used for the new target would be an upgraded one. We want to create a new target for the application which specifically uses the upgraded version. So as of now there are many different application complied into... | Sure. You can use target-specific variable assignments, which will be set for the target and propagate down to all dependencies. Consider the following Makefile:
DEP_PATH := dep
INCS += \
-I$(DEP_PATH)/Util/include
all: INCS += -I$(DEP_PATH)/3rdPartyLib-1.0/include
all: Application1$(EXEEXT)
app2: INCS += -I... |
68,194,091 | 68,194,384 | Automatically downcast a shared_ptr in parent class to child class type | I have a virtual parent class for collecting reports with its associated report struct. The reports should be rendered as a JSON string in the end, so I'm using https://github.com/nlohmann/json to help me with that.
I create different different child classes to generate such reports of the respective child report struc... | Also an idea could be to make the parent class a templated class, which uses the child report type as template parameter:
#include <iostream>
#include <vector>
#include <memory>
struct Report {
// make abstract
virtual ~Report() {}
std::string type = "main_report";
int foo = 0;
};
struct ChildAReport : public... |
68,194,513 | 68,194,556 | How to achieve a c++ macros like this | #define idebug(...) \
\#ifdef _DEBUG\
printf(__VA_ARGS__);\
\#endif\
#endif
It is difficult to describe the intention,
which generally means that i predefine a macros idebug which to save some code.
If _ DEBUG flag is predefined, then print the output.
Or pretend nothing happened.
if we achieve it using a func... | Do it the other way:
#ifdef _DEBUG
# define idebug(...) printf(__VA_ARGS__)
#else
# define idebug(...) ((void)0)
#endif
|
68,195,103 | 68,198,257 | Storing a class that uses the PIMPL idiom in a std::vector | I am writing an application that needs to store objects of a class that uses the PIMPL idiom in a std::vector. Because the class uses std::unique_ptr to store a pointer to it's implementation and std::unique_ptr is not copyable, the class itself is not copyable. std::vector should still work in this case because the cl... | Add Test(Test&&) noexcept; and Test& operator=(Test&&) noexcept; then =default them in your cpp file.
You should probably make Test(const int value) explicit while you are at it.
In modern gcc/clang at least, you can =default the move ctor in the header. You cannot do this to operator= because it can delete the left h... |
68,195,225 | 68,195,432 | Compilers disagree on accepting this view::keys code | Out of 3 compilers only gcc accepts this code. I guess clang problem is that it uses antique libstdc++, but MSVC and GCC should support ranges code.
What is the standard mandated behavior?
#include<array>
#include<algorithm>
#include<iostream>
#include<map>
#include<set>
#include<ranges>
constexpr std::array<std::pair... | This needs P2017R1 (conditionally borrowed ranges) to work; without that, arr | std::views::keys is not a borrowed_range, and so ranges::find returns dangling.
Presumably the MSVC version on godbolt doesn't have that paper implemented.
|
68,195,546 | 68,195,937 | wxGauge was nullptr out of constructor | first of all sorry for my english, its not my first language
i'm beginner on wxWidgets for c++ and i started to developer a simple application with a progress bar and some background process
unfortunately when i call wx_MyGauge->SetValue(20), a exception "wx_MyGauge was nullptr" occurs
this only occurs outside the co... | You call the method Connect of the pnl and don't pass which event handler Importar is. Thus, the method Connect joins the mouse event to pnl instead of testGuage
btn->Connect(wxEVT_LEFT_UP, wxMouseEventHandler(testGauge::Importar));
Must be
btn->Connect(wxEVT_LEFT_UP, wxMouseEventHandler(testGauge::Importar), nullptr,... |
68,195,871 | 68,206,984 | Misunderstanding about non-deducible function template arguments | From C++ Templates - The Complete Guide 2nd edition:
Moreover, such parameters can't usefully be placed after a template parameter pack or appear in a partial specialization, because there would be no way to explicitly specify or deduce them.
template<typename ...Ts, int N>
void f(double (&)[N+1], Ts ... ps); // usele... |
I.e. in the example above N is the parameter that cannot be deduced because N+1 is "too complicated to be deduced".
Formally, this is [temp.deduct.type]/5.3
The non-deduced contexts are:
[...]
/5.3 A non-type template argument or an array bound in which a subexpression references a template parameter.
As is alrea... |
68,195,912 | 68,205,378 | boost::mp11::mp_list can't define proper transition table for FSM based on boost::msm, what is missing? | Does boost::mp11::mp_list can be used instead of boost::mpl::vector as transition-list in state-machines constructed with boost::msm?
I just tried it (link) and it seems that:
it compiles
but it does not work - transitions tables are missing
and produces 1/3 code comparing to boost::mpl::vector.
I also tried boost::f... | It seems that the only way to use boost::mp11::mp_list as a list of transition rows in boost::msm is to use typedef (using) - inheritance does not work; required changes are as follows:
// Transition table for player
using transition_table = boost::mp11::mp_list<
_row < Empty , play , Playin... |
68,195,951 | 68,196,419 | Storing two integer values in 32 bits while avoiding UB with negative numbers | I have two int16_t integers that I want to store in one one 32-bit int.
I can use the lower and upper bits to do this as answered in this question.
The top answers demonstrates this
int int1 = 345;
int int2 = 2342;
take2Integers( int1 | (int2 << 16) );
But my value could also be negative, so will << 16 cause und... | Here’s the solution with a single std::memcpy from the comments:
std::int32_t pack(std::int16_t l, std::int16_t h) {
std::int16_t arr[2] = {l, h};
std::int32_t result;
std::memcpy(&result, arr, sizeof result);
return result;
}
Any compiler worth its salt won’t emit code for the temporary array. Case in... |
68,196,051 | 68,196,088 | ARDUINO: ISO C++ forbids comparison between pointer and integer [-fpermissive] | i get this error when I run this code . The code is supposed to run a servo motor when i press a button.It uses serial data from an hc05 module to run the servo motor .I don't know c++ so I can't add anything else.The problem is in the t variable in the serial.Read() funciton i think.Thank you for your help
#include <S... | The condition t=="O" is wrong. Double quotations "" is used for representing (c-style) strings, which are sequences of characters terminated by a null-character. It is an array and it can be converted to a pointer to the first element.
You should use single quotations '' to represent a character constant like t=='O'.
|
68,196,356 | 68,198,203 | Provide a pointer to member function to be invoked by the target class without functional | I'm reading a lot of questions (and answers) about function pointers, functors and callbacks but I still have a confusion about which is the right tool for me.
Some of them cannot apply to my scenario because it seems my compiler avr-gcc v5.4.0 does not have C++ standard library (i.e. std::function is not available).
T... | Making a member function virtual is a relatively low-overhead way to have a single pointer (to an object) refer to both the object's data and the correct member function.
class InputsBase
{
// All classes that implement myRaw() should inherit from this class
public:
virtual uint8_t myRaw() = 0;
};
class Inputs... |
68,196,640 | 68,199,571 | Stop exceptions from bring up implementation in visual studio 2019 | When debugging my program sometimes it will break with an exception and bring up the c++ implementation which makes it difficult to figure out where the bug is occurring. Currently I have to manually go through step by step to figure out which exact line is causing the program to break, which can be tedious or impossib... | Just My Code is for this, and enabled by default for most languages.
To enable Just My Code in Visual Studio follow these steps :
under Tools > Options (or Debug > Options) > Debugging > General
select Enable Just My Code.
|
68,196,695 | 68,197,718 | Throwing destructor causes memory leak | This code
#include <iostream>
#include <memory>
template <typename T>
class ScopeGuard final {
public:
explicit ScopeGuard(T callback) : callback_(std::move(callback)) {}
ScopeGuard(const ScopeGuard&) = delete;
ScopeGuard(ScopeGuard&&) = delete;
ScopeGuard& operator=(const ScopeGuard&) = delete;
ScopeGuar... | Seems like a bug, already reported and fixed for gcc: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66139
I suppose, std::shared_ptr<> is partially created during exception throw
As a workaround, you could prevent copy elision:
Res LeakImpl() {
ScopeGuard on_exit{[] { throw std::runtime_error("error"); }};
Res res{s... |
68,196,984 | 68,197,176 | Why std::string.size() behaves abnormally in my code? | Here in this code, when I'm entering inputs one by one, I'm getting correct output as expected(correct size of string using std::string.size()), But when I'm entering three or four inputs together(or entering input in bulk) the output (size of string) gets incremented by 2.
Ps: Look once at attached output snippets.
#i... | std::cin.ignore(); ignores characters to the EOF. When you enter one line, EOF is met. When you enter several lines, EOF is not met, but \n is met. Thus the next getline after the input 5 returns the empty string, the length is 0.
When consuming whitespace-delimited input (e.g. int n; std::cin >> n;) any whitespace th... |
68,197,009 | 68,197,119 | C++ static members initialized with lambda | Following is legal:
class FooAccesor {
static std::function<void(Foo& foo)> getFooMethod() {
return []() { foo.method(); };
}
}
while
class FooAccesor {
static const std::function<void(Foo& foo)> fooMethod = []() { foo.method(); };
}
is not. (Tried to fix with constexpr to no avail.) My MSVC compiler explai... | You are allowed to declare the member as inline (since C++17). And you have to fix several typos in your example (missing ; and not passing a Foo to the lambda):
#include <functional>
struct Foo { void method(){}};
class FooAccesor {
inline static std::function<void(Foo& foo)> fooMethod = [](Foo& foo) { foo.method(... |
68,197,117 | 68,198,450 | How can I load the file.lua library globally by C++ without having to import it with : loadfile("file.lua")()? | I have a library called " json.lua " found on this github : github json.lua
I'm importing this library through the main.lua file like this:
local json = loadfile("json.lua")() -- json = library loaded
print("json decoded : "..json.decode("13E+2")) -- will print : json decoded = 1300.0
but I want to use the " json " v... | Run this in C++ before loading your scripts:
luaL_dostring(L,"json = dofile('json.lua')");
|
68,197,694 | 68,197,884 | Can't inherit two classes that inherit one interface | I have 2 interfaces: Socket and ListeningSocket, and 2 classes: BerkeleySocket and BerkeleyListeningSocket that implement those interfaces.
There will be more socket types, now it's just an example.
The problem is BerkeleyListeningSocket inherits both of BerkeleySocket and ListeingSocket. It inherits BerkeleySocket to ... | This is a case where you need virtual inheritance because with your code, BerkeleyListeningSocket inherits twice from Socket (once from BerkeleySocket and once from ListeningSocket). In order to tell the compiler to "merge both Socket in one", you need to change your class definitions:
class ListeningSocket : public v... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.