378 questions from the last 30 days
51
votes
2
answers
3k
views
Why is 0.0 printed as 0.00001 when rounding upward?
If in a C++ program, I activate upward rounding mode for floating-point numbers and print some double-precision value already rounded to an integer, e.g.:
#include <cfenv>
#include <iostream&...
14
votes
1
answer
861
views
What is correct mental model for [[no_unique_address]] in C++?
I recently found out about [[no_unique_address]] attribute in C++. According to cppreference.com:
Applies to the name being declared in the declaration of a non-static data member that is not a bit-...
10
votes
1
answer
813
views
Can formal parameters inside the function not be dropped even if the function returns until the caller statement ends?
I have tried some compilers and some C++ standard versions. This code may have a deadlock (the comments point out that this is UB) and can be reproduced at least under gcc8 and C++11. I use "...
6
votes
3
answers
247
views
How to create a unique_ptr while guarding against implicit conversion in ctor?
Here's an example:
class Example {
public:
Example(int m, int n, double pad) {}
Example(double size, double pad) {}
};
int main() {
Example example { 1.0, 1.0 };
auto ptr = std::...
11
votes
1
answer
759
views
Is CPP TrivialCopyable class effectively a C struct?
During coding of std::atomic, CAS, etc, I always struggle to memorize the definition of CPP class being "TriviallyCopyable".
Now I am gradually switching to C world, I accidentally found ...
13
votes
1
answer
478
views
Uniqueness of multiple unnamed namespaces within translation unit
I have recently come across this answer about forward declaration of the class in the unnamed namespace, and I was surprised that it indeed compiles and seems to work with Clang. I thought that every ...
5
votes
2
answers
159
views
What is the rationale behind container types in std defining their own swap function even if their move-semantics have been correctly implemented?
Below is the most common implementation of std::swap:
template<typename T>
void std::swap(T& a, T& b) {
auto tmp = std::move(a);
a = std::move(b);
b = std::move(...
6
votes
4
answers
528
views
how to avoid buffered printf() blocking
Is there some way to know ahead of time when buffered printf() will block, giving an opportunity to avoid the call and either delay or discard output? For example a low level method of knowing when ...
4
votes
4
answers
198
views
Why do I need an Enable type parameter when using std::enable_if
According to the examples in std::enable_if documentation, this compiles:
template <typename T, typename Enable = void>
struct transform {
T operator()(nlohmann::json &data);
};
...
5
votes
3
answers
172
views
Count how many adjacent elements satisfy a predicate
Given a std::vector named v and a predicate p that takes two elements and returns a bool, what is the idiomatic way to count how many adjacent elements in v satisfy p?
The obvious way is to use a loop:...
1
vote
5
answers
213
views
Check for free function existence in compile time
I am writing a function wrapper for our internal API that recently changed and I would like my function to support both versions, depending on which header was included, i.e. which function version is ...
6
votes
2
answers
157
views
Three-way comparison operator defaulted out of class is not a friend [duplicate]
I have a project targeting C++17, which defines some structs without comparison operators (because they are not required and noone could be bothered to define them). I am then unit testing that code ...
15
votes
1
answer
305
views
Why does the parameter pack not work as expected in concepts?
template<typename T, typename... Args>
inline constexpr auto c = sizeof(T) + sizeof...(Args) > 1;
template<typename... Args>
requires c<Args...> // ok
void f1() {
}
template<...
6
votes
1
answer
108
views
Deleting a file scope function in a header file
I am writing a header file, in which there is a void Foo() function in file scope, and I want it to be deleted. Should it be inline?
void Foo() = delete;
or
inline void Foo() = delete;
2
votes
1
answer
210
views
Can I always reduce a struct with a single member in C++ to just its member? [closed]
I ended up writing this code today:
struct node{
vector<node*> children;
};
...and it just felt wrong.
Like, if I wrote struct N{int n;};
I could just simply use the int directly and not ...
5
votes
1
answer
207
views
Constructor is ambiguous however there is only one candidate
In the following code there are two constructors - direct constructor from int v and deleted const int& constructor:
struct X
{
X(int v);
X(const int&)=delete;
};
X foo()
{
return ...
4
votes
2
answers
196
views
A tuple-like container that only allows unique and non-convertible types
I needed a type that could generalize several types that cannot be converted to each other. For example: There are 2 types A and B. A is not convertible to B, B is not convertible to A. That is, these ...
3
votes
3
answers
194
views
Receiving a lambda through auto&&
If I assign a lambda in C++ with this:
auto&& mylambda = [&](int someparam)
{
some_function();
return 42;
};
Is this wrong? I know that this triggers auto type deduction, but is ...
6
votes
3
answers
145
views
Is there a way to rank user-defined conversions between class templates mirror the ranking of conversions of their template arguments?
Consider the following code (live example):
#include <memory>
struct Base {};
struct Middle : public Base {};
struct Derived : public Middle {};
void foo(Base*);
void foo(Middle*);
void ...
1
vote
4
answers
172
views
A generic wrapper for C++ vector of structs operations: removal, find_if, etc
I'm using C++ 14. I find C++'s vector operations erase and remove verbose and confusing and want to write a simple generic wrapper to remove an element from a vector of structs if that element's value ...
3
votes
3
answers
132
views
C++ class template with conditional data members
Consider the following C++ code.
#include <iostream>
#include <set>
#include <string>
enum class Field { kX, kY };
std::string ToString(const Field f) {
switch (f) {
case Field:...
6
votes
1
answer
207
views
std::variant in constexpr context
Following code fails to be compiled with some compilers (including VS v19.20)
#include <variant>
struct A {
int a;
bool b;
using T1 = int A::*;
using T2 = bool A::*;
...
4
votes
1
answer
258
views
Pros and cons of make_unique vs direct constructor call in C++17 [closed]
The function std::make_shared<T>() is most often preferred to std::shared_ptr<T> {new T}, because it will only make one allocation, as opposed to two allocations in the second example. ...
1
vote
4
answers
152
views
Why is the base class _vptr incorrect when it is passed as lpvoid to be derefenced later?
My app crashes when I try to pass the base class as lpvoid then typecasting back to the base class, but works fine if I use a different method by passing the pointer to the base class as a function ...
5
votes
1
answer
178
views
Ensure a value is in a specific register both in GCC and MSVC on windows x64
The goal is to guarantee that r10 and r11 are set to certain values before a call to an assembly function:
template<typename Args...>
int wrapper(int val1, int val2, Args... args) {
// somehow ...
0
votes
3
answers
222
views
Array of pointers to char looks weird in memory [closed]
I have an array of char pointers (C-style string). As far as I know C-style string containing N characters occupy N + 1 bytes in memory since it also has a null character '\0' at the end terminating ...
5
votes
2
answers
134
views
Is this assignment to brace-enclosed string constant really illegal in C++?
I am porting a large codebase from Linux/g++ to MacOS/Clang. I hit this compiler error in multiple places in Clang (where g++ builds successfully and does the right thing at run time):
error: ...
2
votes
2
answers
165
views
Is it safe to .pop_back() from an std::vector in order to avoid pointers/memory shifting?
I have this class:
class Socket
{
[...]
pollfd* fdPtr;
};
And I have a Manager class that creates the actual pollfd objects and adds them to a std::vector named pollFdsVec, to then poll on ...
0
votes
4
answers
239
views
Is it possible to extend a member function?
I am relatively new to C++ and would like to know if it is possible to do the following and if so, is there a better way to achieve the same or similar result more efficiently?
Declare a struct/class
...
-1
votes
2
answers
324
views
standards compliant way to write array bound checks in C or C++ that can't be optimized away? [closed]
is there a standards compliant way that can't be optimized away of writing a bounds check in C or C++? since the compiler can assume that the UB behaviour never happens, this means it can just throw ...
2
votes
2
answers
114
views
Why can I not efficiently move the strings when using std::istream_iterator<std::string>?
#include <fstream>
#include <string>
#include <vector>
int main() {
auto fin = std::ifstream("tmp.txt");
auto pos = std::istream_iterator<std::string>(fin);...
5
votes
1
answer
134
views
std::ostringstream 2GB cap on Windows?
I paste below a minimal example that writes to an std::string and also to an std::ostringstream object, 0.5GB at a time, then queries and prints their sizes at each step.
When executing on Windows (64-...
6
votes
1
answer
207
views
Why is `else` omitted after `return` in some libstdc++ `std::expected` methods, but not in others?
I'm reading libstdc++ implementation of std::expected from master branch. In the expected header, on line 864, there's this code:
template<typename _Gr = _Er>
constexpr _Er
error_or(_Gr&&...
3
votes
1
answer
185
views
Why inline functions when forward declarations exist?
I am reading learncpp's article on Inline functions, and it says that the modern goal of using inline functions is to avoid ODR errors.
That makes sense, it allows for a function to be defined in ...
2
votes
2
answers
159
views
Is there a possibility to use std::vector<T> as parameter in this case
Consider the following:
struct A
{
std::string name;
// other members
};
struct B
{
std::string name;
// different members
};
class Table
{
private:
std::vector<A> vec1;
...
5
votes
1
answer
193
views
How can I invert the boolean return value of a function passed to std::bind?
Let's say I have the following code:
bool IsTheMagicNumber(int number, int magic_number)
{
return number == magic_number;
}
using NumberValidator = std::function<bool(int)>;
NumberValidator ...
4
votes
1
answer
139
views
Why does this va_start crash?
Why do two pointers pointing to the same memory have different effects in va_start, one is okay but the other crashes?
The testing environment is Visual Studio 2019.
#include <Windows.h>
#...
2
votes
1
answer
179
views
std::unique() algorithm returns clearly non-unique results [duplicate]
I have been experimenting with C++'s std::unique() algorithm, but the results it returns really confuse me.
I have done a simple function to test it, like so:
#include <algorithm>
#include <...
-3
votes
1
answer
216
views
Why can't the compiler deduce the element type of `std::vector`?
I want to use auto more in my code and came up with the following example:
#include <vector>
int main() {
auto v{std::vector{}};
for (auto i{0}; i < 10; i++) {
v.push_back(i)...
3
votes
2
answers
206
views
retrieving a runtime array from a pointer to its storage?
When an array of objects of type T (without constraints on T) has been created (implicitly or explicitly) inside a storage, whose memory location is given, for instance, by a void *, unsigned char * ...
2
votes
3
answers
205
views
C++: How to iterate over tuple in compile-time?
How to iterate over tuple in compile-time?
problem code:
#include <array>
#include <cstddef>
#include <tuple>
namespace {
class Solution {
public:
template <size_t ...
2
votes
3
answers
159
views
Apply a templated lambda to each type in a std::tuple (C++20)
I've run into an interesting C++20 problem where I want to apply the same templated function to each type listed in a std::tuple. Here's some pseudocode to illustrate the idea:
template <typename T&...
0
votes
3
answers
186
views
Confusion about invalidated iterators
If vectors are stored contiguously, as long as they are not made smaller or reallocated, any iterator pointing to an element within it should be valid. The following code would be defined:
#include &...
2
votes
2
answers
112
views
How to use a function template as a template parameter of another template?
I have some function templates with same signature, and I'm trying to create a proxy function to call them with different types.
How to pass the function name to the proxy function correctly?
https://...
1
vote
1
answer
116
views
How does typecasting between different sized integers work in C++?
Imagine: int full = static_cast<int>(uint8_t_var);
Does anything actually happen under the hood here? If you're on a machine with 64 bit registers, I assume that the higher bits of uint8_t_var ...
4
votes
1
answer
106
views
Can the name of a template parameter shadow the name of a member of that class?
Example
Consider this example (https://godbolt.org/z/hrE3YEzPd):
#include <cstdint>
class Foo {
template <typename Write>
void WriteNestedMessage(uint32_t field_number, Write ...
3
votes
2
answers
138
views
How to reduce verbosity when splitting `std::string_view` by `std::views::split`?
Consider the following snippet:
// included, for exposition only
SomeData buzz(std::string_view);
constexpr auto foo(std::string_view v) {
using namespace std::string_view_literals;
return v ...
1
vote
2
answers
98
views
Forward string literal to consteval function
My api would require calling runtime(constFoo(str)) to get the final result, I wanted to shorten this because the real function names are kind of verbose. To do this I need to somehow wrap the ...
5
votes
1
answer
215
views
How to use C++ coroutine with Qt?
I am trying to use coroutines with Qt.
Here's minimal(I guess) example to reproduce my problem
Basically, bellow code is adopted from the example of cppreference here:
https://en.cppreference.com/w/...
2
votes
2
answers
162
views
Are unsynchronized writes to global variables UB if code does not read from them? [duplicate]
For the purpose of debugging, our project is sometimes using global volatile variables:
volatile struct {
uintptr_t last_read = 0;
uintptr_t last_write = 0;
size_t reads = 0;
size_t ...