In flüchtig umgewandelt, Unterschied zwischen C und C++C++

Programme in C++. Entwicklerforum
Anonymous
 In flüchtig umgewandelt, Unterschied zwischen C und C++

Post by Anonymous »

In C lässt sich der folgende Code gut kompilieren.

Code: Select all

typedef struct T {
int val;
} T;

void test(volatile T*p, T a) {
*p = (volatile T)a;  // doesn't work for G++
*p = a;  // doesn't work for G++
}
Aber in C++ (getestet von gcc 12.2) ist es illegal:

Code: Select all

: In function 'void test(volatile T*, T)':
:29:22: error: ambiguous overload for 'operator=' (operand types are 'volatile T' and 'volatile T')
29 |     *p = (volatile T)a;  // doesn't work for G++
|                      ^
:24:16: note: candidate: 'constexpr T& T::operator=(T&&)' (near match)
24 | typedef struct T {
|                ^
:24:16: note:   conversion of argument 1 would be ill-formed:
:29:10: error: binding reference of type 'T&&' to 'volatile T' discards qualifiers
29 |     *p = (volatile T)a;  // doesn't work for G++
|          ^~~~~~~~~~~~~
:24:16: note: candidate: 'constexpr T& T::operator=(const T&)' (near match)
24 | typedef struct T {
|                ^
:24:16: note:   conversion of argument 1 would be ill-formed:
:29:10: error: binding reference of type 'const T&' to 'volatile T' discards qualifiers
29 |     *p = (volatile T)a;  // doesn't work for G++
|          ^~~~~~~~~~~~~
:30:10: error: passing 'volatile T' as 'this' argument discards qualifiers [-fpermissive]
30 |     *p = a;  // doesn't work for G++
|          ^
:24:16: note:   in call to 'constexpr T& T::operator=(const T&)'
24 | typedef struct T {
|
Warum möchte der C++-Standard es als illegal betrachten und was ist die beste Vorgehensweise, um die Struktur zu definieren, damit es funktioniert?
Alle Vorschläge wären willkommen :)
[Bearbeiten]
Ich folge dem Vorschlag von @Einigem Programmierer-Typ

Damit dies möglich ist, muss die Funktion vorhanden sein deklariert mit dem
volatile-Qualifizierer selbst: T& Operator=(T const&) volatile;

Code: Select all

typedef struct T {
int val;

T& operator=(const T &a) volatile {
val = a.val;
return const_cast(*this);
}
} T;

void test(volatile T*p, T a) {
*p = (volatile T)a;  // doesn't work for G++
*p = a;  // doesn't work for G++
}
Fehlermeldung von Clang 15 ist

Code: Select all

:15:8: error: no viable overloaded '='
*p = (volatile T)a;  // doesn't work for G++
~~ ^ ~~~~~~~~~~~~~
:8:8: note: candidate function not viable: 1st argument ('volatile T') would lose volatile qualifier
T& operator=(const T &a) volatile {
^
Ich bin mir nicht sicher, ob ich etwas falsch verstanden habe.

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post