FAQ Database Discussion Community


The destructor for the class member `B`, why is it invoked in the snippet below?

c++,language-lawyer,c++14,delete-operator
From §5.3.5[expr.delete]/1, I can understand that the destructor for the object *a is not invoked in the snippet below. But I didn't understand why is the destructor for the class member B invoked in this case, as can be seen in this live example. #include <iostream> class A { public:...

Why can't I complete the type with the typedef?

c++,language-lawyer
Given an incomplete type in translation unit A: struct Incomplete; Incomplete* create_incomplete(); void destroy_incomplete(Incomplete*); why can't I use it in another translation unit, by using typedef? For example in translation unit B: struct Unrelated { int x; int y; }; typedef Unrelated Incomplete; Incomplete* create_incomplete() { return new Incomplete(); }...

Making a private inherited inner template public via a using directive

c++,templates,c++11,language-lawyer
I'm trying to use a using directive to bring in the public access declaration of a derived class some inner class template declared in the base. Code: template <typename T> class Base { public: template<typename U> struct Inner; }; template<typename T> class Derived: private Base<T> { public: using typename Base<T>::template...

Why do iterators need to be default-constructible

c++,stl,iterator,language-lawyer,standard-library
Iterators of the categories forward, bidirectional, and random access need to be default-constructible. Why is this, and why do input and output operators not have to be default-constructible? ...

May iterator's operator * return by-value?

c++,language-lawyer
So, I want to understand if it is allowed for const_iterator (i.e not mutable) to return by-value. What I have found is that return type of *r should be reference(1) where reference is iterator_traits<X>::reference(2). Naming clearly suggest that it's usually should be reference type, but does it have to? Are...

is return main(); a valid syntax?

c,function,return,language-lawyer,return-type
I found some interesting code lines: #include <stdio.h> int main() { printf("Hi there"); return main(); } It compiles ok (VS2013) and ends up in stackoverflow error because of the recursive call to main(). I didn't know that the return statement accepts any parameter that can be evaluated to the expected...

std::vector::resize(size_type) requires CopyInsertable?

c++,c++11,language-lawyer
This question is made while I answer this another question. N3337 23.3.6.3 "vector capacity" says (it's in 770 page): void resize(size_type sz); Effects: If sz <= size(), equivalent to erase(begin() + sz, end());. If size() < sz, appends sz - size() value-initialized elements to the sequence. Requires: T shall be...

Is modifying the pointed value and the pointer at the same time UB

c++,c,language-lawyer,undefined-behavior
I know that C and C++ and different languages, but the following applies to both. TL/DR I know that i = i++; is UB, because i is modified twice in the expression and C and C++ forbids it. References : C99 6.5 : If a side effect on a scalar...

What is a trivial function?

c++,language-lawyer,c++14
[basic.def.odr]/3 makes a reference to the term "nontrivial function", whose definition I couldn't find in the Standard (N4140). [basic.def.odr]/3 A variable x whose name appears as a potentially-evaluated expression ex is odr-used by ex unless applying the lvalue-to-rvalue conversion (4.1) to x yields a constant expression (5.19) that does not...

AFAIK, the code below shouldn't compile, but it does in clang and GCC. What am I missing here?

c++,c++11,language-lawyer
The code below shows a union-like class with a non-trivial default constructor (member y is initialized with a brace-or-equal-initializer), so if a default constructor for such a class is defaulted, it should be deleted according to §12.1/5 first bullet point. That is, the declaration T t; should not compile, as...

Can headers always be combined?

http,http-headers,language-lawyer
If I have two headers with the same name (and assuming that this makes sense and is valid) Some-Header: foo Some-Header: bar can they always be combined? Some-Header: foo,bar I am looking for guarantees (or lack thereof) made by the HTTP RFCs. (If the standards differ from practice, I'd be...

non-static data member initialization with new expression

c++,c++11,gcc,language-lawyer
Consider the following code: #include <map> template <typename T> struct X { std::map<int, T>* storage = new std::map<int, T>(); }; int main() { X<int> x; } This compiles on clang 3.6.0, but fails to compile on gcc 5.1. It would compile, however, if the type of storage were instead std::vector<T>*...

constexpr char array with GCC and clang

c++,arrays,c++11,language-lawyer,constexpr
Consider the following code: #include <cstddef> #include <iostream> #include <stdexcept> class const_string { public: template <std::size_t sz> constexpr const_string(const char (&str)[sz]): p_(str) {} constexpr char operator[](std::size_t i) const { return p_[i]; } private: const char* p_; }; template <char c> void Print() { std::cout << c << '\n'; } int...

Does not evaluating the expression to which sizeof is applied make it legal to dereference a null or invalid pointer inside sizeof in C++?

c++,language-lawyer,sizeof,undefined-behavior,null-pointer
First of all, I've seen this question about C99 and the accepted answer references operand is not evaluated wording in the C99 Standard draft. I'm not sure this answer applies to C++03. There's also this question about C++ that has an accepted answer citing similar wording and also In some...

Why char is of 1 byte in C lanaguage

java,c,char,language-lawyer
Why char is of 1 byte in C? Why it's not of 2 bytes or 4 bytes? What is the basic logic behind it to kept it in 1 byte? I know in Java it's of 2 bytes. Same question for it....

Initialize data members of class in C++ 11

c++,initialization,language-lawyer
I am curious to know that why class' data members can't be initialized using () syntax? Consider following example: #include <iostream> class test { public: void fun() { int a(3); std::cout<<a<<'\n'; } private: int s(3); // Compiler error why??? }; int main() { test t; t.fun(); return 0; } The...

Is it safe to use operator [] for std::string

c++,language-lawyer
I'm fighting with an old c-style-interface. I have a function with a signature like this: /// if return_value == NULL only the length is returned void f( char * return_value, size_t * size_only_known_at_runtime); My question is, is the following code safe? std::size required; f( NULL, &required ); std::string s; s.resize(required);...

Function signature returning abstract class

c++,abstract-class,language-lawyer,signature
Consider some abstract class A: class A { virtual void f() = 0; }; Suppose I wish to declare a function signature type returning this class: using Type = A(); Given this code, gcc-4.8.2 failes with error error: ‘type name’ declared as function returning an abstract class type clang-3.3 compiles...

Using `reinterpret_cast` on an enum class - valid or undefined behavior?

c++,language-lawyer,c++14,reinterpret-cast,enum-class
#include <iostream> #include <cassert> #include <type_traits> template<typename T> using Underlying = std::underlying_type_t<T>; enum class ETest : int { Zero = 0, One = 1, Two = 2 }; template<typename T> auto& castEnum(T& mX) noexcept { // `static_cast` does not compile // return static_cast<Underlying<T>&>(mX); return reinterpret_cast<Underlying<T>&>(mX); } int main() { auto...

Memory location of bit-fields

c++,language-lawyer,bit-fields
From the November 2014 working draft of the C++14 standard: § 1.7 6 c ISO/IEC N4296 5 [Example: A structure declared as struct { char a; int b:5, c:11, :0, d:8; struct {int ee:8;} e; } contains four separate memory locations: The field a and bit-fields d and e.ee are...

Is this code standard compliant or not?

c++,c++11,language-lawyer,c++14,c++98
So the code is class A { public: int i; A(){ i = 5; } }; class B : public A { public: void someFunc(); }; class C { A myObj; public: void func(){ B* foo = reinterpret_cast<B*>(&myObj); foo->someFunc(); } }; Assuming that classes will stay as they are and...

Why is the value of a pointer-to-member always the same for different members of the same struct?

c++,language-lawyer,pointer-to-member
I have the following code: #include <iostream> #include <string> using namespace std; struct foo_s { string a; string b; string c; }; void print_field(foo_s* foo, string foo_s::* field) { cout << "field: " << field << " - " << foo->*field << endl; } int main() { foo_s my_foo =...

C++: Is the ignored return value destruction behavior well-defined

c++,language-lawyer
Question: Is an ignored return value destructed immediately or at the moment going out of scope.? The code below returns for my compiler Output: Who makes it, has no need of it. Who buys it, has no use for it. Who uses it can neither see nor feel it. What...

does enum fields have default values in c language

c,enums,initialization,language-lawyer
I'm reading a c code somewhere, I found this structure typedef enum { SPIIP_0, SPIIP_1, NUMBER_OF_SPIIP, ERROR_SPIIP }SPIIP_ID_E; and somewhere else in my code I found statemment : if(IP>NUMBER_OF_SPIIP) but NUMBER_OF_SPIIP value is declared nowhere my quesion is : deos enum type define value to it's elements ...

Does MISRA C 2012 say not to use bool

language-lawyer,c99,misra,pc-lint
I am in the early stages of framing stuff out on a new project. I defined a function with a return type of "bool" I got this output from PC-Lint Including file sockets.h (hdr) bool sock_close(uint8_t socket_id); ^ "LINT: sockets.h (52, 1) Note 970: Use of modifier or type '_Bool'...

Compilation issue with instantiating function template

c++,c++11,language-lawyer,variadic-templates,function-templates
Consider the following code: #include <iostream> struct S { void f(const char* s) { std::cout << s << '\n'; } }; template <typename... Args, void(S::*mem_fn)(Args...)> void invoke(S* pd, Args... args) { (pd->*mem_fn)(args...); } int main() { S s; void(*pfn)(S*, const char*) = invoke<const char*, &S::f>; pfn(&s, "hello"); } When compiling...

Where in the Standard does it say that a member alias-declaration can be used as if it was a static member?

c++,alias,language-lawyer,c++14
Consider the following snippet: #include <iostream> struct A { int i; using Int = int; }; int main() { std::cout << sizeof(A::Int) << '\n'; } It compiles and executes normally in clang and GCC. I know this looks obvious, but I couldn't find anything in the Standard (C++14) supporting the...

clang bug? namespaced template class' friend

c++,g++,language-lawyer,clang++
The following code which doesn't compile under clang but does under gcc and VS: template<typename T> class bar; namespace NS { template<typename T> class foo { foo() {} template<typename U> friend class bar; }; } template<typename R> class bar { public: bar() { NS::foo<int> f; } }; int main(int, char...

Ambiguous name lookup with using-directive

c++,language-lawyer,name-lookup,qualified-name
It's not allowed to put a namespace and a class with the same name into one declarative region, i.e. namespace A {} class A{}; is ill-formed (see §3.3.1/4). However, one can introduce the name of either one via a using-directive: namespace N { namespace A {int i;} } struct A...

Where in the C++ Standard the lookup for an unqualified *mem-initializer-id* is defined?

c++,language-lawyer
This is the very first sentence in §12.6.2/2 (C++14): In a mem-initializer-id an initial unqualified identifier is looked up in the scope of the constructor’s class and, if not found in that scope, it is looked up in the scope containing the constructor’s definition. I would like to know where,...

How is friendship conferred for a class defined within a friend function?

c++,language-lawyer
The question is self explanatory, but here's an example if desired: Say I have a class 'Thing' with a private constructor, that is friends with a function 'make_thing': class Thing { friend std::shared_ptr<Thing> make_thing(); Thing() { std::cout << "Thing constructor" << std::endl; } }; The 'make_thing' function has a struct...

Explicit call to destructor of template parameter type, even when instantiated on a builtin

c++,language-lawyer
The C++ program (somewhat unexpectedly, at first, to me) compiles and runs fine, except for the line commented at the end of main(), which is a compile-time error if it is uncommented. #include <typeinfo> #include <iostream> struct Foo { int x; }; template <typename T> void create(char *buffer) { std::cout...

Can an implementation specify undefined behavior

c,standards,language-lawyer,undefined-behavior,c11
3.4.1 1 implementation-defined behavior unspecified behavior where each implementation documents how the choice is made Can an implementation specify that, implementation-defined behavior is undefined behavior in cases where undefined behavior is a possible outcome? For example: 6.3.1.3 Signed and unsigned integers 3 Otherwise, the new type is signed and...

C++11 introduced exception constructors taking `const char*`. But why?

c++,exception,c++11,language-lawyer
Standard library defect #254 which covers the addition of new exception constructors: std::logic_error::logic_error(const char* what_arg); std::runtime_error::runtime_error(const char* what_arg); // etc. gives as rationale the idea that storing std::strings opens up some cans of worms relating to potentially problematic memory allocation. However, following initiation of a discussion by orlp in the...

Function returning another function

c++,declaration,language-lawyer
The question may be sounded quite silly, but why can't we do so? I mean, a declarator like the following: void (foo())(); I've read the section 8.3.5 of the current C++ standard and didn't find how it implies from what said there. Here is what the standard said about that:...

What is included in C Standard library?

c,linux,posix,standards,language-lawyer
I will give an example from The GNU C Library documentation: 13.1 Opening and Closing Files This section describes the primitives for opening and closing files using file descriptors. The open and creat functions are declared in the header file fcntl.h, while close is declared in unistd.h. My question is:...

C11 & C++11 Exended and Universal Character Escaping

c++,c++11,language-lawyer,c11,ucn
Context C11 and C++11 both support extended characters in source files, as well as Universal Character Names (UCNs), which allow one to enter characters not in the basic source character set using only characters that are. C++11 also defines several translation phases of compilation. In particular, extended characters are normalized...

C operator += Sequence point?

c,pointers,language-lawyer,undefined-behavior,sequence-points
Is this defined behaviour? *p += *p--; And, if it is, is it equivalent to { p[0] += p[0]; --p; } or to { p[-1] = p[0]; --p; } ? I'm guessing the being defined or not depends on whether += has an implicit sequence point and, if it has,...

Reference as a non-type template argument

c++,c++11,language-lawyer
The example below attempts to use a variable of reference type as an argument for a non-type template parameter (itself of reference type). Clang, GCC and VC++ all reject it. But why? I can't seem to find anything in the standard that makes it illegal. int obj = 42; int&...

Is std::string::npos == -1 always true?

c++,casting,language-lawyer
The title is relatively self explanatory. I recognize the similarity to other answers, but all of those have different arrangements of operators (and therefore different casting rules). So I require an answer that clarifies this particular case. If someone could point out the section of the standard that explains this,...

Declaring friend class template via wrapper

c++,templates,language-lawyer,friend
I've seen the following pre-C++11 code, used as a trick to declare class template friends (which in C++11 can simply be done with friend T;) template <typename T> struct Wrapper { typedef T type; }; template <typename T> class Foo { friend class Wrapper<T>::type; // effectively makes T a friend...

Is it definitely illegal to refer to a reserved name?

c++,c++11,language-lawyer,c++14
On the std-proposals list, the following code was given: #include <vector> #include <algorithm> void foo(const std::vector<int> &v) { #ifndef _ALGORITHM std::for_each(v.begin(), v.end(), [](int i){std::cout << i; } #endif } Let's ignore, for the purposes of this question, why that code was given and why it was written that way (as...

Is it legal to read data out of a function pointer?

c,language-lawyer
Per the standard, is it legal to access data from a function pointer? Something like: #include <stdio.h> int test(){ // } int main() { int (*fp)(void) = &test; int i=0; for(i; i<10; ++i) printf("%x", *(fp+i)); } Running on ideone, it seems to work - but I'm wondering if it is...

Does C language specify any implicit initialization for void pointers only?

c,pointers,initialization,language-lawyer,void-pointers
Here is my code: int main() { int *p; void *x; printf("%p\n", p); printf("%p\n", x); return 0; } which will print: koraytugay$ ./a.out 0x7fff53b35ad0 0x0 koraytugay$ ./a.out 0x7fff5803fad0 0x0 koraytugay$ ./a.out 0x7fff512c9ad0 0x0 koraytugay$ ./a.out 0x7fff55213ad0 0x0 koraytugay$ ./a.out 0x7fff52dbdad0 0x0 Is there any explanation to this behaviour in the...

Must the C++ standard library support classes that are picky about who their friends are?

c++,stl,language-lawyer,friend,access-modifiers
This question is easiest to illustrate with an example, so here goes: Is code like the following guaranteed to be valid, and compile & run correctly? (Not all implementations actually compile it correctly, but I'm wondering if that's a bug.) #include <algorithm> class Picky { friend Picky *std::copy<Picky const *,...

Do C# and Java longs form a commutative ring?

java,c#,language-lawyer,integer-overflow
A ring is a standard mathematical structure describing objects which can be added and multiplied. Do C# and Java signed longs obey all the properties of a ring? For example, is multiplication by Long.MIN_VALUE always associative and distributive? Assume we are in an unchecked context. (definition copied from Wikipedia) A...

C++ Templates with pointer to member function by signature and type

c++,templates,pointers,function-pointers,language-lawyer
The code below works fine but I can't figure out based what points of the C++ standard it should be valid. template< class C, class signature > void f(signature C::*ptr) { } When C = A and signature = void(float, int), the function f will be void f(void(A::*ptr)(float, int)) Based...

static_assert dependent on non-type template parameter (different behavior on gcc and clang)

c++,templates,language-lawyer,c++14,dependent-name
template <int answer> struct Hitchhiker { static_assert(sizeof(answer) != sizeof(answer), "Invalid answer"); }; template <> struct Hitchhiker<42> {}; While trying to disable general template instantiation with static_assert I discovered that the above code in clang generates the assert error even when the template is not instantiated, while gcc generates the assert...

Template overload resolution for operators inside an anonymous namespace

c++,templates,gcc,language-lawyer,argument-dependent-lookup
Short question: do operators have special template lookup rules for overload resolution with internal linkage or is the code at the bottom a template overload resolution bug for operators in GCC? The detail: instead of pasting a chunk of code I'll take you through my reasoning. Let's start with some...

What does 'transmitted' mean in printf function return?

c,language-lawyer
I'm confused the interpretation of printf's return value and buffered stream in Standard C Library. In C99:TC3 Standard, 7.19.6.3/p3 defines that printf function returns non-negative "number of characters transmitted" in success. Also, 7.19.3/p3 describes the behaviors of fully/line buffered stream with "transmitted to or from the host environment", and p7...

Is there any reason for §3.3.7/1.2 to be considered an error?

c++,language-lawyer
This code was obtained from the example in §3.3.7/1.5: enum { i = 1 }; class X { char v[i]; // error: i refers to ::i // but when reevaluated is X::i enum { i = 2 }; }; GCC emits an error because of §3.3.7/1.2 However, if we apply...

Does reinterpret_casting an integral to a pointer type and back yield the same value?

c++,pointers,language-lawyer,integral,reinterpret-cast
According to http://en.cppreference.com/w/cpp/language/reinterpret_cast, it is known that reinterpret_cast a pointer to an integral of sufficient size and back yield the same value. I'm wondering whether the converse is also true by the standards. That is, does reinterpret_cast an integral to a pointer type of sufficient size and back yield the...

Is typename required or not here?

c++,templates,c++11,language-lawyer,typename
Consider the code: #include <memory> template <class T, class Deleter = std::default_delete<T>> class unique_ptr_wrapper: public std::unique_ptr<T, Deleter> { public: using typename std::unique_ptr<T, Deleter>::unique_ptr; operator T* () const {return this->get();} }; int main() { unique_ptr_wrapper<int> upw{new int{42}}; } g++5.1 compiles it fine, although clang++ complains error: typename is allowed for identifiers...

Is round-trip through floating point always defined behavior if floating point range is bigger?

c++,language-lawyer,c++14,floating-point-conversion
Let's say I have two arithmetic types, an integer one, I, and a floating point one, F. I also assume that std::numeric_limits<I>::max() is smaller than std::numeric_limits<F>::max(). Now, let's say I have a positive integer value i. Because the representable range of F is larger than I, F(i) should always be...

Why is repeated inheritance / duplicate inheritance invalid?

c++,inheritance,multiple-inheritance,language-lawyer
This code is invalid: struct Agent {}; struct DoubleAgent : public Agent, public Agent {}; Because: > g++ -c DoubleAgent.cpp DoubleAgent.cpp:2:43: error: duplicate base type ‘Agent’ invalid struct DoubleAgent : public Agent, public Agent {}; ^ Why? I don't think this violates the concept of inheritance; if a class can...

Why are the UINTX_C() macros not properly defined in Windows stdint.h?

c++,macros,windows-7-x64,language-lawyer
In MVSC, when I #include <stdint.h>, I end up with the following definitions for the UINTX_C and INTX_C macros: #define INT8_C(x) (x) #define INT16_C(x) (x) #define INT32_C(x) ((x) + (INT32_MAX - INT32_MAX)) #define UINT8_C(x) (x) #define UINT16_C(x) (x) #define UINT32_C(x) ((x) + (UINT32_MAX - UINT32_MAX)) Clearly the 8 and 16-bit...

Does the following chained assignment cause Undefined behavior?

c,variable-assignment,language-lawyer,undefined-behavior
Does the following code invoke undefined behavior in C? int a = 1, b = 2; a = b = (a + 1); I know that the following does invoke UB: a = b = a++; The reason is that it violates the following clause from the standard: Between the...

Is it legal to for a function declared “inline” to be recursive?

c,recursion,segmentation-fault,inline,language-lawyer
I was thinking a little bit about the C programming language and started to wonder how inline interacts with recursion. I made this test program to find out. static inline void f(void) { f(); } int main(void) { f(); return 0; } I compile the program using gcc and get...

Why is implicit pointer of pointer to pointer conversion legal?

c,pointers,language-lawyer
I recently came across some code on stackoverflow where pointers to pointers where used to change allocated memory. While checking the code I made the mistake to add an ampersand to a pointer so make a pointer to a pointer still the compiler happily compiled and runtime errors occured. As...

Can addresses of unmodified locals wind up corrupted in setjmp/longjmp?

c,clang,language-lawyer,longjmp,address-sanitizer
If one winds up in the situation of being stuck using setjmp/longjmp (don't ask), then there are lots of nice warnings from the compiler about when you might be doing something wrong. But with a -Wall -Wextra -pedantic build while using Address Sanitizer in Clang, I wound up with a...

Reading uninitialized variable

c++,language-lawyer
Reading uninitialized variables leads to undefined behavior, e.g. #include <iostream> int a; std::cout << a << std::endl; // undefined behavior Can someone give a formal explanation of this fact?...

Adjacent character and string literal tokens

c,string,char,language-lawyer,c11
It's a familiar fact that in C you can write "a" "b" and get "ab". This is discussed in the C11 standard: In translation phase 6, the multibyte character sequences specified by any sequence of adjacent character and identically-prefixed string literal tokens are concatenated into a single multibyte character sequence....

Does it violate the standard for a non-default-constuctible struct to lack a user-defined constructor?

c++,visual-studio-2012,language-lawyer,default-constructor,aggregate-initialization
It is possible to define a struct (a) that has no user-defined constructors, and (b) for which a default constructor cannot be generated. For example, Foo in the below: struct Baz { Baz(int) {} }; struct Foo { int bar; Baz baz; }; You can still create instances of Foo...

Do parentheses make a difference when determining the size of an array?

c,arrays,language-lawyer,sizeof,parentheses
The following program prints the same number twice on gcc 4.8.2: #include <stdio.h> int main() { char a[13]; printf("sizeof a is %zu\n", sizeof a ); printf("sizeof(a) is %zu\n", sizeof(a)); } According to this reddit post, gcc is not standard-conformant in this respect, because a parenthesized expression is not on the...

Why is this configurable property not deletable?

javascript,properties,language-lawyer,ecma262
Configurable properties seem to be deletable: var o = {}; Object.defineProperty(o, 'prop', { configurable: true, value: 'val' }); delete o.prop; // true o.prop; // undefined But it doesn't work in the following case, at least on Firefox and Chrome: var form = document.createElement('form'), input = document.createElement('input'); form.appendChild(input); var elems =...

Ambiguity in the standard on undefined behaviour of out of range pointer

c++,c++11,language-lawyer,semantics,undefined-behavior
ISO IEC 14882-2011 §5.7/5 States: If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. This section is used here on stackoverflow...

Weird overload resolution with variadic function templates

c++,c++11,language-lawyer,variadic-templates,overload-resolution
I have the following code: #include <iostream> template <typename... Args> void f(int a, int b, Args... args) { std::cout << b << '\n'; f(a, args...); } void f(int, int b) { std::cout << b << '\n'; } int main() { f(1, 2); //f(1, 2, 3); } While f(1, 2) compiles,...

MSVC 12 std::initializer_list bug when copying std::string

c++11,visual-studio-2013,language-lawyer,msvc12
I'm trying to create a C++ program with MSVC 12 (Visual Studio 2013, Update 4) which uses a std::initializer_list of structs which have std::string members. I seem to have run into a bug in MSVC. Here's a minimal example which exhibits the problem: #include <cassert> #include <initializer_list> #include <string> namespace...

What does a compiler check for uninstantiated template code?

c++,templates,gcc,clang,language-lawyer
For example, the following code piece compiles with gcc-4.9 and clang-602 class Base { public: static void foo() {} void badfoo(int i) {} }; template <typename T> class Derived : public Base { public: void bar() { Base::foo(); } void badbar() { Base::badfoo(); } // compiles ok //static void badbar()...

In C++, What does “access” mean in the strict aliasing rule?

c++,language-lawyer,strict-aliasing
3.10/10 says: If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined: However, the term "access" is not defined anywhere. In this context does it mean read, or read or modify ? In...

Why does ISO C forbid casting nonscalar to the same type

c,language-lawyer
struct Foo { int dummy; } bar; int main(void) { /* This statement causes GCC to produce the warning: * ISO C forbids casting nonscalar to the same type */ (volatile struct Foo)bar; /* The warning may be silenced like so. * Is this form superior or just trickier? Why?...

Can constexpr be combined with volatile?

c++,c++11,gcc,clang,language-lawyer
The following snippet works fine in Clang 3.5 but not in GCC 4.9.2: int main() { constexpr volatile int i = 5; } with error: error: both 'volatile' and 'constexpr' cannot be used here If I inspect the assembly that Clang generates, it shows 5 as expected: movl $5, -4(%rsp)...

Is it legal to call memcpy with zero length on a pointer just past the end of an array?

c,pointers,language-lawyer,undefined-behavior
As answered elsewhere, calling functions like memcpy with invalid or NULL pointers is undefined behaviour, even if the length argument is zero. In the context of such a function, especially memcpy and memmove, is a pointer just past the end of the array a valid pointer? I'm asking this question...

Issue with std::reference_wrapper

c++,c++11,language-lawyer,implicit-conversion,reference-wrapper
The issue is clear with the following code: #include <functional> #include <iostream> #include <vector> int main() { //std::vector<int> a, b; int a = 0, b = 0; auto refa = std::ref(a); auto refb = std::ref(b); std::cout << (refa < refb) << '\n'; return 0; } If I use the commented...

Are unsigned integer types always of different sizes?

c,language-lawyer
Is it possible (conforming to the C spec) to have 2 unsigned integer types of different ranges yet of the same size (due to padding)? #include <inttypes.h> #include <stdio.h> #include <stdint.h> int main(void) { printf("Size:%zu Max:%llu\n", sizeof(unsigned_32_t), (unsigned long long) ((unsigned_32_t) -1)); // Size:4 Max:4294967295 printf("Size:%zu Max:%llu\n", sizeof(unsigned_24_t), (unsigned long...

Integer promotion for implementations where sizeof(short) == sizeof(int)

c++,language-lawyer
Background I'm looking into integer promotion rules in C++, and came across the following (taken from n4296): 4.5.1 [pconv.prom] A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank (4.13) is less than the rank of int can be converted to a prvalue...

GCC rejects a simple-declaration with an enum-base; clang accepts it — which is correct?

c++,c++11,enums,language-lawyer,c++14
GCC 4.9.2 doesn't compile this snippet, but clang 3.5.0 does. Which one is correct? enum F : int { x, y, z}; int F; enum F:int f = F::x; GCC output : main.cpp:3:12: error: expected ';' or '{' before 'f' enum F:int f = F::x; ^ main.cpp:3:12: error: expected class-key...

Trying to understand [basic.def.odr]/2 in C++14 (N4140)

c++,language-lawyer,c++14
The Example in [basic.def.odr]/2 starts with the following sentence: In the following example, the set of potential results of the initializer of n contains the first S::x subexpression, but not the second S::x subexpression. From the definitions in this paragraph, how can we deduce that the initializer of n contains...

Safety of static_cast to pointer-to-derived class from base destructor

c++,casting,language-lawyer,static-cast
This is a variant of the questions Downcasting using the Static_cast in C++ and Safety of invalid downcast using static_cast (or reinterpret_cast) for inheritance without added members I am not clear on the phrase in the standard "B that is actually a subobject of an object of type D, the...

What do “positive” and “negative” mean in ECMAScript? +0 and -0

javascript,language-lawyer,specifications
I was reading the ECMAScript 5.1 spec. It says: The slice method takes two arguments, start and end [...]. If start is negative, it is treated as length+start where length is the length of the array. If end is negative, it is treated as length+end where length is the length...

Can an implementation consider hints as actual statements?

c,embedded,language-lawyer
In C, the register storage qualifier is an hint to the implementation that such identifier should be accessed as fast as possible (e.g. stored in a CPU register). §6.7.1 A declaration of an identifier for an object with storage-class specifier register suggests that access to the object be as fast...

Understanding the example on lvalue-to-rvalue conversion

c++,language-lawyer,c++14,constexpr,lvalue-to-rvalue
I have a hard time understanding how this code (an example from the C++14 draft standard [conv.lval]) invokes undefined behavior for g(false). Why does constexpr make the program valid? Also, what does it mean by "does not access y.n"? In both calls to g() we are returning the n data...

Why does the Java 8 generic type inference pick this overload?

java,generics,java-8,language-lawyer
Consider the following program: public class GenericTypeInference { public static void main(String[] args) { print(new SillyGenericWrapper().get()); } private static void print(Object object) { System.out.println("Object"); } private static void print(String string) { System.out.println("String"); } public static class SillyGenericWrapper { public <T> T get() { return null; } } } It prints...

I don't understand how the template function gets to be a friend of the class A::X::Y in the example in [namespace.memdef]/3 in C++14

c++,templates,language-lawyer,c++14,friend
Consider the following code from the example in [namespace.memdef]/3 in C++14: // Assume f and g have not yet been declared. void h(int); template <class T> void f2(T); namespace A { class X { friend void f(X); // A::f(X) is a friend class Y { friend void g(); // A::g...

C++14 warning: too many template headers for variable (should be 0)

c++,language-lawyer,c++14,template-specialization,variable-templates
While experimenting with the recent g++-5 compiler, I wrote below statement in a file: template<T> T a; template<> int a = 1; Which results in: warning: too many template headers for a (should be 0) Also effectively, it doesn't really specialize a<int>. e.g. template<typename T> T a; template<> int a...

Do floats, doubles, and long doubles have a guaranteed minimum precision?

c++,floating-point,language-lawyer,floating-point-precision,minimum
From my previous question "Is floating point precision mutable or invariant?" I received a response which said, C provides DBL_DIG, DBL_DECIMAL_DIG, and their float and long double counterparts. DBL_DIG indicates the minimum relative decimal precision. DBL_DECIMAL_DIG can be thought of as the maximum relative decimal precision. I looked these macros...

.net decimal - remove scale, solution that is guaranteed to work

c#,decimal,language-lawyer
I want to convert a decimal a with scale > 0 to its equivalent decimal b with scale 0 (suppose that there is an equivalent decimal without losing precision). Success is defined by having b.ToString() return a string without any trailing zeroes or by extracting the scale via GetBits and...

Type punning a struct in C and C++ via a union

c++,c,language-lawyer,strict-aliasing,type-punning
I've compiled this in gcc and g++ with pedantic and I don't get a warning in either one: #include <stdio.h> #include <stdlib.h> #include <string.h> struct a { struct a *next; int i; }; struct b { struct b *next; int i; }; struct c { int x, x2, x3; union...

Contradictory results between GCC and clang related to [basic.link]/7 in the C++ Standard

c++,c++11,language-lawyer,c++14,linkage
This snippet compiles in clang, namespace A { void f() { void g(); g(); } } void A::g() { } but GCC only accepts the code if g is defined inside the namespace A as follows: namespace A { void f() { void g(); g(); } void g() {} }...

Does upcasting a null pointer lead to undefined behavior

c++,language-lawyer,implicit-conversion,nullptr,up-casting
I'm wondering whether the following code leads to undefined behavior: #include <cstddef> #include <cstdio> struct IA { virtual ~IA() {} int a = 0; }; struct IB { virtual ~IB() {} int b = 0; }; struct C: IA, IB {}; int main() { C* pc = nullptr; IB* pib...

Does deleting a copy constructor or copy assignment operator count as “user declared”?

c++11,move,language-lawyer,copy-constructor
Per this presentation, if either the copy constructor or copy assignment operator is "user declared", then no implicit move operations will be generated. Does deleteing the copy constructor or copy assignment operator count as "user declared"? struct NoCopy { NoCopy(NoCopy&) = delete; NoCopy& operator=(const NoCopy&) = delete; }; Will implicit...

Can we perform deleting object through a pointer to one of its base classes? [duplicate]

c++,language-lawyer,undefined-behavior
This question already has an answer here: Does delete work with pointers to base class? 2 answers Does it cause UB if we define a virtual destructor? For intance: struct A{ virtual ~A(){ } }; struct B : A { }; A *a = new B; int main() {...

Can't understand the declaration #3 in the Example of [basic.link]/6 C++14

c++,declaration,language-lawyer,c++14,extern
[basic.link]/6 The name of a function declared in block scope and the name of a variable declared by a block scope extern declaration have linkage. If there is a visible declaration of an entity with linkage having the same name and type, ignoring entities declared outside the innermost enclosing namespace...

Issue warning and compiling with warnings-as-errors violates compliance?

c++,language-lawyer
My question (Single line comment continuation) got me wondering about compiler compliance and warning messages, particularly with warnings-as-error feature in many compilers. From the C++ spec, § 1.4.2.1 states: If a program contains no violations of the rules in this International Standard, a conforming implementation shall, within its resource limits,...

Const vs. array-to-pointer conversions

c++,arrays,type-conversion,const,language-lawyer
Is the handling of constness in fa being turned inside out intentional, or does it look like a bug (compiler or the standard)? I can see how this can happen, but it still feels pretty weird (at the very least I would expect a = "qwe" to be treated as...

Is following statement valid in ANSI C? Is it valid at all?

c,language-lawyer,c89,sequence-points
During my preparation to exam on ANSI C I have encountered the following question - Is following statement valid? If not, please make required changes to make it valid. The original statement is: test(i++,i++); it isn't valid because the behaviour is undefined according to K&R p202 The order of evaluation...

Do C and C++ standards imply that a special value in the address space must exist solely to represent the value of null pointers?

c++,c,language-lawyer,systems-programming
Following discussion from this question about null pointers in C and C++, I'd like to have the ending question separated here. If it can be inferred from C and C++ standards (answers can target both standards) that dereferencing a pointer variable whose value is equal to the nullptr (or (void...

Does the C# compiler get the Color Color rule wrong with const type members?

c#,language-lawyer,member-access
Okay, so the C# Language Specification has a special section (old version linked) on the Color Color rule where a member and its type has the same name. Well-known guru Eric Lippert once blogged about it. The question I am going to ask here is in a sense (not) quite...

Scope and Default Arguments in Template Declarations in C++ : Clarifying Standardese

c++,templates,language-lawyer,c++14
I was reading through the C++14 standard's section on templates in an attempt to improve my understanding of the subject, and stumbled across this particular rule: § 14.1 12 A template-parameter shall not be given default arguments by two different declarations in the same scope. [Example: template<class T = int>...

Why does clang's stdbool.h contain #define false false

c++,clang,language-lawyer
After being pointed there by a compiler error, I noticed clang's stdbool.h file includes (among other things) the following lines: #define bool bool #define false false #define true true They're contained in an #ifdef block that enforces __cplusplus indirectly, hence the c++ tag even though stdbool.h is a C header....