C++ inplace destructor compile warning

I am using an inplace destructor in my code, similar to this stripped down piece of code:

#include <new>
#include <stdlib.h>

struct Node {
};

int main(int, char**) {
    Node* a = reinterpret_cast<Node*>(malloc(sizeof(Node)));
    new(a) Node;

    Node* b = a; 
    b->~Node(); 

    free(a);
}

Unfortunately this gives me a warning in Visual Studio 2015, both in Debug and Release:

warning C4189: 'b': local variable is initialized but not referenced

It compiles fine though in g++, even with -Wall. Any idea why I get the warning? Might this be a bug in the compiler? b is clearly used in the b->~Node() call.

It also seems to compile fine when I change the Node implementation to this:

struct Node {
    ~Node() {
    }
};

But as far as I can say this should not make a difference.


There are no standards for compiler warning in C++. Hence each compiler can warn you wherever he wants, it is a matter of choice .

In your case the warning does make sense, since the default destructor may not consider as a reference (for example: all local variable are defaultly destroyed at the end of their scope).


Trivial destructor

The destructor for class T is trivial if all of the following is true:

  • The destructor is not user-provided (meaning, it is either implicitly declared, or explicitly defined as defaulted on its first declaration)
  • The destructor is not virtual (that is, the base class destructor is not virtual)
  • All direct base classes have trivial destructors
  • All non-static data members of class type (or array of class type) have trivial destructors.
  • A trivial destructor is a destructor that performs no action. Objects with trivial destructors don't require a delete-expression and may be disposed of by simply deallocating their storage.

    链接地址: http://www.djcxy.com/p/94712.html

    上一篇: 如何解决与Nginx的http重定向?

    下一篇: C ++ inplace析构函数编译警告