【发布时间】:2018-03-08 11:15:00
【问题描述】:
考虑这段代码:
#include <iostream>
struct S
{
S(std::string s) : s_{s} { std::cout << "S( string ) c-tor\n"; }
S(S const&) { std::cout << "S( S const& ) c-tor\n"; }
S(S&& s) { std::cout << "S&& c-tor\n"; s_ = std::move(s.s_); }
S& operator=(S const&) { std::cout << "operator S( const& ) c-tor\n"; return *this;}
S& operator=(S&& s) { std::cout << "operator (S&&)\n"; s_ = std::move(s.s_); return *this; }
~S() { std::cout << "~S() d-tor\n"; }
std::string s_;
};
S foo() { return S{"blaaaaa"}; }
struct A
{
A(S s) : s_{s} {}
S s_;
};
struct B : public A
{
B(S s) : A(s) {}
};
int main()
{
B b(foo());
return 0;
}
当我用g++ -std=c++1z -O3 test.cpp 编译它时,我得到以下输出:
S( string ) c-tor
S( S const& ) c-tor
S( S const& ) c-tor
~S() d-tor
~S() d-tor
~S() d-tor
我想知道为什么没有复制省略?我期待更多这样的东西:
S( string ) c-tor
~S() d-tor
当我使用 -fno-elide-constructors 编译时,输出相同
【问题讨论】:
-
如果我计算正确,没有省略应该有四个复制构造函数调用,而不是你有的两个。我建议你在调试器中运行,在复制构造函数上设置一个断点,这样你就可以看到它是从哪里调用的。这可能会给你一些关于正在发生的事情的提示。
标签: c++ copy-elision