[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Bug#344501: g++-4.0: spurious warning about explicit conversion operator to same type

Package: g++-4.0
Version: 4.0.2-5
Severity: normal


Given the following (stripped down) code as variant.cpp:

    #include <iostream>
    using std::cout;
    using std::endl;

    struct Variant
        Variant() {}
        template< typename T > Variant( T ) {}
        Variant( const Variant& ) {}
        Variant &operator=( const Variant& ) { return *this; }

        template< typename T > operator T() const
            cout << "operator T() called" << endl;
            return T();
        template< typename T > operator const T&() const
        {   static T test_dummy;
            cout << "operator T&() called with T = Variant, uh oh" << endl;
            return test_dummy;

      #ifdef WITH_WARNING
        operator Variant() const
            cout << "operator Variant() called" << endl;
            return *this;
        operator const Variant&() const
            cout << "but operator Variant&() _is_ called" << endl;
            return *this;

    Variant TempMaker( Variant v ) { return v; }

    int main()
        Variant v = TempMaker( 1 );
        return 0;

The following may be observed:

  $ make variant "CPPFLAGS=-Wconversion -DWITH_WARNING"
  g++  -Wconversion -DWITH_WARNING   variant.cpp   -o variant
  variant.cpp:39: warning: conversion to the same type will never use a
                  type conversion operator
  variant.cpp:44: warning: conversion to a reference to the same type
                  will never use a type conversion operator

  $ ./variant 
  but operator Variant&() _is_ called

  $ make variant CPPFLAGS=-Wconversion
  g++  -Wconversion   variant.cpp   -o variant

  $ ./variant 
  operator T&() called with T = Variant, uh oh

Indicating that the explicit operators are in fact called, despite
the warning, and are in fact necessary to avoid the compiler attempting
to use the template conversion operator with T = Variant(&) (and doing
bad recursive things in less stripped code) when temporaries are created
for the function call.

The simple answer to me is get rid of the warning, the code operates
intuitively correctly now, but things are rarely simple...


-- System Information:
Debian Release: testing/unstable
  APT prefers unstable
  APT policy: (500, 'unstable')
Architecture: i386 (i686)
Shell:  /bin/sh linked to /bin/bash
Kernel: Linux 2.6.12
Locale: LANG=C, LC_CTYPE=C (charmap=ANSI_X3.4-1968)

Versions of packages g++-4.0 depends on:
ii  gcc-4.0                       4.0.2-5    The GNU C compiler
ii  gcc-4.0-base                  4.0.2-5    The GNU Compiler Collection (base 
ii  libc6                         2.3.5-9    GNU C Library: Shared libraries an
ii  libstdc++6-4.0-dev            4.0.2-5    The GNU Standard C++ Library v3 (d

g++-4.0 recommends no packages.

-- no debconf information

Reply to: