This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Assignment Operator Bug


This question is better suited to gcc-help@gcc.gnu.org.

On Thu, Jul 7, 2011 at 6:22 PM, Mactavish <mdtabishalam@gmail.com> 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 Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]