https://gcc.gnu.org/bugzilla/show_bug.cgi?id=83818
Bug ID: 83818
Summary: g++ class template parameter deduction discards const
qualifier
Product: gcc
Version: 7.2.1
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: bugzilla.gcc.karo at cupdev dot net
Target Milestone: ---
The following code should fail to compile, since `s` is declared const; the
assignment to u should fail because it discards the const qualifier.
The assignment to s.x should also fail because `s` is const, but the code
compiles successfully;
# Code
```
template
struct tstruct {
T x;
tstruct(const T &x_) : x{x_} {}
};
int main() {
const tstruct s{2};
tstruct &u = s;
s.x = 2;
return 0;
}
```
# Compiling the code above (with class template parameter deduction)
```
$ g++ --std=c++17 -Wall -Wextra -Wpedantic g.cc -o g
g.cc: In function ‘int main()’:
g.cc:9:17: warning: unused variable ‘u’ [-Wunused-variable]
tstruct &u = s;
$ ls -al g
-rwxr-xr-x 1 karo karo 8.3K Jan 12 18:11 g*
```
# With explicitly added to avoid template parameter deduction
If I explicitly add the `` template parameter to the declaration of `s`,
gcc yields the correct errors and does not produce a file:
```
$ g++ --std=c++17 -Wall -Wextra -Wpedantic g.cc -o g
g.cc: In function ‘int main()’:
g.cc:9:21: error: binding reference of type ‘tstruct&’ to ‘const
tstruct’ discards qualifiers
tstruct &u = s;
^
g.cc:10:9: error: assignment of member ‘tstruct::x’ in read-only object
s.x = 2;
^
g.cc:9:17: warning: unused variable ‘u’ [-Wunused-variable]
tstruct &u = s;
```
# GCC Version
```
$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-pc-linux-gnu/7.2.1/lto-wrapper
Target: x86_64-pc-linux-gnu
Configured with: /build/gcc/src/gcc/configure --prefix=/usr --libdir=/usr/lib
--libexecdir=/usr/lib --mandir=/usr/share/man --infodir=/usr/share/info
--with-bugurl=https://bugs.archlinux.org/
--enable-languages=c,c++,ada,fortran,go,lto,objc,obj-c++ --enable-shared
--enable-threads=posix --enable-libmpx --with-system-zlib --with-isl
--enable-__cxa_atexit --disable-libunwind-exceptions --enable-clocale=gnu
--disable-libstdcxx-pch --disable-libssp --enable-gnu-unique-object
--enable-linker-build-id --enable-lto --enable-plugin
--enable-install-libiberty --with-linker-hash-style=gnu
--enable-gnu-indirect-function --enable-multilib --disable-werror
--enable-checking=release --enable-default-pie --enable-default-ssp
Thread model: posix
gcc version 7.2.1 20171128 (GCC)
```