Re: returning lvalue in C vs C++



Ben C wrote:

On 2006-03-29, Ben C <spamspam@xxxxxxxxx> wrote:
On 2006-03-29, Phlip <phlip2005@xxxxxxxxx> wrote:
Ben C wrote:

struct thing
{
int x;
};

struct thing f(void)
{
struct thing ret = {100};
return ret;
}

int g(void)
{
return 10;
}

int main(void)
{
#if 0
g() = 4; /* "invalid lvalue" in C and C++ */
#endif
f().x = 200; /* "invalid lvalue" in C, but not in C++ apparently
*/

Consider the general scheme of C++, and specifically its overloaded
operators.

x.operator=() (figuratively) could have a side-effect that your code
depends on. So regardless where 'thing' appears, thing.x is accessible
as an lvalue.

It would be thing.operator=() but I see the point.

Sorry, no it wouldn't, you were right. It's x's operator= we'd be
calling.

But x is an int, so if f().x = 200 works on that basis, why not g() = 4?

Yup: why not? I don't know. But for classes, it sure works:


#include <iostream>

struct dummy {

dummy & operator= ( dummy const & other ) {
std::cout << "hello world!\n";
return ( *this );
}

};

dummy g ( void ) {
dummy tmp;
return ( tmp );
}

int main ( void ) {
g() = g();
}


Best

Kai-Uwe Bux
.



Relevant Pages

  • Re: Linux 2.6.29.4
    ... static int is_efer_nx ... if (ret) ... struct ftdi_private { ... the specific security attributes of the socket ...
    (Linux-Kernel)
  • Re: [PATCH 2/2] Futex non-page-pinning fix
    ... futex has been swapped out, press Enter and it will wake the futexes. ... D: clarify comment about hashing: we hash address of struct page, ... static inline struct list_head *hash_futex(struct page *page, int offset) ... ret = -EWOULDBLOCK; ...
    (Linux-Kernel)
  • Re: Linux 2.6.22.2
    ... struct cpufreq_freqs freqs; ... return ret; ... int tcode, int destination, int source, ... int err; ...
    (Linux-Kernel)
  • Re: [RFC PATCHES] Re: Is configfs the right solution for configuration based fs?
    ... static struct class *dev_class; ... int nr_pins; ... static int io_release ... int i, ret = 0; ...
    (Linux-Kernel)
  • Re: Linux 2.6.27.8
    ... struct pt_regs *regs); ... static int printbinary ... void show_regs ...
    (Linux-Kernel)