开发者

Avoiding copying variables during initialization in C++ with block

开发者 https://www.devze.com 2023-02-11 14:57 出处:网络
Please look this code. C++ with Clang\'s block feature. Can this code avoid copying? Please let me know your opinion.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消