Reputation: 151
The following code is correct
string s1="abc";
string s2="bcd";
string &rs1=s1;
string &rs2=s2;
rs1=rs2;
cout<<rs1<<"----"<<rs2<<endl;
And thefollowing code will compile error:
class A
{
public:
A(string& a):ma(a) { }
string& ma;
};
string s1="abc";
string s2="bcd";
A oa(s1);
A ob(s2);
oa=ob;
cout<<oa.ma<<"----"<<ob.ma<<endl;
All above is string&
type assignment, why put them into class will cause a compile error?
(gcc version 4.7.1 )
error info is
non-static reference member 'std::string& A::ma', can't use default assignment operator
Upvotes: 0
Views: 73
Reputation: 66194
You're setting a member reference to a local temp variable. the parameter in your constructor is a temp). This is causing a "dangling reference", which is not good.
Change the param to a reference, or change your member to a non-reference. For your purposes you'll likely want:
class A
{
public:
A(string& a):ma(a) { }
A& operator =(const A& other)
{
ma = other.ma;
return *this;
}
string& ma;
};
But you should know, the default copy constructor of your class is probably not going to do what you think it will.
UPDATE
Specific area of the standard dealing with why the default copy-assignment operator is deleted when the class has a reference member:
C++11 § 12.8,p23
A defaulted copy/move assignment operator for class X is defined as deleted if X has: - a variant member with a non-trivial corresponding assignment operator and X is a union-like class, or
- a non-static data member of const non-class type (or array thereof), or
- a non-static data member of reference type, or
- a non-static data member of class type M (or array thereof) that cannot be copied/moved because overload resolution (13.3), as applied to M’s corresponding assignment operator, results in an ambiguity or a function that is deleted or inaccessible from the defaulted assignment operator, or
- a direct or virtual base class B that cannot be copied/moved because overload resolution (13.3), as applied to B’s corresponding assignment operator, results in an ambiguity or a function that is deleted or inaccessible from the defaulted assignment operator, or
- for the move assignment operator, a non-static data member or direct base class with a type that does not have a move assignment operator and is not trivially copyable, or any direct or indirect virtual base class.
Upvotes: 1