- 1
std::thread_fence(get_current_memory_order());
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+14
std::thread_fence(get_current_memory_order());
+16
#include <iostream>
using namespace std;
struct T
{
int a, b, &c;
T():a(0), b(1), c(a){cout<<"dc"<<endl;}
T(const T& a):a(a.a), b(a.b), c(&a.c == &a.a ? this->a : b){cout<<"cc"<<endl;}
T& operator=(T a)
{
::new((void*)(&b+1)) int*(&a.c == &a.a ? &this->a : &b);
//asm volatile ("" : : : "memory");
cout<<"co"<<endl;
return *this;
}
void Switch()
{
::new((void*)(&b+1)) int*(&c == &a ? &b : &a);
//asm volatile ("" : : : "memory");
cout<<"sw"<<endl;
}
} __attribute__((aligned(1))) ;
int main() {
T a;
cout<<a.a<<endl;
cout<<a.b<<endl;
cout<<a.c<<endl;
a.Switch();
cout<<a.c<<endl;
T b;
cout<<b.c<<endl;
b=a;
cout<<b.c<<endl;
b.b=666;
cout<<b.c<<endl;
return 0;
}
Очевидно откуда это.
+18
template <typename T>
struct canref {
struct yes { uint8_t bytes[1]; };
struct no { uint8_t bytes[2]; };
template <typename U> static yes test(U*p);
template <typename U> static no test(...);
static const bool value = sizeof(test<T>(NULL)) == sizeof(yes);
};
template <typename T, int N, bool CanRef=canref<T>::value>
class array;
// class for all types
template <typename T, int N>
class array <T,N,true>
{
struct Bytes
{
uint8_t bytes[sizeof(T)];
};
struct TStruct
{
T t;
TStruct(T t):t(t){}
};
Bytes elements[N];
int count;
void copy_ctor (int index, const T& t)
{
new (&((*this)[index])) T(t);
}
void copy (int index, const T& t)
{
(*this)[index] = t;
}
void dtor (int index)
{
(*this)[index].~T();
}
public:
array () : count(0) {}
~array ()
{
resize(0);
}
T& operator [] (int index)
{
assert (index>=0 && index<count);
return ((TStruct*)(&elements[index]))->t;
}
const T& operator [] (int index) const
{
assert (index>=0 && index<count);
return ((TStruct*)(&elements[index]))->t;
}
template <int M>
array (const array<T,M> &a)
{
assert(a.count<=N);
count = a.count;
for (int i=0; i<count; ++i)
copyctor(i, a[i]);
}
template <int M>
array& operator = (const array<T,M> &a)
{
if (this != &a)
{
if (count>a.count)
{
for (int i=0; i<a.count; ++i) copy(i, a[i]);
for (int i=a.count; i<count; ++i) dtor(i);
count = a.count;
} else
{
assert(a.count<=N);
int ocount = count;
count = a.count;
for (int i=0; i<ocount; ++i) copy(i, a[i]);
for (int i=ocount; i<count; ++i) copy_ctor(i, a[i]);
}
}
}
int size()
{
return count;
}
Скоро даже сратору станет очевидно откуда это.
+15
struct Point3D {
float x,y,z;
float& operator [] (int i) {
switch (i) {
case 0: return x;
case 1: return y;
case 2: return z;
default: assert(false);
}
}
};
Писал Жабапоглащенный.
+16
// https://github.com/mono/moon/blob/master/src/list.h#L87
class Queue {
protected:
MoonMutex lock;
List *list;
public:
Queue ();
~Queue ();
// convenience properties
bool IsEmpty ();
int Length ();
// convenience methods
void Clear (bool freeNodes);
void Push (List::Node *node);
List::Node *Pop ();
void Lock ();
void Unlock ();
// accessing the internal linked list directly requires manual Locking/Unlocking.
List *LinkedList ();
// copies the queue and empties the original
void MoveTo (Queue &queue);
};
// https://github.com/mono/moon/blob/master/src/list.cpp#L391
Queue::Queue ()
: lock (true)
{
list = new List ();
}
int
Queue::Length ()
{
int length;
Lock ();
length = list->Length ();
Unlock ();
return length;
}
void
Queue::MoveTo (Queue &queue)
{
List::Node *node;
while ((node = list->First ())) {
list->Unlink (node);
queue.Push (node);
}
}
Во имя луны!
+27
int enumDevices(DevInfo* &lst) {
int count = 0;
DevInfo* tmp = NULL;
Device device;
for (int i = 0; i < MAXDEVICES; i++)
if (device = OpenDevice(i)) {
count++;
realloc(tmp, sizeof(DevInfo)*count);
ReadInfo(device, &tmp[count-1]
}
if (count == 0) return 0;
lst = new DevInfo[count];
for (int i = 0; i < count; i++)
lst[i] = tmp[i];
free(tmp);
return count;
}
//................
DevInfo* list;
int devcount = enumDevices(list);
/* работаем со списком */
delete[] list;
Самому стыдно.
+34
class cxx_query {
elements operator()(const std::string &css_query);
void operator()(std::function<void()> callback);
http_request get(const std::string &url);
// ...
} $;
#define function []
$(function() {
$.get(some_url, function(const std::string &data) {
$("#result").html(data);
});
});
+17
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <iostream>
#define GEN_MACRO_0(X, Y) \
((X, Y)) GEN_MACRO_1
#define GEN_MACRO_1(X, Y) \
((X, Y)) GEN_MACRO_0
#define GEN_MACRO_0_END
#define GEN_MACRO_1_END
#define SHOW(name,val) \
std::cout << name << " : " << val ;
#define SHOW_TUPLE(r,_,tupple) \
SHOW( "1st",BOOST_PP_TUPLE_ELEM(2,0,tupple)) \
SHOW("\t2nd",BOOST_PP_TUPLE_ELEM(2,1,tupple)) \
std::cout << std::endl;
#define OUTPUT (ADD_PAREN_1 INPUT,_END)
#define SHOW_NODES(seq) \
BOOST_PP_SEQ_FOR_EACH(SHOW_TUPLE,_, \
BOOST_PP_CAT(GEN_MACRO_0 seq,_END) )
int main() {
SHOW_NODES(
("cock","unskill")
("rock","hard")
("price","over 100500")
)
}
Годнокодец из boost::fusion.
http://coliru.stacked-crooked.com/a/c516a67930a9c1a8
+18
#include <iostream>
#define PRINT(val) std::cout << #val \
<< " value: " << val \
<< " address: " << &val << std::endl;
int& constRef(){
int var = 10;
PRINT(var)
return var;
}
int main() {
const int a = 'a', b = 'bcde';
std::cout << a << " " << b << std::endl;
const int& ref = constRef();
PRINT(ref)
}
Малоизвестный синтаксис плюсов.
1. Инициализация целочисленного значения из строки (используется в строках-классах времени компиляции).
2. Константная ссылка на стековый объект (используется для создания DSL, в т.ч. boost::spirit).
P.S.: Более полный вариант со строками лежит на форуме.
+23
//VS 2010 C++
#include <Windows.h>
#include <time.h>
#include <queue>
#pragma comment(lib, "winmm.lib")
char shapeForms[7][4][5][6] = {{{{0,0,0,0,0},{0,0,1,0,0},{0,0,1,0,0},{0,0,1,0,0},{0,0,1,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,0},{0,1,1,1,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,1,0,0},{0,0,1,0,0},{0,0,1,1,0}}},{{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,0,1,1},{0,0,1,1,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,1,0,0},{0,0,1,1,0},{0,0,0,1,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,0,1,1},{0,0,1,1,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,1,0,0},{0,0,1,1,0},{0,0,0,1,0}}},{{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,1,1,1},{0,0,0,0,1}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,1,1,0},{0,0,1,0,0},{0,0,1,0,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,1,0,0,0},{0,1,1,1,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,1,0},{0,0,0,1,0},{0,0,1,1,0}}}}, field[32][28] = {0}, shape[5], shape_r[5], modifiers[4][3] = {{0,-1,0},{0,1,0},{1,0,0},{0,0,64}}, keys[4] = {'A', 'D', 'W', 'S'}, keyPressed = -1, lk = 0; //shape - 1: shape state; 2: shape type; 3: y; 4: x;
std::queue<std::pair<COORD, std::pair<char, char>>> paste;
COORD t;
unsigned int Score(0);
void draw(COORD cd, char c) {if((cd.Y = cd.Y - 4)||true) if(cd.Y >= 0) {SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cd);
printf("%c", c);}}
bool next_frame(bool mode, bool isShapeFell) {for(char y(0); y != 5; ++y) {for(char x(0); x != 6; ++x) {t.X = shape[4]+x; t.Y = shape[3]+y;
if(shapeForms[shape[2]][shape[1]][y][x] == 1) {if(field[t.Y][t.X] == 0) paste.push(std::make_pair(t, std::make_pair(-37, 1)));
if(field[t.Y][t.X] == 2 || field[t.Y][t.X] == 3) isShapeFell = true;}else if(field[t.Y][t.X] == 1) paste.push(std::make_pair(t, std::make_pair(32, 0)));}}
if(isShapeFell) {while(paste.size()) paste.pop();
if(mode) for(char i(0); i != 31; ++i) for(char j(0); j != 25; ++j) if(field[i][j] == 1) field[i][j] = 3;
return false;}else {for(paste; paste.size() != 0; paste.pop()) {draw(paste.front().first, paste.front().second.first);
field[paste.front().first.Y][paste.front().first.X] = paste.front().second.second;}}
return true;}
bool clearFullLines() {for(char isLineExist(1); isLineExist == 1;) {isLineExist = 0;
for(char j(0), up(0), down(0), cnt(0); j != 31; (++j) && (cnt = 0)) {for(char i(3); i != 25; ++i) if(field[j][i] == 3) if(j < 5) return false; else cnt++;
if(cnt == 22) {if(isLineExist == 0 && (isLineExist = 1) && (down = j)) up = j;
else down = j;}else if(isLineExist == 1 && (Score = Score + down-up+1)) {for(char q = down, tmp(0); q >= char(4); (--q)) for(char p(3); p != 25; (++p) && (tmp = 0)) {for(t.X = p, t.Y = q; tmp == 0; tmp = 1);
field[q][p] = 0; draw(t, 32);
if(field[up+q-down-1][p] == 3) draw(t, -37);
t.Y = up+q-down-1;
field[q][p] = field[up+q-down-1][p];
field[up+q-down-1][p] = 0;}
goto next_search;}}
next_search:;}
return true;}
int main() {timeBeginPeriod(2);
system("mode con cols=42 lines=28");
srand(clock()+time(NULL));
memset(field, 2, sizeof(field));
for(char i(0); i != 28; ++i) for(char j(0), q(0); j != 32; ++j && (q = 0)) for(t.X = i, t.Y = j; q == 0; q = 1) draw(t, -80);
for(char i(3); i != 25; ++i) for(char j(0), q(0); j != 30; ++j && (q = 0)) for(t.X = i, t.Y = j; q == 0; (q = 1) && (field[j][i] = 0)) draw(t, 32);
for(int tm = 100;true;) {next_turn: if(!clearFullLines() && printf("You fail!")) {system("pause");
return 0;}
for(t.X = 30, t.Y = 5; false;);
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), t);
printf("Score: %i ", Score);
shape[1] = rand()*4/(RAND_MAX+1); shape[2] = rand()*7/(RAND_MAX+1); shape[4] = rand()*20/(RAND_MAX+1)+3;
for(shape[3] = 0; true; shape[3]++) {for(char h(0); h != 5; ++h) {Sleep(tm); tm = 70;
for(char i(0); i != 4 && keyPressed == -1; ++i) if(GetKeyState(keys[i]) < 0) keyPressed = i;
if(keyPressed != -1 && !(lk == keyPressed && lk == 2)) {for(char j(0); j != 5; ++j) shape_r[j] = shape[j];
shape[4] += modifiers[keyPressed][1]; shape[1] = (shape[1] + modifiers[keyPressed][0])%4;
tm -= modifiers[keyPressed][2];
lk = keyPressed;
keyPressed = -1;
if(!next_frame(false, false)) {for(char j(0); j != 5; ++j) shape[j] = shape_r[j];
if(!next_frame(true, false)) goto next_turn;}}else {if(!next_frame(true, false)) goto next_turn;
if(keyPressed == -1) lk = -1;
if(lk != 2) lk = 0;else keyPressed = -1;}}}}}
Была задача за минимальное кол-во строк реализовать простой тетрис. Особого внимания заслуживает 6 строчка кода. Всё очень плохо?
Управление WSAD.