This is the mail archive of the cygwin-apps@cygwin.com mailing list for the Cygwin project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: [setup] Why does PackageSpecification have a private copy-constructor? (Robert?)


> I can't see why setup's PackageSpecification class has a private
> copy-constructor.
> Am I missing something?
> 
> The reason why I am suddenly interested is that the C++ standard says that
> this:
> 
> foo(SomeClass())
> 
> requires SomeClass's copy-constructor to be accessible (bizarre, no?) and
> g++ 3.4 has decided to enforce this. So, unless I can make the
> copy-constructor public (which I don't want to do if doing so risks other
> problems), I need to rewrite all code like:

Actually, this makes perfect sense.  When you do SomeClass(), without
using the new operator, you are telling the compiler to create this
instance on the stack, and then when you do foo(SomeClass()) you are
telling the compiler to pass this class by value.  To do so requires
creating a copy.

If foo() only needs temporary access to the instance of SomeClass(),
then you can change foo() to accept a reference operator.  Care must
be taken not to store the object passed by reference, because it will
obsolete as soon as the constuctor returns.

On the otherhand, if you want to have perminent access to SomeClass(),
then use the new operator, and change foo to accept a pointer.

foo(new SomeClass());

However, I would discourage this solution, because it is likely to end
with a memory leak, or an object that is deleted twice...

> do_something(PackageSpecification(somename))
> 
> to:
> 
> PackageSpecification tmppkgspec(somename);
> do_something(tmppkgspec);

This would not solve your problem.  If you are trying to pass the
class by value, a copy will still need to be made.

BTW.  I would discourage all of these examples.  Why?  Because I
firmly believe in using a smart pointer class, and making the actual
constructors private.  i.e.

class Something
{
  private Something() {}
  public static SmartPointer<Something> create()
  { return new Something(); }
...
}

If that was followed for all the code, then your original example would have
been written:

foo.create(Something.create());

Assuming the SmartPointer template is correctly written, this
eliminates the possibility of memory leaks from unreferenced objects.

                               Bill


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]