Placement new and templates

Discussion in 'C++' started by Kalle Rutanen, May 19, 2005.

  1. Hello.

    The following code compiles fine with VC7. I seemingly call int's
    destructor. Why does it compile ? What does the standard say about this
    ?

    #include <new>

    using namespace std;

    template <typename T>
    void destruct(T* that)
    {
    that->~T();
    }

    int main()
    {
    char memory[100];
    int* a = 0;

    // Can do this...
    a = new(memory) int;
    destruct(a);

    // But can't do this
    a = new(memory) int;
    //a->~int();

    return 0;
    }
     
    Kalle Rutanen, May 19, 2005
    #1
    1. Advertisements


  2. It's explicitly allowed. It's called "pseudo-destructor call". The
    Standard defines that in 5.2.4. If your compiler does not allow you
    do

    int *pa;
    ...
    pa->~int();

    then your compiler is broken. For built-in types a pseudo-destructor
    call has no effect except to evaluate the expression before the . or
    the ->.

    V
     
    Victor Bazarov, May 20, 2005
    #2
    1. Advertisements

  3. Kalle Rutanen

    msalters Guest

    Victor Bazarov wrote:
    If your compiler does not allow you
    So a pedantic compiler may reject this as UB, considering
    that you're dereferencing an uinitialized pointer ;)

    Of course, normal compilers will just skip this instruction.

    Regards,
    Michiel Salters
     
    msalters, May 20, 2005
    #3
  4. The '...' contains all the necessary code to prevent the UB.

    V
     
    Victor Bazarov, May 20, 2005
    #4
  5. It's explicitly allowed. It's called "pseudo-destructor call". The
    Thank you for a clearing answer.
     
    Kalle Rutanen, May 20, 2005
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.