当函数返回C++向量实例时,它正在运行
C++ vector instance is operational when function returns it
在我的类中,我有两个向量对象:
std::vector<std::string> vecteur_noms_A_;
std::vector<std::string> vecteur_noms_B_;
我还有以下功能:
std::vector<std::string> & get_vecteur_noms_A_() {
return vecteur_noms_A_;
}
但我对B
没有一样!
当我实例化我的类,并在我的类构造函数中执行以下说明时;我可以看到(通过调试或当它抛出错误时(:
vecteur_noms_A_.push_back("some value"); // is ok
vecteur_noms_B_.push_back("some other value"); // is not ok <- throws an error.
调试让我看到一个对象(或实例?(空向量(存在vecteur_noms_A_
但不存在vecteur_noms_B_
。
不清楚为什么我观察到我没想到的举止,如果我得到解释,我会很高兴。
我定义函数的事实是否强制编译器实例化对象?
这是一个例子:
#include <iostream>
#include <vector>
using namespace std;
class GP
{
public:
//Constructeur
GP(std::vector<std::string> list_names_A, std::vector<std::string> list_names_B
);
//Fonctions
void construction_vecteur_A_B_(std::vector<std::string> list_names_A, std::vector<std::string> list_names_B);
std::vector<std::string>& get_vecteur_noms_A() {
return vecteur_noms_A_;
}
std::vector<std::string> vecteur_noms_A_;
std::vector<std::string> vecteur_noms_B_;
};
GP::GP(std::vector<std::string> list_names_a, std::vector<std::string> list_names_b) {
construction_vecteur_A_B_(list_names_a, list_names_b);
}
void GP::construction_vecteur_A_B_(std::vector<std::string> list_names_a, std::vector<std::string> list_names_b)
{
for (int i = 0; i < list_names_a.size(); i++) {
vecteur_noms_A_.push_back(list_names_a[i]);
}
for (int i = 0; i < list_names_b.size(); i++) {
vecteur_noms_B_.push_back(list_names_b[i]);
}
}
int main()
{
std::vector<std::string> list_names_A = std::vector<std::string>();
std::vector<std::string> list_names_B = std::vector<std::string>();
list_names_A.push_back("A");
list_names_B.push_back("B");
GP(list_names_A, list_names_B);
return 0;
}
由于这里编写的程序不会抛出任何错误,我想问一下为什么:
vecteur_noms_A_
和
vecteur_noms_B_
在执行时存在,以便我可以进行反推。 为什么没有必要在构造函数中将其应用于它们:
vecteur_noms_A_ = std::vector<std::string>();
vecteur_noms_B_ = std::vector<std::string>();
感谢您的帮助。
关于你的最后一个问题。在使用类GP
时,在执行构造函数的主体之前,不必为成员向量赋值(如std::vector<std::string>()
(,vecteur_noms_B_
vecteur_noms_A_
因为它们是默认构造的。
因此请注意,如果要在GP
的构造函数的主体中执行以下操作:
vecteur_noms_A_ = std::vector<std::string>();
vecteur_noms_B_ = std::vector<std::string>();
它等效于以下操作:
vecteur_noms_A_.operator=(std::vector<std::string>());
vecteur_noms_B_.operator=(std::vector<std::string>());
也就是说,您正在将一个空向量(使用复制赋值运算符(分配给已经默认构造的空向量,这是多余的。
相关文章:
- 建议在运行时将带有类实例的列表从c++导入qml
- 我们如何并行运行算法的 n 个实例并以有效的方式计算结果函数的平均值?
- 当函数返回C++向量实例时,它正在运行
- 有没有办法根据命令行参数定义数组大小?运行时与编译时实例化?
- 使用to_string、reverse、stoi组合的C++反转编号给出运行时错误实例超出范围
- 非类型引用参数可以在运行时修改,这是否意味着模板可以在运行时实例化?
- 运行时检查实例 (Base*) 是否覆盖父函数 (Base::f())
- 根据运行时参数避免模板实例化的代码重复
- 获取派生模板实例化的运行时类型
- 如何根据运行时输入实例化 c++ 模板
- 确保只有一个函数实例在运行?
- 一次运行程序的多个实例C
- 在C 中运行时从指针访问对象实例
- JIT 编译的运行速度能否比编译时模板实例化更快?
- 析构函数在 lambda 捕获说明符中声明的类实例上运行两次
- 备份正在运行的 rocksdb 实例
- 使用运行时常量实例化的函数模板
- 最大化qt中单个实例应用程序的已运行实例
- 获取应用程序运行实例的句柄
- 如何限制c++中运行实例的数量