C++ Guaranteed Copy Elision

考虑如下代码:

struct S
{
    S(){}

    // not copyable, not movable:
    S(S const &) = delete;
    S(S  &&) = delete;
};

S getS_GCE() {
    return S();
}

int main()
{
    S s = getS_GCE();
    return 0;
}

这段话在C++17前是编译不过的。因为在用到拷贝构造函数时,却遇到程序员禁止了它们(=delete标注的函数)。C++17新标准,Guaranteed Copy Elision。prvalue的含义发生变化(是啊,还没听说什么纯右值,广义右值之类的“新”名词,prvalue就改变了定义了)。这段程序片段被神奇的编译通过了!

考虑另一段代码:

struct S
{
    S(){}

    // not copyable, not movable:
    S(S const &) = delete;
    S(S  &&) = delete;
};

S getS_NRVO() {
    S s;
    return s;
}

int main()
{
    S s = getS_NRVO();

    return 0;
}

C++17仍旧编译失败。看来,是因为Guaranteed Copy Elision只适用于特定的情况。此处待研究。

参考:

http://en.cppreference.com/w/cpp/language/copy_elision

https://stackoverflow.com/questions/38043319/how-does-guaranteed-copy-elision-work

posted @ 2018-03-15 20:34  thomas76  阅读(242)  评论(0编辑  收藏  举报