tags:

views:

26

answers:

1

I'm got a function in C++ that wraps an output stream constructor so it can pass in a pointer to a parent class that it's running in, ala:

pf_istream PF_Plugin::pf_open_in() {
    return     pf_istream(this);
}

When I do it that way, however, I get something like this:

pf_plugin.cc:103: error: no matching function for call to ‘pf_istream::pf_istream(pf_istream)’

pf_istream.hh:36: note: candidates are: pf_istream::pf_istream(const PF_Plugin*)

pf_istream.hh:29: note: pf_istream::pf_istream(pf_istream&)

I've got a copy constructor and assignment operator defined (as can be seen above), and if I write the function like so:

pf_istream PF_Plugin::pf_open_in() {
   pf_istream to_ret(this); 
   return     to_ret;
}

It works just fine. I get similar errors if I try to assign a pf_istream instance directly from a call to the function, eg:

pf_istream inFile = pf_open_in();

What else do I need to add to make this work?

+2  A: 
> pf_istream::pf_istream(pf_istream&)

This is your problem. It's not properly finding your copy constructor, because it's passing a temporary. Your copy constructor should take a const&, like so:

pf_istream::pf_istream(const pf_istream&) { ... }
Stephen
Hmmm my problem is that the copy semantics for these pf_istream objects is such that copying one passes ownership of the underlying output stream to the new element, so I had to leave my copy constructor non-const. How can I deal with that?
gct
Hmm, ideally you solve it with a different design ;) You're hitting the same problem that `std::auto_ptr` did, and auto_ptr is a pretty controversial topic :) See here: http://www.aristeia.com/BookErrata/auto_ptr-update.html
Stephen
Sweet I'll check it out, thanks!
gct
If you want the semantics that `std::auto_ptr` has, your best bet may be to actually wrap the underlying output stream in a `std::auto_ptr` and let it deal with the stupid copy constructor tricks. Implementing `std::auto_ptr`'s copy construction semantics requires proxy classes, which are a pretty huge pain to do by hand (as I can attest from having done so, foolishly...)
Tyler McHenry
Trying that now, made my copy constructor const, but then I try to assign the other objects reader_ object to the new object's (wrapped in an auto_ptr) and it complains that doing that discards the const qualifier.
gct