Re: Assignment Operator Bug

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

 



This question is better suited to gcc-help@xxxxxxxxxxx.

On Thu, Jul 7, 2011 at 6:22 PM, Mactavish <mdtabishalam@xxxxxxxxx> wrote:
> I have compiled this code in MS Visual C++ Express 2008 and it works as it
> should

That's a bug in MSVC++, as the code is not valid C++.

> be but when i compile this code in Mingw as a part of GCC ver 4.4.1-2
> the input() function should return a temporary object to 'ob' object and
> invoke the assignment operator '=' but it doesn't and it shows me error :"no
> match for 'operator=' in 'ob=input()()'   "
>
>
> code:
> #include<iostream>
> #include<conio.h>
> #include<cstdio>
> #include<cstring>
>
> using namespace std;
>
> class sample{
>
>    char *s;
>    public:
>        sample(){s=new char('\0');}
>        sample(const sample &ob);
>        ~sample(){if(s) delete []s; cout<<"Freeing\n";}
>        void show(){cout<<s<<endl;}
>        void set(char *str);
>        sample operator=(sample &ob);

There's your problem: you're taking a non-const lvalue reference to ob....

> };
>
> sample::sample(const sample &ob)
> {
>    s=new char[strlen(ob.s)+1];
>    strcpy(s,ob.s);
> }
>
> void sample::set(char *str)
> {
>    s=new char[strlen(str)+1];
>    strcpy(s,str);
> }
>
> sample input()
> {
>    char instr[20];
>    sample str;
>
>    cout<<"Enter a string :";
>    cin>>instr;
>
>    str.set(instr);
>    return str;
>
> }
>
> sample sample::operator=(sample &ob)
> {
>    /* If the target memory is not large enough
>    then allocate new memory. */
> if(strlen(ob.s) > strlen(s))
>    {
>        delete []s;
>        s = new char[strlen(ob.s)+1];
>    }
>    strcpy(s, ob.s);
>    return *this;
> }
>
>
> int main()
> {
>    sample ob;
>
>    ob=input(); //showing errors

...and therefore cannot legally call operator= when its right hand
side is a temporary, as temporaries must not (according to C++) bind
to non-const lvalue references.  This is a longstanding Visual C++
issue; I don't use MSVC++, so I don't know if it is fixed in more
recent versions, or if there is an option to enable
standards-conforming behavior for this.

-- James



[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