RuLoViC RuLoViC - 1 year ago 97
C++ Question

Need to implement destructor, copy constructor, assignment operator when using shared_ptr

I am working on c++11 project. In it I have a

shared_ptr
holding
std::string
data.

class Base {
public:
Base() : Base(string()) {}
virtual ~Base() = default;
Base(const string &str) {
str_ = std::make_shared<string>(str);
}
private:
std::shared_ptr<std::string> str_;
};


My question is: here should I implement destructor to free
str_
, copy constructor and assignment operator to take care of copies?
Is it enough if I rely on default ones provided by the compiler?
I want to allow creating objects of this class either in the stack by
Base b1("string");
or in the heap by
Base *b1 = new Base("string");

Answer Source

The default constructor and assignment operators (both copy and move) will be "correct". The reason I put "correct" in quotations is that I have concerns that you intend to derive classes from this Base class (given the virtual destructor, and the name), and if you write something like:

Base *p1 = new Derived1("foo", "bar");
Base *p2 = new Derived1("bar", "foo");
*p1 = *p2;   // Will compile, but probably won't do what you want.

Specifically, the assignment will copy the Base part of the object pointed to by p2, but will not copy any Derived1 parts.

I would either delete the constructor and assignment operators or make them protected.

class Base {
 public:
  Base() : Base(string()) {}
//Either
  Base(const Base& rhs) = delete;
  Base& operator=(const Base& rhs) = delete;
//OR
protected:
  Base(const Base&rhs) = default;
  Base& operator=(const Base& rhs) = default;
  Base(Base&&rhs) = default;
  Base& operator=(Base&& rhs) = default;
public:
//END
  virtual ~Base() = default;
  Base(const string &str) {
    str_ = std::make_shared<string>(str);
  }
 private:
  std::shared_ptr<std::string> str_;
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download