#include<string>
#include<iostream>
#include<chrono>
using namespace std;
std::string inline copy_str(const std::string &str) {
std::string str1 = str;
return str1;
}
void inline copy_str(std::string &str_out, const std::string &str_in) {
str_out = str_in;
}
class T {
public:
T() { std::cout << "create" << std::endl; }
T(const T& t) { std::cout << "create copy" << std::endl; }
T(T&& other) noexcept { std::cout << "create move" << std::endl; }
T& operator=(const T&) { std::cout << "= operator" << std::endl; return *this;}
~T() { std::cout << "~ destroy" << std::endl;};
};
T inline copy_T(const T &str) {
T str1 = str;
return str1;
}
void inline copy_T(T &str_out, const T &str_in) {
str_out = str_in;
}
int main()
{
T tt2;
std::cout<<"split here-------------------------" << std::endl;
T tt1;
tt1 = copy_T(tt1);
std::cout<<"split here-------------------------" << std::endl;
T tt3;
copy_T(tt3, tt2);
auto t1 = std::chrono::steady_clock::now();
for (int i = 0; i < 1e6; i++) {
std::string str = "base_link";
}
auto t2 = std::chrono::steady_clock::now();
std::string str_base = "base_link";
for (int i = 0; i < 1e6; i++) {
copy_str(str_base);
}
auto t3 = std::chrono::steady_clock::now();
for (int i = 0; i < 1e6; i++) {
std::string str;
str = copy_str(str_base);
}
auto t4 = std::chrono::steady_clock::now();
for (int i = 0; i < 1e6; i++) {
std:string str_out;
copy_str(str_out, str_base);
}
auto t5 = std::chrono::steady_clock::now();
std::chrono::duration<double, std::milli> duration1 = t2 - t1;
std::chrono::duration<double, std::milli> duration2 = t3 - t2;
std::chrono::duration<double, std::milli> duration3 = t4 - t3;
std::chrono::duration<double, std::milli> duration4 = t5 - t4;
std::cout << duration1.count() << std::endl
<< duration2.count() << std::endl
<< duration3.count() << std::endl
<< duration4.count();
return 0;
}
输出如下:
create
split here-------------------------
create
create copy
= operator
~ destroy
split here-------------------------
create
= operator
85.89
48.75
149.73
73.165~ destroy
~ destroy
~ destroy
实验结论:函数内构造再返回比提前构造好多了一次拷贝构造;