C++函数返回 如何传值?

用函数返回一个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吧! 不用有顾虑的

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值