gpt4 book ai didi

C++:创建一个局部对象数组

转载 作者:行者123 更新时间:2023-11-27 23:20:27 25 4
gpt4 key购买 nike

如果我执行以下操作:

string* create_array(){
string* arr = new string[2];
string s = "hello";
string s2 = "world";

arr[0] = s;
arr[1] = s2;
return arr;
}

arr[0] = s的赋值,复制s,然后将该拷贝放入arr[0]<的内存地址 指向?或者它是否使 arr[0] 引用局部堆栈变量 s,在这种情况下,如果我使用从此函数返回的数组,调用 arr[0] 将具有不可预测的行为?

谢谢

最佳答案

is the assignment of arr[0] = s making a copy of s

是的。

and then putting that copy in the memory address that arr[0] points to?

没有。 arr[0] 是一个字符串,它不指向任何东西。 (在内部,它可能在某处有一个 char*,但每个 std::string 实例都是唯一的,并且是一个实现细节,我添加此评论只是为了完整)

or is it making arr[0] refer to the local stack variable s, and in this case if I use the array returned from this function calling arr[0] will have unpredictable behaviour?

不,它制作拷贝。

关于C++:创建一个局部对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13362300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com