Babra Cunningham Babra Cunningham - 1 month ago 4
C++ Question

Passing objects efficiently?

For most of my programs I've been passing objects by reference:

MyClass
{
public:
auto DoStuff()->void
{
//Doing stuff...
}
};

MySubClass
{
public:
auto CallFunction(MyClass &MCO)->void
{
MCO.DoStuff();
}
};

int main()
{
MyClass MCO;
MySubClass MSCO;
MSCO.CallFunction(MCO);
}


For an object that I don't need to edit (just call its functions), is passing by reference the most memory efficient solution?

Or, alternatively using a raw pointer?

MyClass
{
public:
auto DoStuff()->void
{
//Doing stuff...
}
};

MySubClass
{
public:
auto CallFunction(MyClass *MCO)->void
{
MCO->DoStuff();
}
};

int main()
{
MyClass *MCO;
MySubClass MSCO;
MSCO.CallFunction(MCO);
delete MCO;
}

Answer

If you don't need to modify the object, then pass it by const reference.

void CallFunction(const MyClass &MCO)
{
  MCO.DoStuff();
}

You should usually choose a passing model based on semantics, not optimization. Pass objects by ref or const ref. Pass data by value, and avoid pointers unless your programming model requires it. You can almost never do better than the compiler for micro-optimizations.

Once you have profiled your program and identified the bottleneck, you can usually get more bang for your buck by modifying the algorithm or the way data is stored.