c++ - 函数返回结构 vector 的拷贝

标签 c++ stl

我在 Visual Studio 2010 中执行此操作。

我调用返回结构 vector 的函数。然后我将第一个 vector 元素(一个结构)存储到本地结构中,然后访问该结构的字符串成员,我得到正确的值。

但是如果我通过应用方括号访问相同的字符串值,直接调用函数本身,我会得到垃圾结果。

struct stNameAge
{
    char Name[64];
    int Age;
};

typedef std::vector<stNameAge> NamesAndAges;

NamesAndAges GetNamesAndAges()
{
    stNameAge nameage;
    strcpy_s (nameage.Name, 64, "My name goes here"); 
    nameage.Age = 23; 

    NamesAndAges nameandages;
    nameandages.push_back(nameage);

    return nameandages;
}

int _tmain(int argc, _TCHAR* argv[])
{
    stNameAge nameage = GetNamesAndAges()[0];

    char* MyName1 = nameage.Name ; // I get correct value of name here
    int MyAge1 = nameage.Age ;    // I get correct value here

    char* MyName2 = GetNamesAndAges()[0].Name ; // *** I get garbage value here ***
    int MyAge2 = GetNamesAndAges()[0].Age ; // I get correct value here

    return 0;
}

我真的是一头雾水。有人可以解释为什么会这样吗?

已编辑: (在下方添加了新代码)

如果我保持 vector 全局,它仍然是相同的情况。我认为返回 vector 本身的拷贝不是个好主意。

struct stNameAge
{
    char Name[256];
    int Age;
};

typedef std::vector<stNameAge> NamesAndAges;

NamesAndAges nameandages;

NamesAndAges GetNamesAndAges()
{
    stNameAge nameage;
    strcpy_s (nameage.Name, 64, "My name goes here"); 
    nameage.Age = 23; 

    nameandages.push_back(nameage);

    return nameandages;
}

int _tmain(int argc, _TCHAR* argv[])
{
    // Function returning vector of structs 
    stNameAge nameage = GetNamesAndAges()[0];

    char* MyName2 = GetNamesAndAges()[0].Name ; // *** I get garbage value here ***

    char* MyName1 = nameage.Name ; // I get correct value of name here

    return 0;
}

最佳答案

两者之间存在细微差别,第一种情况是将有效值复制到另一个有效变量,而第二种情况则无法保存“结果”。

在第一次出现时,您使用堆栈上的一个临时值来创建您的 vector ,但随后您返回它并将一个值复制分配给另一个您可以安全使用的变量

stNameAge nameage = GetNamesAndAges()[0];

在第二个中,您正在创建一个临时 vector ,请求一个元素,但请求指向该元素的指针。当 vector 被销毁时,指针不再有效

char* MyName2 = GetNamesAndAges()[0].Name ;

你能看出这两种情况的区别吗?

在伪代码中我们可以总结如下

int nameage;
int *pointer;
{
  int value = 44; // The value you're interested in

  nameage = value; // You can safely use nameage from this point forward
  pointer = &value; // When the scope ends, there's no guarantee you'll be pointing to valid data
}

// nameage is valid here, pointer is likely not and even if it is it's undefined behavior

关于c++ - 函数返回结构 vector 的拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23671632/

相关文章:

c++ - std::basic_string 中的 push_back() 与序列容器

c++ - 为什么 vector.begin() 可能不等于 &vector[0]?

c++ - 最快的 c++/STL 算法在成对的集合中查找字符串

c++ - 如何在 winapi C++ 上创建一些基本控件,如列表框

c++ - 用派生类初始化成员类

c++ - 方法访问控制和POD

C++,静态对象的构造函数中的异常绕过先前静态对象的析构函数

c++ - 为什么 std::fill 使用 ForwardIterator 而不是 OutputIterator?

c++ - 计算投影到地球上的圆上的点

c++ - 使用列表的此 C++ 代码出现段错误的原因是什么?