8,953 questions
4
votes
0
answers
168
views
Is it impossible that the acquire load returns `1` when the loops in other threads exit?
Consider this example:
#include <atomic>
#include <cassert>
#include <thread>
int main() {
std::atomic<int> strong = {3};
std::atomic<int> weak = {1};
auto t1 ...
0
votes
0
answers
82
views
Modifying object representation in presence of padding bits
This question is a follow-up of std::bit_cast padding and undefined behavior. This "revival" is motivated by my answer to Accessing object storage where I proposed a function to modify a ...
2
votes
0
answers
122
views
Is it possible that the assertion can fail with memory_order::relaxed to transfer pointers?
Consider this example:
#include <iostream>
#include <atomic>
#include <thread>
#include <cassert>
int main(){
std::atomic<int> val = 1;
std::atomic<std::atomic&...
2
votes
1
answer
91
views
Is it undefined behaviour to free a `static restrict` array function parameter?
I'm asking this question from the perspective of a compiler developer – I want to know whether a particular potential optimisation is valid (because all programs that the optimisation would break have ...
2
votes
1
answer
113
views
Accessing Union Members with Different Qualifiers in C
In the C standard (at least, I'm looking at draft C23 WG14/N3088), section 6.7.3 Type Qualifiers states:
7 If an attempt is made to modify an object defined with a const-qualified type through the ...
1
vote
1
answer
288
views
Accessing object storage
Consider the code below assuming 4 is a correct index of p->c.
Are buf and *p objects alive at the same time?
struct S { int x; char c; };
alignas(S) unsigned char buf[sizeof(S)];
S* p ...
18
votes
1
answer
2k
views
Whose responsibility is it to destroy a C++20 coroutine that throws from its initial suspend?
I am trying to track if a C++20 coroutine has ever suspended, so that unhandled_exception knows whether it can simply re-throw; the exception back to the caller of the initial coroutine function, or ...
4
votes
2
answers
266
views
Using std::launder with reinterpret_cast?
I am probably familiar with strict aliasing rule and implicit lifetime creation in a certain degree, but I still do not understand well enough how do these terms relate to std::launder.
The following ...
5
votes
1
answer
206
views
Calling static function from inline function in C
In C, if I call a static function from an inline function, I typically get a compiler warning like
warning: static function <name> is used in an inline function with external linkage [-Wstatic-...
2
votes
3
answers
197
views
What are examples of non-finite float values other than infinity and NaN?
C23 §5.2.5.3.3 [Characteristics of floating types <float.h>] paragraph 8 says:
Floating types shall be able to represent signed zeros or an unsigned zero and all normalized floating-point ...
4
votes
1
answer
125
views
Can an exported function template invoke a module-local function using ADL?
Let's say that we have a simple main.cpp file which contains only a single call of a function bar which is defined in the module a:
import a;
int main() {
bar(1);
}
Then let's take a look at the ...
2
votes
1
answer
126
views
Is it legal to declare a function template of type which has C language linkage?
Function templates are not allowed to have C language linkage:
extern "C" {
template<typename T> // error: template with C linkage
void bad_f() {}
}
This is reasonable, as ...
3
votes
1
answer
150
views
Declaring aliases for anonymous classes
This is an attempt to make an alias to an anonymous class:
struct {
int i = 0;
} a;
// error C7626 in MSVC
using A = decltype(a);
This produces an error in Visual Studio:
error C7626: unnamed ...
5
votes
1
answer
148
views
What's the difference between `extern "C" /*...*/` and `extern "C" { /*...*/ }`
Both GCC and Clang reject
extern "C" static void foo() {}
but accept
extern "C" {
static void foo() {}
}
Aren't these supposed to be equivalent?
2
votes
1
answer
148
views
Can conforming implementations remove or reorder functions that don't have C++ defined observable behaviors?
intro.abstract p8 says:
The following specify the observable behavior of the program:
Accesses through volatile glvalues are evaluated strictly according to the rules of the abstract machine.
Data is ...
8
votes
1
answer
827
views
When is reinterpret_cast UB?
Does the code below contain undefined behavior (UB)?
struct A
{
int x;
char y;
};
int main()
{
std::vector<uint8_t> v(sizeof(A), 0);
A* p = reinterpret_cast<A*>(v.data());...
10
votes
1
answer
510
views
Is this a well-defined way to access bitfield bits by index in C11
The order of bits in C11 bitfields is implementation-defined, and so is any padding in between them. This makes it difficult to access the bitfields by index at runtime, even though most ...
-2
votes
2
answers
249
views
Where in their documents do implementations state they won't reorder black-box functions?
Consider this example:
extern void black_box_foo();
extern void black_box_bar();
int main(){
black_box_foo(); // #1
black_box_bar(); // #2
}
#1 and #2 are functions whose definitions are ...
4
votes
1
answer
208
views
std::format formatter for volatile
This simple code:
#include <print>
int main()
{
volatile int i = 5;
std::println("{}", i);
}
Doesn't compile with any major implementation of the std library. Any particular ...
10
votes
3
answers
1k
views
Is creating an object not the same thing as starting its lifetime?
I've always assumed that "creating an object" is the same thing as "starting its lifetime" (and not the same thing as allocating storage for it).
But I've recently been told that &...
0
votes
1
answer
128
views
Is it well-formed to track POD class layouts at compile time?
I'm trying to generate compile-time info about my POD types. Getting the offset of each member has been challenging due to limitations like no pointer conversions in constexpr, but I think I've found ...
3
votes
1
answer
151
views
Do methods on the ECMAScript Atomics object enforce that all prior shared memory operations are completed first?
The ECMAScript Language Specification states:
Atomics are carved in stone: Program transformations must not cause any Shared Data Block events whose [[Order]] is seq-cst to be removed from the is-...
1
vote
2
answers
204
views
Does this execution violate the observable behavior if ignoring the OOTA?
Consider this example:
#include <iostream>
#include <thread>
#include <atomic>
int main(){
std::atomic<int> val = 0;
std::atomic<bool> flag = false;
auto t1 = std::...
16
votes
3
answers
912
views
Necessity of `typename` for naming of local nested classes in function templates
I have a function template f, defining in its body a local class A with another nested class B. Both classes are not templates. Must I name the inner class as typename A::B or shorter variant A::B is ...
-2
votes
2
answers
193
views
Does calling IO functions constitute an observable behavior?
[intro.abstract] p8 says:
The following specify the observable behavior of the program:
Accesses through volatile glvalues are evaluated strictly according to the rules of the abstract machine.
Data ...
0
votes
1
answer
331
views
Can external IO operations be considered as if seq_cst operations in the reasoning of multithreaded programs?
Consider this example:
// thread A:
start_transaction();
update_mysql();
commit_transaction(); // remove "key" from mysql tables
remove_redis_cache("key");
// thread B:
std::...
2
votes
0
answers
170
views
Accessing objects of implicit lifetime type in the storage provided by std::allocator, before any explicit construction
This question rises for a discussion of the answer to another question about allocation in constexpr context.
cppreference states that std::allocator<T>::allocate(std::size_t n) allocates an ...
10
votes
1
answer
300
views
How can you prevent a destructor call from being reordered above an atomic write by the compiler?
Here is a possibly incorrect program for communicating between a function and a signal handler that might interrupt it. Assume that HandleSignal has been arranged to run as a signal handler. The ...
Advice
2
votes
4
replies
249
views
Can function-local class be defined in the global scope?
Any C++ class can be first forward declared, and defined only later in the program. Are function-local classes an exception from this rule?
Please consider a simplified program:
auto f() {
struct ...
14
votes
1
answer
898
views
Are out-of-bounds usize slice indexes guaranteed to panic?
Rust programs typically panic when you index into a slice with an out-of-bounds usize index.
Is that panic actually guaranteed to happen? Can I rely on the panic when reasoning about the soundness of (...
16
votes
2
answers
716
views
Parsing of small floats with std::istream
I have a program that reads the coordinates of some points from a text file using std::istringstream, and then it verifies the correctness of parsing by calling stream's operator bool().
In general it ...
14
votes
1
answer
373
views
Are pointers to pure virtual member functions of local classes allowed?
Consider the following snippet:
int main() {
struct Local {
virtual void foo() = 0;
};
void (Local::* ptr)() = &Local::foo;
}
When compiling with C++20, GCC 13.3.0 and Clang 18.1.3 ...
-1
votes
0
answers
223
views
+50
Do the RMW operations on `cnt` still not avoid an inconsistent status for this multiple-producer single-consumer implementation?
Looking at this implementation of multiple-producer single-consumer, which was the implementation in Rust's standard library; however, its memory order model is derived from C++. So, it should be ...
5
votes
1
answer
237
views
Is it legal to cast a repr(C) struct pointer to pointer to its first field?
In C, this is legal as far as I know (In C, does a pointer to a structure always point to its first member?).
#include <stdio.h>
typedef struct {
char *name;
int age;
} A;
typedef ...
2
votes
1
answer
243
views
May uninitialized structure padding bytes lead to undefined behavior?
Consider the following structure:
struct foo
{
uint32_t a;
uint16_t b;
};
Assume that this structure has 2 padding bytes at the end (a likely case) and suppose that an instance is set up like ...
0
votes
1
answer
164
views
Does an implementation that reorders evaluation in a single thread violate [intro.execution] p8?
[intro.execution] p8 says:
Given any two evaluations A and B, if A is sequenced before B (or, equivalently, B is sequenced after A), then the execution of A shall precede the execution of B.
...
2
votes
2
answers
194
views
How to return a list of selected elements of some underlying container in a typesafe manner?
Im wondering if there is a better, more typesafe, way to return "a selection" than I do at the moment.
If we only ever have one selected element at a time, we can just return a reference, ...
0
votes
2
answers
159
views
Does this approach to examine object representation reuse storage?
In order to examine object representation, the C++ standard provides https://timsong-cpp.github.io/cppwp/n4861/basic.lval#11:
If a program attempts to access ([defns.access]) the stored value of an ...
3
votes
1
answer
225
views
How to correctly start a byte array's lifetime at a memory address returned by mmap?
I'm working on legacy code that uses mmap to load data from a file:
int fd;
std::size_t fs;
fd = open(filename, O_RDONLY); // error management omitted for the example
fs = get_size_from_fd(fd); // ...
0
votes
1
answer
178
views
Is this a conforming observable behavior in the abstract machine's sense, where the load reads a value that is not currently produced
Consider this example:
#include <atomic>
#include <iostream>
#include <chrono>
#include <thread>
#include <cassert>
int main(){
std::atomic<int> val = {0};
...
21
votes
1
answer
655
views
Default equality operator for an empty union
C++ allows us to make union class type without any data members. (cppreference even contain an example with it.)
Can one request the compiler to provide default implementation of equality comparison ...
10
votes
1
answer
290
views
Why does the memory order need to be Acquire in a single consumer linked-list queue when comparing pointer values?
This is a multi-producer single-consumer implementation translated from Rust, for the language-lawyer question, rewriting it in C++
template<class T>
struct Node{
std::atomic<Node*> ...
1
vote
2
answers
310
views
Can I clean the phrase of the C++ n4928 working draft (regarding mandatory copy-elision during initialization with identical types) like this?
So there is a phrase from the C++ Standard working draft (n4928):
[dcl.init.general] ¶ 16.6.1
If the initializer expression is a prvalue and the cv-unqualified version of the source type is the same ...
3
votes
1
answer
246
views
Need help understanding Synthesized three-way comparison
Can someone help me understand this part of cppreference?
https://en.cppreference.com/w/cpp/language/default_comparisons.html
Synthesized three-way comparison
The synthesized three-way comparison of ...
5
votes
1
answer
154
views
Unused short circuit result with side effects
To avoid recursive template programming I am relying on the short circuit evaluation of the result of lambdas combined with logical && using a fold expression. Is that safe to do or will the ...
7
votes
1
answer
334
views
<stdalign.h> and C++
C11 introduced <stdalign.h>, which defined the macros alignas to _Alignas and alignof to _Alignof. Additionally, the feature test macros __alignas_is_defined and __alignof_is_defined are defined ...
7
votes
1
answer
202
views
Visibility of C++ nested class complete definition in the presence of forward declarations
In C++, forward declarations introduce an incomplete type. Incomplete types can be used to declare pointers, but they cannot be used to initialize values or access members because the complete ...
0
votes
0
answers
117
views
Can std::(weakly)canonical return an error for existing directory absolute path?
Based on cppreference, I was under impression that std::canonical and std::weakly_canonical return the input path if it is an absolute directory path to existing directory that has no dot, dot-dot ...
0
votes
1
answer
180
views
Has the thread executed the previous full-expression if the next full-expression in the same thread is visible to another thread?
Consider this example:
#include <atomic>
#include <thread>
int main(){
std::atomic<int> v0 = 0;
std::atomic<int> v = 0;
std::thread t1([&](){
v0.store(...
15
votes
1
answer
1k
views
Is it Undefined Behavior to backport namespace std features to older C++ versions?
According to What are the reasons that extending the std namespace is considered undefined behavior?, adding anything to namespace std is Undefined Behavior, with some exceptions carved out, such as ...