, , , , , . -, , , X. , , X . -, X.s , ( ), X :
class X {
public:
X(const string& val) {
cout << "copied " << val << endl;
s = new string(val);
}
X(string&& val) {
cout << "moved " << val << endl;
s = new string(std::move(val));
}
~X() {
delete s;
}
private:
const string *s;
};
int main() {
string s = "hello world";
X x1(s);
X x2("hello world");
return 0;
}
, , const *. (nullptr), , :
X(const string* val) : s(nullptr) {
if(val != nullptr)
s = new string(*val);
}
These are the methods. When you design your class, the specifics of the problem at hand will determine whether you need to have a value or a pointer element.
source
share