P
pmatos
Hi all,
I've been having questions about strings, references,
initializations... I've created code (which will not compile due to a
reference problem) and I'd like comments on why this won't work and any
other comment to the code with efficiency in mind.
#include <iostream>
#include <string>
using std::cout;
using std::string;
class myClass {
public:
myClass(string s) : str(s) { }
~myClass() { }
string& getStr() const { return str; }
private:
string str;
};
int main() {
string * s = new string("FOO");
myClass * m = new myClass(*s);
cout << m->getStr() << std::endl;
delete s;
delete m;
return 0;
}
Some questions:
1 - Should constructor receive a &? (would it be faster? now, it's
copying the string in str(s), right?)
2 - why returning string& is not working? (returning just string would
return a copy of str, right?)
3 - How can I return the string, as efficiently as possible but making
sure it cannot be modified?
Any other comments are welcome.
Thanks,
Paulo Matos
I've been having questions about strings, references,
initializations... I've created code (which will not compile due to a
reference problem) and I'd like comments on why this won't work and any
other comment to the code with efficiency in mind.
#include <iostream>
#include <string>
using std::cout;
using std::string;
class myClass {
public:
myClass(string s) : str(s) { }
~myClass() { }
string& getStr() const { return str; }
private:
string str;
};
int main() {
string * s = new string("FOO");
myClass * m = new myClass(*s);
cout << m->getStr() << std::endl;
delete s;
delete m;
return 0;
}
Some questions:
1 - Should constructor receive a &? (would it be faster? now, it's
copying the string in str(s), right?)
2 - why returning string& is not working? (returning just string would
return a copy of str, right?)
3 - How can I return the string, as efficiently as possible but making
sure it cannot be modified?
Any other comments are welcome.
Thanks,
Paulo Matos