[cfe-users] Code which compiles with g++ but not with clang++

Marshall Clow via cfe-users cfe-users at lists.llvm.org
Thu Nov 5 06:47:46 PST 2020


> On Nov 5, 2020, at 6:34 AM, Pavel Černohorský via cfe-users <cfe-users at lists.llvm.org> wrote:
> 
> Hello,
> 
> I would like to ask what is wrong with the following code:
> ```
> 
> #include <optional>
> 
> struct S
> {
>   S& operator=(S&) { return *this; };
> };
> 
> void thisWillNotCompileInClang()
> {
>  std::optional<S> a;
> }
> 
> ```
> 
> Compilation command is `g++ or clang++ -std=c++17 -c source.cpp`. It compiles without problems with g++ 9.3.0, but not with clang++ 10.0.0 (both from current stable Ubuntu 20). This code is simplification of code using widely adopted rapidjson library which uses assignment operator with non-const parameter a lot. Earlier versions of clang did not complain (tried with 7.0.1 on currently stable Debian Buster).

I tried this code on compiler explorer.
It compiles w/o error with clang + libc++
It fails to compile with clang and libstdc++

The error message given is:

In file included from <source>:1:
/opt/compiler-explorer/gcc-10.2.0/lib/gcc/x86_64-linux-gnu/10.2.0/../../../../include/c++/10.2.0/optional:158:7: error: the parameter for this explicitly-defaulted copy assignment operator is const, but a member or base requires it to be non-const
     operator=(const _Optional_payload_base&) = default;
     ^
/opt/compiler-explorer/gcc-10.2.0/lib/gcc/x86_64-linux-gnu/10.2.0/../../../../include/c++/10.2.0/optional:357:7: note: in instantiation of template class 'std::_Optional_payload_base<S>' requested here
   : _Optional_payload_base<_Tp>
     ^
/opt/compiler-explorer/gcc-10.2.0/lib/gcc/x86_64-linux-gnu/10.2.0/../../../../include/c++/10.2.0/optional:631:30: note: in instantiation of template class 'std::_Optional_payload<S, true, false, false>' requested here
     _Optional_payload<_Tp> _M_payload;
                            ^
/opt/compiler-explorer/gcc-10.2.0/lib/gcc/x86_64-linux-gnu/10.2.0/../../../../include/c++/10.2.0/optional:660:15: note: in instantiation of template class 'std::_Optional_base<S, true, true>' requested here
   : private _Optional_base<_Tp>,
             ^
<source>:10:20: note: in instantiation of template class 'std::optional<S>' requested here
 std::optional<S> a;
                  ^
1 error generated.


— Marshall
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-users/attachments/20201105/e9cf5efe/attachment-0001.html>


More information about the cfe-users mailing list