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

我只是一个虾纸丫 提交于 2019-12-25 16:26:12

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/31686973/c-copy-constructor-vs-overloaded-assignment-vs-constructor-best-practices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!