加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 临时对象的子对象是否保证在返回时被移动?

发布时间:2020-12-16 06:01:26 所属栏目:百科 来源:网络整理
导读:#include string#include vectorusing namespace std;auto f(){ vectorstring coll{ "hello" }; // // Must I use move(coll[0]) ? // return coll[0]; }int main(){ auto s = f(); DoSomething(s);} 我知道:如果我只是返回coll,那么coll保证在返回时被移动
#include <string>
#include <vector>

using namespace std;

auto f()
{
    vector<string> coll{ "hello" };

    //
    // Must I use move(coll[0]) ?
    //
    return coll[0]; 
}

int main()
{
    auto s = f();
    DoSomething(s);
}

我知道:如果我只是返回coll,那么coll保证在返回时被移动.

不过,我不确定:coll [0]是否也保证在返回时被移动?

更新:

#include <iostream>

struct A
{
    A() { std::cout << "constructedn"; }
    A(const A&) { std::cout << "copy-constructedn"; }
    A(A&&) { std::cout << "move-constructedn"; }
    ~A() { std::cout << "destructedn"; }
};

struct B
{
    A a;
};

A f()
{
    B b;
    return b.a;
}

int main()
{
    f();
}

gcc 6.2和clang 3.8输出相同:

constructed

copy-constructed

destructed

destructed

解决方法

“隐性移动”规则的最干净的表述是目前工作文件的 [class.copy.elision]/3:

In the following copy-initialization contexts,a move operation might
be used instead of a copy operation:

  • If the expression in a return statement ([stmt.return]) is a (possibly parenthesized) id-expression that names an object with
    automatic storage duration declared in the body or
    parameter-declaration-clause of the innermost enclosing function or lambda-expression,or

  • […]

overload resolution to select the constructor for the copy is first
performed as if the object were designated by an rvalue. If the first
overload resolution fails or was not performed,or if the type of the
first parameter of the selected constructor is not an rvalue reference
to the object’s type (possibly cv-qualified),overload resolution is
performed again,considering the object as an lvalue.

b.a和coll [0]都不是id表达式.所以没有隐含的动作.如果你想要一个举动,你必须明确地做.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读