Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 588
martinus Avatar asked Jan 03 '17 10:01

martinus


2 Answers

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).

like image 56
Ohad Eytan Avatar answered Sep 22 '22 04:09

Ohad Eytan


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.

like image 27
sameerkn Avatar answered Sep 21 '22 04:09

sameerkn