Bug 32944 - operator= not ambiguous overload but does not compile
Summary: operator= not ambiguous overload but does not compile
Status: RESOLVED INVALID
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 4.0.1
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2007-07-31 12:19 UTC by Dallas Clarke
Modified: 2007-08-01 00:24 UTC (History)
1 user (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Dallas Clarke 2007-07-31 12:19:36 UTC
#include <string.h>
#include <stdio.h>

class CString{
public:
	CString(){value = NULL;}
	CString(char *initValue){
		if(initValue != NULL) value = NULL; 
		else strcpy((value = new char[strlen(initValue)+1]),initValue);
	}
	~CString(){if(value != NULL) delete [] value;}
	CString& operator=(char* newValue){
		if(value != NULL) delete [] value;
		if(newValue != NULL) value = NULL; 
		else strcpy((value = new char[strlen(newValue)+1]),newValue);
	}
	CString& operator=(CString& newValue){
		if(value != NULL) delete [] value;
		if(newValue.value != NULL) value = NULL; 
		else strcpy((value = new char[strlen(newValue.value)+1]),newValue.value);
	}
	CString operator+(char *addValue){
		CString tempValue;
		strcpy((tempValue.value = new char[strlen(value) + strlen(addValue) + 1]),value);
		strcat(tempValue.value,addValue);
		return CString(tempValue.value);
	}
	CString operator+(CString& addValue){
		CString tempValue;
		strcpy((tempValue.value = new char[strlen(value) + strlen(addValue.value) + 1]),value);
		strcat(tempValue.value,addValue.value);
		return CString(tempValue.value);
	}
	char *value;
};

int main(int argc, char *argv[])
{
	CString a("First String"), b("Second String"), c;
	c = a + " - " + b;
	printf(c.value);
}
Comment 1 Paolo Carlini 2007-07-31 12:37:36 UTC
The compiler is right: operator+ returns a *temporary* CString and you have an assignment operator taking a *non const* reference. Just change the latter to take a const reference.
Comment 2 Dallas Clarke 2007-08-01 00:14:05 UTC
The reason I was passing the reference and not the value is because is some circumstances I can change the value of the parameter. Using the const keyword prevents me from calling methods that can change the value – even if in this example they do not.

Thanks,
Dallas Clarke
 
BSc (CS) LLB UNSW
Architect / Lead Developer 
Ekky Software
 
 
Website: http://www.ekkySoftware.com 
Comment 3 Andrew Pinski 2007-08-01 00:24:09 UTC
You need to change the operator= to:
        CString& operator=(const CString& newValue){

Otherwise you cannot bind a rvalue to the reference as it will only bind to a lvalue and returned from operator+ is a rvalue.

In C++0x there are rvalue references which you can use but that feature is not in a released version of GCC yet.  (it is on the trunk though).