Should the code fail during runtime? Visual studio executes it without failure
#include<iostream>
#include <string>
using namespace std;
class Boy
{
string* _name;
public:
Boy(string n) :_name(new string(n)) {}
string getName() const { return *_name; }
};
int main() {
Boy t("Tom");
string str = "Tom2";
t = str;
cout << t.getName();
return 0;
}
Should the code fail during runtime?
No, it shouldn't.
Let's dissect, what the following line does:
t = str;
There's a temporary Boy
instance implicitely constructed. Thus it's merely the same as
t = Boy(str);
the operator=
copies the pointer generated in the constructor to t._name
.
The temporarily created Boy
instance goes away, without deleting the internally managed pointer (as it should).
Thus your code works without failure or undefined behavior (but leaks memory).
Said all that above, what you really should do, is the following class declaration:
class Boy {
std::string name;
public:
Boy(const std::string& n) : name(n) {}
const std::string& getName() const { return name; }
};
and stop worrying about pointers, memory management and all of that stuff, YAGNI. std::string
, and other container classes provided by the c++ standard library are designed to do all of that for you in an efficient, safe, and less error prone manner.