Could someone please tell me why this does not work? I was under the impression that C++ would automatically pass the reference of the return-by-value function result to the constructor, but it complains that no matching operator could be found.
class bucket_string {
public:
bucket_string();
bucket_string(bucket_string & rhs);
bucket_string & operator=(bucket_string & rhs);
virtual ~bucket_string();
bucket_string substr(iterator start, iterator end){
bucket_string b(str);
return b;
}
};
bucket_string bs("the quick brown fox jumps over the lazy dog");
bucket_string bs1 = bs.substr(bs.begin(), bs.end());
returns the following error:
error: no matching function for call to ‘bucket_string::bucket_string(bucket_string)’
note: candidates are: bucket_string::bucket_string(bucket_string&)
bucket_string::bucket_string()
In C++, temporary values cannot be bound to non-const references.
Your bucket_string substr(iterator start, iterator end)
function returns a temporary, and your constructor/assignation operator take a non-const reference as a parameter hence your problem.
Thus you need to add the missing const
specifier to your constructor and assignation operator. Like so:
bucket_string(const bucket_string& rhs);
bucket_string& operator=(const bucket_string& rhs);
Here is an interesting discussion on the topic for a better understanding.
On a side note, and if C++11 is an option, you may also make your class movable. This would allow the internal resources of your temporary to be transferred to another instance. We lack context to say if that would be a good thing in your situation.
You would then have to implement those methods:
bucket_string(bucket_string&& other);
bucket_string& operator=(bucket_string&& other);
Put some const
.
bucket_string(const bucket_string & rhs);
^^^^^
bucket_string & operator=(const bucket_string & rhs);
^^^^^
You're passing a temporary const values to the constructor. Compiler is searching for a constructor which accpets const
reference:
bucket_string bs("the quick brown fox jumps over the lazy dog");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With