Skip to content

Instantly share code, notes, and snippets.

@odeblic
Last active July 27, 2017 11:31
Show Gist options
  • Save odeblic/ff82e57719ecdf828c2f07944fca9d41 to your computer and use it in GitHub Desktop.
Save odeblic/ff82e57719ecdf828c2f07944fca9d41 to your computer and use it in GitHub Desktop.
Different versions of new operator
#include <iostream>
struct Object
{
Object(int n = 0) : n(n)
{ std::cout << '[' << n << ']' << " Object::Object()" << std::endl; }
~Object()
{ std::cout << '[' << n << ']' << " Object::~Object()" << std::endl; }
int n;
};
char * buffer[100];
int main()
{
{
Object obj1(11);
}
Object * obj2 = new Object(22);
delete obj2;
Object * obj3 = new(buffer) Object(33);
obj3->~Object();
try
{
Object * obj4 = new Object[1000000000000];
delete[] obj4;
}
catch(std::bad_alloc e)
{
std::cout << "exception: cannot allocate 1000000000000 objects" << std::endl;
}
Object * obj5 = new(std::nothrow) Object[1000000000000];
if (obj5)
{
delete[] obj5;
}
else
{
std::cout << "null pointer: cannot allocate 1000000000000 objects" << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment