added defer test files - currently called raii tests TODO: rename?
This commit is contained in:
parent
61781e1743
commit
544196376c
24
raii_test.c
Normal file
24
raii_test.c
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include "defer.h"
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
int n;
|
||||||
|
printf("Allocate this much bytes: "); scanf("%d", &n);
|
||||||
|
void *ram = malloc(n);
|
||||||
|
defer {
|
||||||
|
free(ram);
|
||||||
|
printf("%d bytes freed\n", n);
|
||||||
|
};
|
||||||
|
|
||||||
|
unsigned char cs = 0;
|
||||||
|
unsigned char *bytes = ram;
|
||||||
|
for(int i = 0; i < n; ++i) {
|
||||||
|
cs += bytes[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Checksum of found bytes: %d\n", cs);
|
||||||
|
|
||||||
|
// exit(0); // This does not release resources!
|
||||||
|
return 0;
|
||||||
|
}
|
35
raii_test.cpp
Normal file
35
raii_test.cpp
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
#include <cstdio>
|
||||||
|
#include <cstdlib>
|
||||||
|
#include "defer.h"
|
||||||
|
|
||||||
|
struct Test {
|
||||||
|
inline Test() {
|
||||||
|
puts("Constructor of test");
|
||||||
|
}
|
||||||
|
inline ~Test() {
|
||||||
|
puts("Destructor of test");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
int n;
|
||||||
|
printf("Allocate this much bytes: "); scanf("%d", &n);
|
||||||
|
void *ram = malloc(n);
|
||||||
|
defer {
|
||||||
|
free(ram);
|
||||||
|
printf("%d bytes freed\n", n);
|
||||||
|
};
|
||||||
|
|
||||||
|
unsigned char cs = 0;
|
||||||
|
unsigned char *bytes = (unsigned char*) ram;
|
||||||
|
for(int i = 0; i < n; ++i) {
|
||||||
|
cs += bytes[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Checksum of found bytes: %d\n", cs);
|
||||||
|
|
||||||
|
Test t;
|
||||||
|
|
||||||
|
// exit(0); // This does not release resources! But neither calls destructors properly anyways.
|
||||||
|
return 0;
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user