Re: non-const reference to temporary (was: non-const copy ctor)

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

 



Hi Brian,

Brian Budge wrote:
> Hi Christian -
>
> It makes no sense to pass a temporary to a function which expects a
> reference.  The reference means that it has a place in memory
> somewhere, and that place in memory isn't generated for your
> temporary.

Well, this is confusing. From my understanding also a temporary object has a 
place in memory somewhere. My guess is that this space is on the stack, but 
that I'm not sure of--and, it's not important.

Let's look at another example in which I call a non-const method on a temprary 
object, which--to the contrary--works fine.

class C
{
public:
	void method() {} // not const
};

int main()
{
	C().method(); // why does that work then?
	return 0;
}

So, altering a temporary makes sense to the compiler this time? Strange.

>
> Also, usually you pass things by reference when you want to alter the
> original object.  What possible reason could you have for passing a
> temporary by reference?  Note that it is possible to pass the
> temporary by const reference, since it is "guaranteed" that you cannot
> change the const references values.

In this case I definitely want to alter the temporary object. What I'm trying 
to do is passing some kind of "responsibility". The concept is much like 
std::auto_ptr's concept of passing ownership. The responsibility is passed to 
the next instance on copy or assignment. That means I must take the 
responsibility from the source of the copy or assignment operation. Thus I 
cannot use a const reference in both, the copy constructor and the assignment 
operator.

The other thing is that I want to use as little const in my programms as 
possible. But this issue forces me to use it.

>
> I haven't used auto_ptr much, but it seems like a bad idea to make a
> temporary out of one of those too.
>
> The obvious workaround to your problem is to change
> foo(C());
>
> to
>
> C bar;
> foo(bar);

Oh yes. This really is obvious. Although in the cases where I want to use it, 
it is quite inconvenient.

Thanks,
  Christian

> [...]

[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