[Bug c++/77741] New: Add a warning about inadvertent converting constructor

akrzemi1 at gmail dot com gcc-bugzilla@gcc.gnu.org
Mon Sep 26 08:39:00 GMT 2016


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77741

            Bug ID: 77741
           Summary: Add a warning about inadvertent converting constructor
           Product: gcc
           Version: 6.1.1
            Status: UNCONFIRMED
          Severity: enhancement
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: akrzemi1 at gmail dot com
  Target Milestone: ---

PROBLEM DESCRIPTION:

It is a known C++ gotcha: you declare a one-argument non-explicit constructor,
even though you never intend it to participate in any conversion. This later
causes bugs in code due to the inadvertent conversion being silently used.
Everyone agrees that it would be better if C++ reversed the defaults: "a
constructor is by default explicit, if you want it in conversions define it as
/converting/". This cannot be done due to compatibility reasons, but a compiler
can achieve a similar effect by adding a new attribute and a warning.

THE FEATURE REQUEST:

Add a new attribute: [[converting]]. You can apply it to any non-explicit
constructor. Its purpose is to control warning messages.

Add a new warning -Wconverting (or some such) it causes a warning message in
two situations:

1. A constructor that could in C++ be used in conversions (single-argument or
one where a second argument has a default value) that is not a copy or move
constructor declared without attribute [[converting]].

2. An explicit constructor declared with attribute [[converting]].

As an illustration, the following code would trigger a number of -Wconverting
warnings:

```
class X
{
public:
  X (); // no warning
  X (X const&); // no warning: copy ctor
  X (int);     // warning: either add `explicit` or [[converting]]
  X (bool, bool = true); // warning: either add `explicit` or [[converting]] 
  explicit X(string); // no warning
  X (double) [[converting]]; // no warning
  explicit X(unsigned) [[converting]]; // warning either remove `explicit` or
[[converting]]
};
```


More information about the Gcc-bugs mailing list