用函数返回一个std::vector 会不会运行很缓慢? 期间的传值是如何进行的呢?
试运行以下代码:
#include <bits/stdc++.h>
using i64 = long long;
struct Node {
int x, y;
std::string* s_ptr;
static int ordinaryConstructer;
static int moveConstructer;
static int moveAssign;
static int copyConstructer;
static int copyAssign;
Node() = delete;
Node(int x, int y) : x {x}, y {y}, s_ptr {nullptr} {
ordinaryConstructer += 1;
}
Node(Node &&a) : x {a.x}, y {a.y} {
s_ptr = a.s_ptr;
a.s_ptr = nullptr;
moveConstructer += 1;
}
Node operator=(Node &&a) {
x = a.x;
y = a.y;
delete s_ptr;
s_ptr = a.s_ptr;
a.s_ptr = nullptr;
moveAssign += 1;
}
Node(Node& a) : x {a.x}, y {a.y} {
s_ptr = new std::string(*a.s_ptr);
copyConstructer += 1;
}
Node operator=(Node& a) {
x = a.x;
y = a.y;
delete s_ptr;
s_ptr = new std::string(*a.s_ptr);
copyAssign += 1;
}
};
int Node::ordinaryConstructer = 0;
int Node::moveConstructer = 0;
int Node::moveAssign = 0;
int Node::copyConstructer = 0;
int Node::copyAssign = 0;
Node func(std::string& s) {
Node a(0, 2);
a.s_ptr = &s;
std::cout << (&a) << '\n';
return a;
}
int main() {
std::string s = "Hello";
Node a = func(s);
std::cout << (&a) << '\n';
printf("%d, %d, %d, %d, %d",
Node::ordinaryConstructer,
Node::moveConstructer,
Node::moveAssign,
Node::copyConstructer,
Node::copyAssign
);
return 0;
}
运行结果如下:

会发现两者地址相同, 并且总体只出现了一次构造函数, 其余函数均未调用
所以请大胆地return吧! 不用有顾虑的
博客探讨了C++中用函数返回std::vector是否运行缓慢及传值方式。通过试运行代码,发现返回对象与接收对象地址相同,且总体仅出现一次构造函数,其余函数未调用,得出可大胆使用return的结论。
5万+





