【发布时间】:2020-06-09 16:20:11
【问题描述】:
我正在学习 C++,尤其是 OO 编程。
我的程序使用指针来处理动态内存分配。
在创建我的默认构造函数时,我对重复自己感到很无聊
myInt = new int;
myOtherInt = new int;
等等。
所以我的问题是:有没有办法写出类似的东西:
myInt, myOtherInt = new int;
这是我的构造函数代码:
Annonce::Annonce(string Titre, long double Prix, string Intro, string Description, vector<vector<string>> ImgUrls) {
titre = new string;
intro = new string;
description = new string;
imgUrls = new vector<vector<string>>;
prix = new long double;
id = new size_t;
*id = nbAnnonces;
*titre = std::move(Titre);
*prix = Prix;
*intro = std::move(Intro);
*description = std::move(Description);
*imgUrls = std::move(ImgUrls);
}
【问题讨论】:
-
"我的程序使用指针来处理动态内存分配。"必须吗?而不是你的班级由
std::string *和std::vector <>*组成,它可以只容纳std::string和std::vector吗?这些对象自己处理动态内存分配,所以我们不必这样做。 -
我 99.9% 确定您不需要这些指针。看看这个构造函数的外观:stackoverflow.com/questions/1711990/…
-
myInt = new int;应该是您几乎从不做的事情。与intro = new string;相同 -
你几乎不应该直接使用
new(除非可能作为std::shared_ptr或std::unique_ptr成员的参数)。你在这里特别展示的例子显然是错误的。见Why should C++ programmers minimize use of 'new'?。如果您的教学材料教您像这样编写 C++,那么我建议您停止使用该材料并改用 recommended C++ books 之一。 -
C++ 不是 Java。
new在 Java 中可能是例行公事,但在 C++ 中应该避免或最小化它,因为 walnut 指出的原因。
标签: c++ class c++11 constructor