![](/img/trans.png)
[英]C++: How many times copy ctor may be called when element is added to the std::set/map or std::unordered_set/map
[英]How many times the copy ctor is called in the following?
在我讀過這個問題的書中,答案是8 次。
Temp fun1(Temp x)
{
Temp y(x);
Temp z=y;
return z;
}
void main()
{
Temp a;
Temp b=fun1(a);
Temp c=fun1(b);
}
#include <iostream>
class Temp
{
public:
int a;
Temp() : a(0) {}
Temp(const Temp &ref) : a(ref.a)
{
std::cout << "Temp(Temp&)" << std::endl;
}
};
Temp fun1(Temp x)
{
Temp y(x);
Temp z=y;
return z;
}
int main(int ac, char**av)
{
Temp a;
Temp b=fun1(a);
Temp c=fun1(b);
}
顯示 6 次叮當聲。
786_ g++ -std=c++11 test.cpp
787_ ./a.out
Temp(Temp&)
Temp(Temp&)
Temp(Temp&)
Temp(Temp&)
Temp(Temp&)
Temp(Temp&)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.