1

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;
}
YAKOVM
  • 9,805
  • 31
  • 116
  • 217

1 Answers1

3

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.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • at the end the temporal object and t both are deleted. but the both point same string pointer? – YAKOVM Sep 06 '20 at 11:56
  • @Yakov I don't fully understand your question, but I suspect, that you believe, that the memory held by the`_name` pointer would be automatically deleted, when an instance of `Bob` is destroeyed. But that's not the case, you would need to call `delete _name;` explicitely in the destructor to do so. – πάντα ῥεῖ Sep 06 '20 at 12:01
  • @Yakov Is your main programming background C#? – πάντα ῥεῖ Sep 06 '20 at 12:11
  • 1
    @Yakov Note that the constructor of `Boy` takes it's argument `n` by value - it makes an independent copy whenever you call it. Then it copies it again in `_name(new string(n))`. On that note: A pointer to a standard container is almost never what you want. – Lukas-T Sep 06 '20 at 12:45