-2

Referring to this question, stackoverflow.com/q/14188612, are there situations when the compiler folds the method instantiation of two objects?

Let's say we have the following class with a private "stateless" method add, that does not modify the class members:

class Element
{
public:        
    Class(int a, int b) : a_(a), b_(b)
    {
        c_ = add(a, b);
    }

private:
    int add(int a, int b)
    {
        return a + b;
    }

private:
    int a_;
    int b_;
    int c_;
}

int main(void)
{
    Element a(1, 2);
    Element b(3, 4);
}

Can we sometimes expect that add will actually be compiled as a static-like method? Or, to be more clear, the address of a.add to be equal to b.add (add stored only once).

This is merely a question related to understanding compiler optimizations.

Alexandru Irimiea
  • 2,513
  • 4
  • 26
  • 46
  • The method is likely to be inlined, which makes whether it is static or not irrelevant. But you can't tell by checking addresses - it you take the address of the function then the compiler will give you the address of a non-inlined version, but may never call it. Look at the generated code, it is the only source of truth. – Alan Stokes Aug 20 '15 at 22:06
  • 2
    All functions are always stored at most once. – molbdnilo Aug 20 '15 at 22:09

3 Answers3

2

The compiler will always generate one binary method/function for add,
independent of how many objects you have. Anything else isn´t just stupid, but impossible:

The compiler can´t possibly know/calculate how many objects will exist during runtime just from the code. While it is possible with your example, more complicated programs will instantiate variables (or not) based on input given at runtime (keyboard, files...).

Note that templates can lead to more than one generation, one for each template type used in the code (but for that, the code is enough to know everything, and it has nothing to do with the object count).

deviantfan
  • 11,268
  • 3
  • 32
  • 49
0

When you define a method inside the class definition it usually means that the method should be inlined into each caller. The compiler can choose not to, but quite often you might find that the method doesn't actually exist in your output program at all (not true in debug builds, of course).

ams
  • 24,923
  • 4
  • 54
  • 75
0

For non-inline member functions, the standard says

There shall be at most one definition of a non-inline member function in a program

There is no entity in C++ b.add or a.add from which you can take the address. The address-of operator needs a qualified-id to a member function of the form C::m(...) to get the address of a function. In your case, the address of add is

   auto ptr = &Element::add;

and is independent from any instance. This gives a member-function pointer, which can only be used to call the function together with an object, e.g. (a.*ptr)(0,1) or (b.*ptr)(2,3) if add were a public method.

Jens
  • 9,058
  • 2
  • 26
  • 43