简体   繁体   English

C ++复制构造函数vs重载赋值vs构造函数最佳实践?

[英]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.我是 C++ 新手,目前正在开发一个使用动态分配字符串的程序。 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). (我正在构建一个包含问题对象的考试对象,该对象包含一组 T/F 答案对象,每个都指向字符串的动态存储)。

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.请帮忙。

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).使用标准库(在这种情况下为std::stringstd::vector / std::map )。 Something like:就像是:

#include <string>
#include <map>

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

std::string does the resource management for you. std::string为您进行资源管理。 When its destructor is called, it'll clean up behind it.当它的析构函数被调用时,它会在它后面清理。 The same goes for std::map or std::vector . std::mapstd::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 .这里的神奇之处在于,所有 3 个类( std::stringstd::mapExam )中的成员都保证在超出范围时根据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.一般来说,我建议尽量避免在你的程序中编写newdelete If you need dynamic allocation in a use-case that doesn't fit well with containers, use std::unique_ptr or std::shared_ptr .如果您需要在不适合容器的用例中进行动态分配,请使用std::unique_ptrstd::shared_ptr Try to abide by the Law of Zero as much as you can.尽量遵守零定律

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM