error: passing const std::string as this argument

This topic is 3793 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

The Following is my Code FileNotReadableException Signature
class FileNotReadableException : public CGIException{
protected:
const string& fileName;
public:
void setFileName(const string& file);
const string& getFileName() const;
};


FileNotReadableException::FileNotReadableException():fileName(""), CGIException(){

}

}

fileName = file;//Line 43 Here is the Error
}

return fileName;
}

}


It yields the following Compiler Error.
Line 43: error: passing ‘const std::string’ as ‘this’ argument of ‘std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(const std::bas.........

Share on other sites
In general, don't use references as members unless you are very sure of what you are doing. You could instead make "fileName" a std::string instance.

Also, I do not understand the need for a setter for the filename member - why would you ever change the file name of such an exception? Also: is there a need for the default constructor? If a file can be detected as not being readable then it probably has a name.

Share on other sites
Um, "const" means you can't change the value. Think about ot a little.

Share on other sites
Thanks solved by using string instead of const string&
I can understand why the const was making the problem (const-correctness)
But cant understand why the reference was making a Problem cause I am initializing all of them on teh Constructor.

Share on other sites
When you create a FileNotFoundException instance, you are probably not passing it a string that will survive the stack unwinding this will cause (this is a guess - perhaps you are). You should only use a reference as a member (function arguments are fine) when you can be 100% sure that the referenced variable will have the same (or greater) lifetime as the reference holder.

Share on other sites
Quote:
 Original post by nlbsThanks solved by using string instead of const string&I can understand why the const was making the problem (const-correctness)But cant understand why the reference was making a Problem cause I am initializing all of them on teh Constructor.
Because when you assign something to a reference, you're assigning something to the value of the string. You have a const reference as a member variable, so you can't assign to it (It's const).

Okay Thanks

1. 1
2. 2
3. 3
Rutin
15
4. 4
khawk
13
5. 5
frob
12

• 9
• 9
• 11
• 11
• 23
• Forum Statistics

• Total Topics
633665
• Total Posts
3013245
×