how to use boost context v2 - c++

boost::context library was updated to version v2 and the changes broke all my previous code relying on boost::jump_fcontext()
Also the old boost::jump_fcontext() is no longer available in the new API. The new boost::context v2 changed so much that I can't understand it. The boost provided examples don't help me.
Here is pseudo code of the program structure I'm trying to archive with the new execute_context:
struct myctx
{
int var;
boost::context::execution_context fctx;
myctx()
: var(0), fctx("how to ctor")
{}
static void ctx_func(ctx_data * ptr) {
while(ptr->var++ < 1000) {
ptr->fctx("how to jump into main() myctx ??")
}
}
};
int main()
{
myctx mctx;
while(1)
mctx.fctx("how to jump into ctx_func() ??");
return 0;
}
How do I replace those strings with real C++?? I don't understand what are the possible arguments to boost::context::execution_context
My usage of the boost::context was that I saved the current context into myctx and switched into multiple other myctx's in unordered fasion. With boost::jump_fcontext this was fairly clearly done.

why dont't you initialize 'fctx'? Even it will not compile because of ctx_data() - ctor (not same name as myctx) ...
maybe you meant something like:
struct myctx
{
int var;
execution_context< myctx * > fctx;
myctx()
: var(0), fctx( myctx::ctx_func)
{}
static execution_context< myctx * > ctx_func(execution_context< myctx * > mctx, ctx_data * ptr) {
while(ptr->var++ < 1000) {
// jump into main()
std::tie(mctx, ptr) = mctx( ptr);
}
return std::move( mctx);
}
};
I've no idea for what you want to pass myctx pointer

Related

implement field access with functions

I want to replace object field access with functions to make it easy for a program analyzer I am building. Is there a simple way to do this? I came up with the following hack with my own set and get functions:
struct Foo
{
int f1;
int f2;
};
// convert v = t->f1 to v = (int)get(t, "f1")
void * get (struct Foo * t, char * name)
{
if (!strcmp(name, "f1")) return t->f1;
else if (!strcmp(name, "f2")) return t->f2;
else assert(0);
}
// convert t->f1 = v; to set(t, "f1", v)
void set (struct Foo * t, char * name, void * v)
{
if (!strcmp(name, "f1")) t->f1 = (int)v;
else if (!strcmp(name, "f2")) t->f2 = (int)v;
else assert(0);
}
Edit: C or C++ hacks would work.
So, as far as I understand you are looking for some reflection library for c/c++?
In this case, there is quite a big difference between c and c++.
For C++, you can use boost describe.
For C there are several libraries, bottom line all solution come down to defining your structs with macros, something like:
MY_STRUCT(s,
MY_MEMBER(int, y),
MY_MEMBER(float, z))
You can see a few examples here.

Position in Member Declaration Breaks Code?

A while ago I asked a question on why the following code did not work:
std::vector<std::vector<std::vector<Tile_Base*>>> map_tile; // This is located in Map object. See below.
int t_x, t_y;
t_x = t_y = 200;
map_tiles.begin(); // clear(), resize() and every other function still causes problems
The thing is, is that it should have worked, yet Visual Studios 2012 throws an exception when the resize function is called. The exception pointed to this piece of code:
*_Pnext != 0; *_Pnext = (*_Pnext)->_Mynextiter)
located in xutility. It said that there was an violating on access to reading the memory. I thought maybe somehow I lost access to the member along the way? (Using VS' watch I saw the memory was not corrupted)
So, I fiddled around with the code and tried to figure out what could possibly be going wrong, and after awhile I moved the map_tiles object down to the bottom of the list, and it worked:
// WORKS
class Map {
std::vector<Tile_Base*> spawn_tiles;
// map tile specific
bool Is_Valid(int,int);
std::string name;
std::vector<std::vector<std::vector<Tile_Base*> > > map_tiles;
public:
// ...
}
// DOESN'T WORK
class Map {
std::vector<std::vector<std::vector<Tile_Base*> > > map_tiles;
std::vector<Tile_Base*> spawn_tiles;
// map tile specific
bool Is_Valid(int,int);
std::string name;
public:
// ...
}
Any help pointing out what went wrong? I can't come up with any reasonable explanation.
A vector<T> comprises two discrete sets of data: the internal state and the array of Ts. The internal state - capacity, size, pointer - is separate from the array. The issue you're describing is normally caused by something overwriting the vector object, i.e the internal state. To track this down easily you could use a container class:
typedef std::vector<std::vector<std::vector<Tile_Base*> > > maptiles_t;
class CMapTiles
{
unsigned int m_guard;
maptiles_t m_tiles;
enum { Guard = 0xdeadbeef };
public:
CMapTiles() : m_guard(Guard), m_tiles() {}
~CMapTiles() { assert(m_guard == Guard); }
void Check()
{
#if defined(DEBUG)
if (m_guard != Guard)
DebugBreak();
#endif
}
void Resize(size_t x, size_t y)
{
Check();
auto init = std::vector<std::vector<Tile_Base*> >(y/32);
m_tiles.resize(m_x / 32, init);
Check();
}
const maptiles_t& tiles() const { Check(); return m_tiles; }
maptiles_t& tiles() { Check(); return m_tiles; }
};
And instead of using std::vector<...> map_tiles have CMapTiles map_tiles, and then when you want to get at the vector, map_tiles.tiles().
Hope this helps.

How to initialize a dynamic memory in a non-standard way in C++?

Say I have a class:
class A
{
private:
const int * const v;
public:
A();
}
I want v to be allocated in the initialization list, and I think I can define the following constructor:
A::A():v((int*)malloc(10*sizeof(int))){}
However, what about v has to be allocated in a non-standard way like the following:
cudaMalloc(&v,10*sizeof(int));
Note cudaMalloc is a CUDA API to allocate GPU memory.
(Ignoring the bigger-picture matters of overall design, exception safety etc. and focusing on the question in its most narrow scope)
Abandon the idea of doing in the initializer list and do it in the constructor body instead
A::A() : v(NULL)
{
cudaMalloc(&v, 10 * sizeof(int));
}
Or, alternatively, wrap the allocation function into your own function that returns the pointer
void *wrapped_cudaMalloc(size_t size)
{
void *m = NULL;
cudaMalloc(&m, size);
return m;
}
...
A::A() : v(wrapped_cudaMalloc(10 * sizeof(int)))
{}
Just for the sake of completeness, there's also an ugly convoluted way to do it in the initializer list without creating any wrappers by exploiting the properties of , operator
A::A() : v((cudaMalloc(&v, 10 * sizeof(int)), v))
{}
Note the additional pair of () around the comma-expression, which is needed to satisfy the initialization syntax (otherwise , will be treated as argument separator instead of comma operator).
In addition to AndreyT's excellent post (and his creative use of the comma operator), you could also wrap things up thusly:
class cudaMallocedInt
{
private:
int *v;
public:
cudaMallocedInt(int n)
{
cudaMalloc(&v, n * sizeof(int));
}
cudaMallocedInt(const cudaMallocedInt &o)
{
// Do whatever is appropriate here. Probably some sort of dance.
}
~cudaMallocedInt()
{
// Remember to cudaFree or whatever
}
operator int*()
{
return v;
}
};
class A
{
private:
cudaMallocedInt v;
public:
A()
: v(10)
{
}
...
};
Update: As Johnsyweb pointed out in comments, please be sure to adhere to the Rule of Three to make sure things don't go boom and you waste your weekends tracking down hard to debug errors instead of having fun!

Equivalent code generated in return value optimization in c++

I am not able to understand how is compiler able to optimize it under the covers. i.e, what is the equivalent code it generates?
There is an example of mentioned in http://en.wikipedia.org/wiki/Return_value_optimization which shows this code before optimization:
struct Data { char bytes[16]; };
Data * f(Data * __hiddenAddress)
{
Data result = {};
// copy result into hidden object
*__hiddenAddress = result;
return __hiddenAddress;
}
int main()
{
Data __hidden; // create hidden object
Data d = *f(&__hidden); // copy the result into d
}
It does not say the equivalent code ofter optimization
Ok, the page has proven to be less than clear, as I've misread it on my first scan (oops). The following is listed as before optimization:
struct Data { char bytes[16]; };
Data f()
{
Data result = {};
// generate result
return result;
}
int main()
{
Data d = f();
}
The code you listed was the non-optimzed pseudo version as a compiler might interpret that, complete with temporary and copy construction. What it shows, is how a compiler will translate into procedural code a function that returns a value (return value passing mechanism).
After that, the code after optimization is listed none-the-less:
struct Data { char bytes[16]; };
void f(Data * p)
{
// generate result directly in *p
}
int main()
{
Data d;
f(&d);
}
I.e.: the compiler is allowed to work on the destination of the return value directly, bypassing the construction/destruction/copy of a temporary instance within the function body.
struct Data { char bytes[16]; };
void f(Data * useThisInsteadOfReturning)
{
// update *useThisInsteadOfReturning directly
}
int main()
{
Data d;
f(&d); // use d in the function
}
The optimized code is shown below the one you mentioned. To quote from the wikipedia site:
struct Data { char bytes[16]; };
void f(Data * p)
{
// generate result directly in *p
}
int main()
{
Data d;
f(&d);
}
So the compiler can figure out that it has reserved memory to hold the return value from the function and it treats it as if a pointer to that memory had been passed as parameter and it writes directly into it instead of creating another temp object inside the function and then copying the memory around.

Handling Huge Multidimensional Arrays in C++

I'm designing a game in C++ similar to Minecraft that holds an enormous amount of terrain data in memory. In general, I want to store an array in memory that is [5][4][5][50][50][50]. This isn't bad since it amounts to about 100mb of virtual memory since my structure will only be about 8 bytes.
However, I'm having trouble figuring out the best way to handle this. I do want this to be in virtual memory, but obviously not on the stack. And I keep making the mistake some how of creating this array on the stack an causing a stack overflow. What I would like to do is below. This is just code that I threw together to give you an example of what I'm doing, I have code with correct syntax on my machine, I just didn't want to clutter the post.
typedef struct modelBlock
{
// Information about the blocks
} BLOCK;
typedef struct modelGrid
{
bool empty;
BLOCK blocksArray[50][50][50];
} GRID;
class Parent
{
Child* child;
Parent(void);
}
Parent::Parent()
{
Child c;
child = &c;
}
class Child
{
GRID grids[5][4][5];
}
However, every time I do this, I cause a stack overflow (appropriate web site choice right?). I played with using pointer based arrays, but I had a lot of trouble with data being lost outside of its scope.
If anyone could give me some insight on how to get my data to store on the heap instead of the stack, or if I should use some other way of creating my array, I'd really appreciate the help. I'd like to avoid using vectors because of overhead, though I'm not sure how substantial it is.
Use boost::multi_array
If you want to allocate something on the heap, use new.
#include <memory>
class Parent
{
std::auto_ptr<Child> child; // use auto_ptr for dynamically-allocated members
Parent(const Parent&); // You probably don't want to copy this giant thing
public:
Parent();
};
Parent::Parent()
: child(new Child) // initialize members with an initializer list
{
}
Also, avoid mixing C and C++ styles. There's no reason to do
typedef struct blah{ ... } BLAH;
in C++. A struct is just a class with all of the members public by default; just like a class, you can refer to the struct type's name without using the struct tag. There's also no need to specify void for a function that takes no parameters.
boost::multi_array (linked in PigBen's answer) is a good choice over raw arrays.
If you want the class created on the heap, create it with new:
Child * c = new Child;
and then of course delete it, or better still use a smart pointer.
In order to do exactly what you're trying to do you have to declare everything as pointers (and pointers to pointers to pointers to pointers) and then allocate each one individually.
Teh sux!
A better option is to simply allocate the ginormous block in one chunk and use multiple variable along with pointer arithmetic to arrive at the correct location.
Edit: Wasn't paying attention and didn't notice your constructor. That's not only not the way to get your Child allocated on the free-store, it's a great way to create situations eliciting undefined behavior. Your Child will be gone when the constructor is through and the pointer to it will then be invalid. I wonder if you shouldn't run through some basic tutorials before trying to write a game.
Here's something that works and can be built upon without the boost dependency. One downside is it removes use of [][][] style of referencing elements, but it's a small cost and can be added.
template<class T>
class Matrix {
unsigned char* _data;
const size_t _depth;
const size_t _cols;
const size_t _rows;
public:
Matrix(const size_t& depth, const size_t& rows, const size_t& cols):
_depth(depth),
_rows(rows),
_cols(cols) {
_data = new unsigned char [depth * rows * cols * sizeof(T)];
}
~Matrix() {
delete[] _data;
}
T& at(const size_t& depthIndex, const size_t& rowIndex, const size_t& colIndex) const {
return *reinterpret_cast<T*>(_data + ((((depthIndex * _cols + colIndex) * _rows) + rowIndex) * sizeof(T)));
}
const size_t& getDepth() const {
return _depth;
}
const size_t& getRows() const {
return _rows;
}
const size_t& getCols() const {
return _cols;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Matrix<int> block(50, 50, 50);
size_t d, r, c;
for (d = 0; d < block.getDepth(); d++) {
for (r = 0; r < block.getRows(); r++) {
for (c = 0; c < block.getCols(); c++) {
block.at(d, r, c) = d * 10000000 + r * 10000 + c;
}
}
}
for (d = 0; d < block.getDepth(); d++) {
for (r = 0; r < block.getRows(); r++) {
for (c = 0; c < block.getCols(); c++) {
assert(block.at(d, r, c) == d * 10000000 + r * 10000 + c);
}
}
}
return 0;
}
A smaller example (with changed names for all the structs, to make the general principle clearer). The 'Bloe' struct is the one you want to allocate on the heap, and this is accomplished using 'new'.
struct Bla {
int arr[4][4];
};
struct Bloe {
Bla bla[2][2];
};
int main()
{
Bloe* bloe = new Bloe();
bloe->bla[1][1].arr[1][1] = 1;
return 0;
}
I did this by putting all the data in a binary file. I calculated the offset of the data and used seek() and read() to get the data when needed. The open() call is very slow so you should leave the file open during the lifetime of the program.
Below is how I understood what you showed you were trying to do in your example. I tried to keep it straightforward. Each Array of [50][50][50] is allocated in one memory chunk on the heap, and only allocated when used. There is also an exemple of access code. No fancy boost or anything special, just basic C++.
#include <iostream>
class Block
{
public:
// Information about the blocks
int data;
};
class Grid
{
public:
bool empty;
Block (*blocks)[50][50];
Grid() : empty(true) {
}
void makeRoom(){
this->blocks = new Block[50][50][50];
this->empty = false;
}
~Grid(){
if (!this->empty){
delete [] this->blocks;
}
}
};
class Parent
{
public:
Grid (* child)[4][5];
Parent()
{
this->child = new Grid[5][4][5];
}
~Parent()
{
delete [] this->child;
}
};
main(){
Parent p;
p.child[0][0][0].makeRoom();
if (!p.child[0][0][0].empty){
Block (* grid)[50][50] = p.child[0][0][0].blocks;
grid[49][49][49].data = 17;
}
std::cout << "item = "
<< p.child[0][0][0].blocks[49][49][49].data
<< std::endl;
}
This could still be more simple and straightfoward and just use one bug array of [50][50][50][5][4][5] blocks in one memory chunk on the heap, but I'll let you figure out how if this is what you want.
Also, usind dynamic allocation in class Parent only has the sole purpose to use heap instaed of stack, but for such a small array (5*4*5 pointers), allocating it on stack should not be a problem, hence it could be written.
class Parent
{
public:
Grid child[5][4][5];
};
without changing anything in the way it is used.