我有以下代码
#include <iostream>
template<typename T>
struct A
{
T e_;
A(T e) : e_(e)
{
std::cout<<"A\n";
}
A(const A& other)
{
std::cout<<" ACopy\n";
}
~A() { std::cout<<"~A\n";}
};
struct B
{
B() { std::cout<< "B\n";}
};
int main()
{
A a(A(A(B{})));
return 0;
}
我不确定为什么A只构造一次。
这是一个哥德链接https://godbolt.org/z/fsvzTf
答案 0 :(得分:2)
这是由于复制省略。您可以在https://en.cppreference.com/w/cpp/language/copy_elision上详细了解它。
顺便说一句,这会导致其他令人惊讶的效果,如Why does an object returned by value have the same address as the object inside the method?。