I have a class that needs to know about some large data structure. Therefore, I created a constructor that accepts a reference to that large data structure and uses it to initialize a member variable like so:
class Foo {
public:
BigStruct m_bigstruct;
Foo(BigStruct &inBigStruct) : m_bigstruct(inBigStruct) {}
};
This appears to make a copy of inBigStruct, but I don't want to waste those resources because BigStructs are huge. Is there a more standard way of making the contents of inBigStruct available to Foo without copying it? I know I can do this:
class Foo {
public:
BigStruct* m_bigstruct;
Foo(BigStruct* inBigStruct) : m_bigstruct(inBigStruct) {}
};
Is this the usual way to make inBigStruct available to Foo without copying? If not, what is?
The C++2011 approach is to move objects, e.g.:
Foo::Foo(BigStruct const& argument): m_bigstruct(argument) {} // copies
Foo::Foo(BigStruct&& argument): m_bigstruct(std::move(argument)) {} // moves
Of course, this assumes that BigStruct has a suitable move constructor. Depending on whether a temporary (or something looking like a temporary by way of std::move()) or a lvalue is passed, the object will get moved or copied: If you have another reference to an object, you generally don't want to steal the object but copy it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With