83

Currently, I am reading the source code of Protocol Buffer, and I found one weird enum codes defined here

  ~scoped_ptr() {
    enum { type_must_be_complete = sizeof(C) };
    delete ptr_;
  }

  void reset(C* p = NULL) {
    if (p != ptr_) {
      enum { type_must_be_complete = sizeof(C) };
      delete ptr_;
      ptr_ = p;
    }
  }

Why the enum { type_must_be_complete = sizeof(C) }; is defined here? what is it used for?

1
  • 2
    If I want to be that sure, then I'd rather use ptr_ itself in the sizeof as sizeof(*ptr_) instead of sizeof(C).
    – Nawaz
    Nov 20, 2015 at 6:51

4 Answers 4

81

This trick avoids UB by ensuring that definition of C is available when this destructor is compiled. Otherwise the compilation would fail as the sizeof incomplete type (forward declared types) can not be determined but the pointers can be used.

In compiled binary, this code would be optimized out and would have no effect.

Note that: Deleting incomplete type may be undefined behavior from 5.3.5/5:.

if the object being deleted has incomplete class type at the point of deletion and the complete class has a non-trivial destructor or a deallocation function, the behavior is undefined.

g++ even issues the following warning:

warning: possible problem detected in invocation of delete operator:
warning: 'p' has incomplete type
warning: forward declaration of 'struct C'

2
  • 1
    "Deleting incomplete type is undefined behavior" is incorrect. It's only UB if the type has a non-trivial destructor. The problem that this little trick addresses is precisely that deleting incomplete type is not always UB, so that the language supports it. Nov 19, 2015 at 10:27
  • Thanks @Cheersandhth.-Alf My point was it may be UB, so in general this line of code is UB. Edited.
    – Mohit Jain
    Nov 19, 2015 at 10:38
32

sizeof(C) will fail at compile time if C is not a complete type. Setting a local scope enum to it makes the statement benign at runtime.

It's a way of the programmer protecting themselves from themselves: the behaviour of a subsequent delete ptr_ on an incomplete type is undefined if it has a non-trivial destructor.

9
  • 1
    Can you explain why C needs to be a complete type at that point - is it necessary to have the complete type definition to call delete on it? And if so, why doesn't the compiler catch it anyway?
    – Peter Hull
    Nov 19, 2015 at 10:14
  • 1
    Isn't it rather about avoid C = void? If C were merely an undefined type, wouldn't the delete statement already fail?
    – Kerrek SB
    Nov 19, 2015 at 10:14
  • 1
    Looks like Mohit Jain has got the answer.
    – Peter Hull
    Nov 19, 2015 at 10:18
  • 1
    −1 "Setting a local scope enum to it makes the statement benign at runtime." is, uh, meaningless. I'm sorry. Nov 19, 2015 at 11:00
  • 1
    @SteveJessop thanks. The part I was missing was that deleting an incomplete type is UB.
    – Peter Hull
    Nov 21, 2015 at 19:51
29

To understand the enum, start with considering the destructor without it:

~scoped_ptr() {
    delete ptr_;
}

where ptr_ is a C*. If type C is incomplete at this point, i.e. all that the compiler knows is struct C;, then (1)a default-generated do-nothing destructor is used for the C instance pointed to. That's unlikely to be the right thing to do for an object managed by a smart pointer.

If deleting via a pointer to incomplete type had always had Undefined Behavior, then the standard could just require the compiler to diagnose it and fail. But it's well-defined when the real destructor is trivial: knowledge that the programmer can have, but the compiler doesn't have. Why the language defines and allows this is beyond me, but C++ supports many practices that today are not regarded as best practices.

A complete type has a known size, and hence, sizeof(C) will compile if and only if C is a complete type -- with known destructor. So it can be used as a guard. One way would be simply

(void) sizeof(C);  // Type must be complete

I would guess that with some compiler and options the compiler optimizes it away before it could notice that it shouldn't compile, and that the enum is a way to avoid such non-conforming compiler behavior:

enum { type_must_be_complete = sizeof(C) };

An alternative explanation for the choice of enum rather than just a discarded expression, is simply personal preference.

Or as James T. Hugget suggests in a comment to this answer, “The enum may be a way of creating a pseudo-portable error message at compile time”.


(1) The default-generated do-nothing destructor for an incomplete type was a problem with old std::auto_ptr. It was so insidious that it made its way into a GOTW item about the PIMPL idiom, written by the chair of the international C++ standardization committee Herb Sutter. Of course, nowadays that std::auto_ptr is deprecated, one will instead use some other mechanism.

6
  • 4
    The enum may be a way of creating a pseudo-portable error message at compile time. Nov 19, 2015 at 12:11
  • 1
    I think this answer explains the motivation of the code very well but I'd like to add that (1) some compilers have sizeof(T) evaluate to 0 for incomplete types instead of failing the compile. This is non-conforming behavior, however. (2) Since C++11, using static_assert((sizeof(T) > 0), "T must be a complete type"); would be a superior (and idiomatic) solution.
    – 5gon12eder
    Nov 21, 2015 at 3:34
  • @5gon12eder; Please provide an example of a C++ compiler that has “sizeof(T) evaluate to 0 for incomplete types”. Nov 21, 2015 at 5:13
  • 1
    I have never used such a compiler and I wouldn't be surprised to hear that they have died out by now. And even if they haven't, not caring about a non-conforming implementation is a valid decision. Nevertheless, both libstdc++ and libc++ use static_assert(sizeof(T) > 0, "…"); in their respective implementations of std::unique_ptr to make sure the type is complete …
    – 5gon12eder
    Nov 21, 2015 at 21:51
  • 1
    … so I think it is safe to say this is idiomatic. Anyway, since evaluating sizeof(T) in a boolean context is exactly equivalent to testing sizeof(T) > 0, it doesn't really matter except maybe for aesthetic reasons.
    – 5gon12eder
    Nov 21, 2015 at 21:51
3

Maybe a trick to be sure C is defined.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.