user2470057
user2470057

Reputation: 537

C++ copy constructor vs overloaded assignment vs constructor best practices?

this is more of an opinion/best practices question.

I'm new to C++ and I'm currently working on a program that uses dynamically allocated strings. I finally get the difference between the constructors, the copy constructors and overloaded assignment operator. I also get the need for a destructor for these objects.

(I'm building an exam object that holds question objects that hold an array of T/F answer objects, each point to dynamic storage for the strings).

Here's my question: What is considered best practices in the professional world for creating these object? As I sit here and think about this, I can gather information from the user and store those values in temporary locations and instantiate the question objects with the constructor, or I can build each object using the copy and assignment methods... I'm not sure what to do. Is one method better than the other? Should I build and test all three? Please help.

Upvotes: 0

Views: 746

Answers (1)

anthonyvd
anthonyvd

Reputation: 7590

Best practice in this case is to not manage resources yourself. Use the standard library (std::string and std::vector/std::map in this case). Something like:

#include <string>
#include <map>

class Exam {
public:
  std::map<std::string, std::string> questions_;
};

std::string does the resource management for you. When its destructor is called, it'll clean up behind it. The same goes for std::map or std::vector.

The magic here is that the members in all 3 classes (std::string, std::map, Exam) are guaranteed to be properly disposed as they go out of scope, per RAII. So, if you use it like:

void foo() {
  Exam e;
  e.questions_["6 x 7 = ?"] = "42";
} // Here, you're guaranteed that all storage for all your questions and answers is disposed.

you don't have to worry about writing constructors, destructors, or managing heap-allocated objects.

Generally, I'd recommend trying to avoid writing new and delete in your programs at all. If you need dynamic allocation in a use-case that doesn't fit well with containers, use std::unique_ptr or std::shared_ptr. Try to abide by the Law of Zero as much as you can.

Upvotes: 4

Related Questions