Re: Guaranteed copy elision

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Am Freitag, dem 18.11.2022 um 16:05 +0100 schrieb Stefan Ring via Gcc-
help:
> On Tue, Nov 15, 2022 at 6:48 AM Yubin Ruan via Gcc-help
> <gcc-help@xxxxxxxxxxx> wrote:
> > 
> > To be sure that a object would not be copied, we usually write
> > something
> > like
> > 
> >          SomeBigObject obj;
> >          func(&obj);
> > 
> > while in most of the cases a one-liner like
> > 
> >          SomeBigObject obj = func();
> > 
> > would suffice.
> > 
> > Is there any language facility to help us guarantee that at compile
> > time
> > (such as some kind of static_assert() ) so that we can be confident
> > writing
> > those one-liner ?
> 
> Interesting question, but unfortunately I do not have a good answer!
> I
> can only bump the thread. ;)

With c++ language features this may is a solution:


#include <iostream>
#include <vector>

class DoNotCopy
{

  std::vector<std::string> myData;
  
public:
  DoNotCopy( const DoNotCopy & other ) = delete;
  DoNotCopy & operator=( const DoNotCopy & other ) = delete;

  // valid move semantic
  // data within the vector will be moved, not copied
  DoNotCopy( const DoNotCopy && other )
    : myData( other.myData )
  {}

  DoNotCopy()
    : myData()
  {
  }
  
};


DoNotCopy func()
{
  DoNotCopy dnc;

  return dnc;
}

int main()
{
  DoNotCopy dnc = func(); // works

  DoNotCopy dnc2 = dnc; // error

  DoNotCopy dnc3;
  dnc3 = dnc; // error
}





[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux