Intel® C++ Compiler
Community support and assistance for creating C++ code that runs on platforms based on Intel® processors.
7956 Discussions

Way to disable nullptr check in placement new?

Dave_P_1
Beginner
852 Views

Is there a way to disable the nullptr check in placement new?

As of C++17 the nullptr check is no longer required: "If the standard placement allocation function returns a null pointer, which is possible if the user passes a null pointer as the argument, the behavior is undefined. (since C++17)", from http://en.cppreference.com/w/cpp/language/new

The change to C++17 was made specifically to remove the nullptr check: "This test is unnecessary overhead; it should be the user's responsibility to ensure that a null pointer is not used in these forms of placement new, just as for other cases when a pointer is dereferenced.", from Defect Report 1748 at http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html

I am using the Intel C++ 64 compiler for Windows, version 18.0.0.124 Build 20170811.  Among the things that I have tried are the command line option /Qstd=c++17, and using the __assume statement as a hint to the optimizer that the memory pointer is not a nullptr.  Here is a snippet from the assembler output showing the nullptr check:

;;;   __assume( nullptr != MemoryPointer );
;;;   BaseClass* Pointer = new( MemoryPointer ) MyClass();
        test      rbx, rbx
        je        .B1.5
.B1.3::
        mov       rax, QWORD PTR [__$U2a.0.168]
        mov       QWORD PTR [rbx], rax
.B1.4::
        mov       rcx, rbx
        jmp       .B1.6
.B1.5::
        xor       ecx, ecx
.B1.6::        

The command line I used:

icl /FAs /Os /Qstd=c++17 test.cpp

The source code for test.cpp:

#include 

class BaseClass
{
  public:
    virtual void Write() { std::cout << "BaseClass"; return; }
};

class MyClass: public BaseClass
{
  public:
    virtual void Write() override { std::cout << "MyClass"; return; }
};

void* GetMemoryPointer()
{
  return new int[1000];
}

int main()
{
  void* MemoryPointer = GetMemoryPointer();

  __assume( nullptr != MemoryPointer );
  BaseClass* Pointer = new( MemoryPointer ) MyClass();

  Pointer->Write();

  delete[] MemoryPointer;

  return 0;
}
0 Kudos
0 Replies
Reply