避免在 C++ 初始化期间复制变量带块
请看一下这段代码。 C++
与 Clang
的 block
功能。 这段代码可以避免复制吗?请让我知道您的意见。 这只是避免堆的一种做法。
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 stored 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.
}
};
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 stored 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:
As with any other reference or pointer, this approach requires that the variables passed not go out of scope.