2

If i have a simple class like this

class A {
    void private_function();
public:
    void public_function() { /* calls the private function in here */ }
};

Is the compiler required to emit object code for private_function(), or is it allowed to inline all calls to private_function() and to omit private_function from the generated executable?

Benno
  • 5,288
  • 5
  • 42
  • 60
  • 2
    Why would it matter what the compiler inlines? Just asking out of curiosity. – andre Oct 25 '13 at 15:16
  • Can you write a standard-conforming program that can tell the difference? If not, it's allowed. – Pete Becker Oct 26 '13 at 13:12
  • @Pete: Sure, but since there's an infinite number of standard-conforming programs that behave in intricate and sometimes arcane ways, its hard to give an answer to this question. – Benno Oct 28 '13 at 16:12

1 Answers1

4

Is the compiler required to emit object code for private_function()

It will have to if anything uses its address.

or is it allowed to inline all calls to private_function() and to omit private_function from the generated executable?

If nothing uses its address, yes. The program's behaviour would be identical whether or not it generated an unused non-inline version; so by the "as if" rule, it's free not to generate it.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • Could you point me towards the exact definition of odr-used? – Benno Oct 25 '13 at 15:36
  • @Benno: C++11 3.2/2. Though I may have misused the term here - it's *odr-used* if you call it, but you only need a non-inline definition if you take its address. – Mike Seymour Oct 25 '13 at 15:37
  • @MikeSeymour I believe it is perfectly legal to take the address of an inline function, is it not? – Sam Cristall Oct 25 '13 at 15:52
  • 1
    @SamCristall: It certainly is. If you do, then the compiler will have to generate a non-inline version, so that it has an address. If you don't, then it's free no to. – Mike Seymour Oct 25 '13 at 15:56
  • Is it possible for code outside of A to take the adress of private_function, or can this only happen within A? – Benno Oct 25 '13 at 16:17
  • @Benno: Since it's private, you have to be inside a member or friend of `A`. – Mike Seymour Oct 25 '13 at 16:19
  • Or someone did a `#define private public`. What if you have that define in a header for the include of a dynamic linked library, and not in library build? – BeniBela Oct 25 '13 at 16:55
  • @BeniBela: Then you've broken the One Definition Rule, and you've got undefined behaviour. – Mike Seymour Oct 25 '13 at 16:59