Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize member variable without making a new copy

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?

like image 242
Fadecomic Avatar asked Feb 11 '26 07:02

Fadecomic


1 Answers

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.

like image 194
Dietmar Kühl Avatar answered Feb 13 '26 23:02

Dietmar Kühl