Simple way to pass temporary struct by value in C++?

Matthew picture Matthew · Feb 6, 2010 · Viewed 11.7k times · Source

Suppose I want to pass a temporary object into a function. Is there a way to do that in 1 line of code vs. 2, with a struct?


With a class, I can do:

class_func(TestClass(5, 7));

given:

class TestClass
{
private:
    int a;
    short b;

public:
    TestClass(int a_a, short a_b) : a(a_a), b(a_b)
    {
    }

    int A() const
    {
        return a;
    }

    short B() const
    {
        return b;
    }
};

void class_func(const TestClass & a_class)
{
    printf("%d %d\n", a_class.A(), a_class.B());
}

Now, how do I do that with a struct? The closest I've got is:

test_struct new_struct = { 5, 7 };
struct_func(new_struct);

given:

struct test_struct
{
    int a;
    short b;
};

void struct_func(const test_struct & a_struct)
{
    printf("%d %d\n", a_struct.a, a_struct.b);
}

The object is more simple, but I wonder if there's a way to do the struct member initialization right in line with the function call, without giving the struct a constructor. (I don't want a constructor. The whole reason I'm using a struct is to avoid the boilerplate get/set class conventions in this isolated case.)

Answer

Emile Cormier picture Emile Cormier · Feb 6, 2010

An alternative to providing a constructor in your struct, would be to provide a make_xxx free function:

struct Point {int x; int y;};

Point makePoint(int x, int y) {Point p = {x, y}; return p;}

plot(makePoint(12, 34));

One reason why you might want to avoid constructors in structs is to allow brace-initialization in arrays of structs:

// Not allowed when constructor is defined
const Point points[] = {{12,34}, {23,45}, {34,56}};

vs

const Point points[] = {Point(12,34), Point(23,45), Point(34,56)};