mercredi 16 décembre 2020

Force C++ to assign new addresses to arguments

It seems that when I pass different integers directly to a function, C++ assigns them the same address as opposed to assigning different addresses to different values. Is this by design, or an optimization that can be turned off? See the code below for an illustration.

#include <iostream>

const int *funct(const int &x) { return &x; }

int main() {

  int a = 3, b = 4;
  // different addresses
  std::cout << funct(a) << std::endl;
  std::cout << funct(b) << std::endl;

  // same address
  std::cout << funct(3) << std::endl;
  std::cout << funct(4) << std::endl;
}

The bigger context of this question is that I am trying to construct a list of pointers to integers that I would add one by one (similar to funct(3)). Since I cannot modify the method definition (similar to funct's), I thought of storing the address of each argument, but they all ended up having the same address.

Aucun commentaire:

Enregistrer un commentaire