Qualcuno può spiegarmi perché questo codice funziona? Sento che il compilatore non dovrebbe permettermi di fare ciò che ho fatto (spostare un puntatore int in modo che punti a un const int), o in alternativa mi aspetterei almeno un avvertimento del compilatore o un segfault. L'idea di cambiare il valore di una costante sembra così sbagliata.Incremento di una costante in C++
Codice:
#include <iostream>
using namespace std;
struct test_struct {
int i;
const int j;
};
int main() {
cout << "Create a struct with int i = 100 and const int j = 101." << endl;
test_struct test{100, 101};
cout << test.i << endl;
cout << test.j << endl;
cout << "Create pointer p and point it to int i." << endl;
int* p1 = &test.i;
cout << *p1 << endl;
cout << "Increment pointer p, which should now be pointing at const int j." << endl;
p1++;
cout << *p1 << endl;
cout << "Dereference p and increment it." << endl;
(*p1)++;
cout << *p1 << endl;
cout << test.j << endl;
}
uscita:
Create a struct with int i = 100 and const int j = 101.
100
101
Create pointer p and point it to int i.
100
Increment pointer p, which should now be pointing at const int j.
101
Dereference p and increment it.
102
102
quale compilatore stai usando? – Creris
Sto usando il compilatore g ++. – rolledback
Un titolo migliore potrebbe essere: Modifica di una costante in una struttura incrementando un puntatore a un membro non const. – Csq