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

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

 



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.

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.

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);

  Brian

On 4/9/06, Christian Fröbel <cfroebel@xxxxxx> wrote:
> Hi there,
>
> Christian Fröbel wrote:
> > I'm having problems with a non-const copy constructor.
>
> I'd like to correct myself. This problem dosn't seem to be related to the copy
> constructor at all. The problem is that I'm not allowed to make a non-const
> reference to a temporary object. For example code like this doesn't compile:
>
> class C {};
>
> void foo (C& c) {}
>
> int main (void)
> {
>         foo (C()); // <== problem
>         return 0;
> }
>
> The error message I get here is:
> conversion.cpp:48: error: invalid initialization of non-const reference of
> type 'C&' from a temporary of type 'C'
> conversion.cpp:42: error: in passing argument 1 of 'void foo(C&)'
>
> I read §5.5 in Stroustrup's C++ Programming Language regadring that topic but
> couldn't find anything of real use there. I understand that it generally
> doesn't make sense to alter a temporary object. But why forbid it? And
> sometimes it does make sense (e. g. std::auto_ptr).
>
> Maybe someone of you can shed some light on this topic.
>
> Also, I'd like to know if there's a general way to work around this problem.
>
> 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