gpt4 book ai didi

c++ - 在 C++ 函数中返回匿名实例/值

转载 作者:行者123 更新时间:2023-11-28 00:19:29 25 4
gpt4 key购买 nike

我对 C++ 中函数的返回类型有疑问。

为什么 return pair<int, int>(1, 1);return vector<int>(3, 3);工作?我不应该事先创建一个本地实例 var 并将其作为返回值,就像返回 a 一样,因为 return int 1;不起作用。

// ...

int fun1() {
// return int 1;
int a = 1;
return a;
}

pair<int, int> fun2() {
return pair<int, int>(1, 1);
}

vector<int> fun3() {
return vector<int>(3, 3);
}

int main(){
cout << fun1() << endl;
cout << fun2().first << endl;
cout << fun3()[1] << endl;

return 0;
}

难道return这种风格只能应用在有特定构造函数的类实例上吗?下面的例子可以工作。我正在寻找确认或引用资料。

class A {
public:
int a;
A(int a_) : a(a_) {};
};

A fun4() {
return A(1);
}

测试的代码示例:

Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn) Target: x86_64-apple-darwin14.0.0 Thread model: posix

最佳答案

because return int 1 doesn't work.

return int(1); 确实...或 return 3 - 2; 就此而言。创建一个临时变量或使用一个文字并没有错——如果有必要,将使用类复制或移动构造函数在调用者的上下文中设置变量,或者有时返回返回值优化(RVO)将启动并且被调用的函数将能够直接在调用者的堆栈中创建返回值。

关于c++ - 在 C++ 函数中返回匿名实例/值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28270392/

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