简体   繁体   中英

Getting around private copy constructor/copy assignment C++

I have an object which upon initialization is passed a large data structure:

class foo {
public: 
   foo(const BigData& data);

   command();

}

BigData 's copy constructor and copy assignment operator are private, and rightly so.

However, I need to change class foo so that command() has access to BigData . Passing command(const BigData& data) is prohibitively difficult given the structure of the program, so I want to do the following:

class foo {
public: 
   foo(const BigData& data);

   command();
private:
   BigData m_data;
}

But how can I initialize m_data without the copy constructor or copy assignment? I also do not like the idea of std::move on the data , because it needs to remain a valid object in the context of the caller.

Note : I have declared the member a reference (ie const BigData& m_data ) but this does not compile under icpc:

error: foo provides no initializer for reference member "m_data"

I have used foo(const BigData& data) : m_data(data) as well as foo(const BigData& data) { m_data = data; } foo(const BigData& data) { m_data = data; } .

How about storing a reference?

class foo
{
public: 
   foo(const BigData& data) : m_data(data) {}
   command();
private:
   const BigData & m_data;
};

If BigData has no copy constructor and no assignment operator, the authors do not want you to make copies of it. However, you can make const references to it yourself, like this:

class foo {
public: 
   foo(const BigData& data) : m_data(data) {}
   command();
private:
   const BigData &m_data;
};

Now your command() member function has access to BigData that has been passed to foo 's constructor.

One important point to keep in mind is that the lifetime of the BigData object is not tied to the lifetime of the foo object. You need to make sure that when foo::command() runs, the same BigData that has been passed to foo 's constructor is around. Otherwise, your program would have undefined behavior due to a dangling reference.

Another alternative is to make your own class similar to BigData , and make a copy from their class into yours. This may be prohibitive in terms of the programming effort, though.

class foo {
public: 
 foo(const BigData& data);

 command();
private:
 const BigData& m_data;
}

// constructor
foo::foo(const BigData& data)
: m_data( data ) 
{
 // usual stuff
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM