Please look this code. C++
with Clang
's block
feature.
Can this code avoid copying? Please let me know your opinion.
This is just a practice of avoiding heap.
class Element
{
public:
int value[1024]; // Here is a large entity.
Element()
{
}
};
class World
{
public:
Element a;
Element b;
inline World(Element& newA, Element& newB)
{
a = newA; // Source of newA is s开发者_如何学JAVAtored in somewhere, this copies whole Element during assignment.
b = newB;
}
inline World(void(^init)(Element& a, Element& b))
{
init(a, b); // Assignment is done without copying whole Element.
}
};
The only way to totally avoid copying is to use a pointer or reference. For example:
class World
{
public:
Element& a;
Element& b;
inline World(Element& newA, Element& newB) : a(newA), b(newB)
{
}
...
};
As with any other reference or pointer, this approach requires that the variables passed not go out of scope.
精彩评论