0
#include<string>

class HasPtr {
public:
    HasPtr(const std::string &s = std::string()) :
        ps(new std::string(s)), i(0) {}
    HasPtr(const HasPtr &orig) :ps(new std::string(*orig.ps)), i(orig.i) {}
    HasPtr &operator=(const HasPtr &rhs) {
        *ps = *rhs.ps;
        i = rhs.i;
        return *this;
    }
private:
    std::string *ps;
    int i;
};

When I assign a HasPtr whose data member ps points to a large string to another, is there any the possibility that I cause a memory corruption? for example:

HasPtr a;
HasPtr b(string("123456789...123456789"));
a=b;
K.Robert
  • 215
  • 1
  • 2
  • 9

3 Answers3

1

The shown code is missing a destructor, this is going to result in a memory leak.

After the appropriate destructor gets added, the resulting class will be perfectly Rule-Of-Three compliant. As such, there won't be any memory-related issues.

Community
  • 1
  • 1
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • I use the synthesized destructor. My question is the safety about my copy assignment operation. – K.Robert Nov 28 '16 at 03:30
  • *I use the synthesized destructor* -- Which is not the correct thing to do. -- *My question is the safety about my copy assignment operation* -- It is not safe, as it leaks memory. Why not do as the answer given states? Add a destructor, implement the rule of 3 using simple swaps, and you're good to go. – PaulMcKenzie Nov 28 '16 at 03:38
  • @PaulMcKenzie I know the Rule of Three, okay I can add a destructor, but what confuse me is that the left-hand-side HasPtr 's data member pointed to a empty string before, it pointed to a place in a dynamic memory, my copy assignment operation copys a large string to that place, and I don't know whether the process is safe or not. – K.Robert Nov 28 '16 at 04:00
  • @K.Robert If what you want is a single string that's shared, then the string member should have been `std::shared_ptr`, not a raw pointer. As it stands now, there is a memory leak as you wrote no code to `delete` that memory at some point. – PaulMcKenzie Nov 28 '16 at 04:33
  • @PaulMcKenzie What you say is right, but it doesn't answer my question.Thank you, I think I have found my answer. – K.Robert Nov 28 '16 at 07:17
  • @PaulMcKenzie the copy assignment does not leak memory. – M.M Nov 28 '16 at 07:33
1

Hold the std::string by value. Besides being a string abstraction, it's also a resource management class, so use it as such. If you do, your class will be rule of 0/3/5 compliant without any extra effort from you.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
0

When std::string use up the memory during the operation, an exception will throw out, so the process doesn't corrupt the memory.

K.Robert
  • 215
  • 1
  • 2
  • 9