当函数返回C++向量实例时,它正在运行

C++ vector instance is operational when function returns it

本文关键字:运行 实例 函数 返回 C++ 向量      更新时间:2023-10-16

在我的类中,我有两个向量对象:

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>());

也就是说,您正在将一个空向量(使用复制赋值运算符(分配给已经默认构造的空向量,这是多余的。