Skip to content

Instantly share code, notes, and snippets.

@dinks
Created January 2, 2015 16:20
Show Gist options
  • Select an option

  • Save dinks/ec122d3d2dbad9f454aa to your computer and use it in GitHub Desktop.

Select an option

Save dinks/ec122d3d2dbad9f454aa to your computer and use it in GitHub Desktop.
Wat in C++
// http://madebyevan.com/obscure-cpp-features/
// ptr[3] is *(ptr + 3) and is therefore 3[ptr]
// Is this:
// 1) A variable of type std::string initialized to a std::string()?
// 2) The declaration of a function that returns a std::string and has one argument,
// which is a pointer to a function with no arguments that returns a std::string?
std::string foo(std::string());
// Is this:
// 1) A variable of type int initialized to int(x)?
// 2) The declaration of a function that returns an int and has one argument,
// which is an int named x?
int bar(int(x));
// Parentheses resolve the ambiguity
std::string foo((std::string()));
int bar((int(x)));
// Redefining keywords via the preprocessor is technically supposed to cause an error but tools allow it in practice
#define class struct
#define private public
#define protected public
// Placement new
#include <iostream>
using namespace std;
struct Test {
int data;
Test() { cout << "Test::Test()" << endl; }
~Test() { cout << "Test::~Test()" << endl; }
};
int main() {
// Must allocate our own memory
Test *ptr = (Test *)malloc(sizeof(Test));
// Use placement new
new (ptr) Test;
// Must call the destructor ourselves
ptr->~Test();
// Must release the memory ourselves
free(ptr);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment