Search code examples
c++gccc++11cocos2d-xmarmalade

Variadic function and C++11, passing objects as parameters


I have such trouble, when we start using new C++11, compiler (GCC) says that this code is wrong, but it works fine at older version :(

std::list<CCPoint> createPointArray(int count, ...) {
    CCPoint val;
    std::list<CCPoint*> arr;

    va_list vl;
    va_start(vl,count);
    for (int i=0;i<count;i++)
    {
        val = va_arg(vl,CCPoint*);
        arr.push_back(*val);
    }
    va_end(vl);

    return arr;
}

And this is the way, i'm using it:

createPointArray(3, &CCPoint(1.3,2.7), &CCPoint(1.5,1.75), &CCPoint(1.9,1.3))

Compiler tell me next:

Error   486 error : taking address of temporary [-fpermissive] (col 57) 

Why is it something wrong with &CCPoint(1.3,2.7) ? How can i change this code to be workable with C++11 and older version?

P.S.: I'am using Marmalade 7.3.1, Visual Studio 2010, cocos2d-x v2.2.1


Solution

  • Taking the address of a prvalue temporary is illegal (and was indeed illegal in C++03 as well).

    You can use a cast to change the value category to lvalue:

    createPointArray(3,
      &static_cast<CCPoint const&>(CCPoint(1.3,2.7)),
      &static_cast<CCPoint const&>(CCPoint(1.5,1.75)),
      &static_cast<CCPoint const&>(CCPoint(1.9,1.3)));
    

    This will work in both C++03 and C++11, as the temporary objects are not destroyed until the end of the enclosing full-expression.

    Because you are passing the objects by pointer to const, you should extract them using va_arg(vl, CCPoint const*).