Move and Copy 构造函数与 std::move [duplicate] 同时调用

Move and Copy Constructor called at the same time with std::move [duplicate]

提问人:Evethir 提问时间:7/21/2020 更新时间:7/21/2020 访问量:362

问:

我正在练习 std::move wih std::vector::p ush_back。我有这个简单的代码:

struct A
{
    A(int i,bool b,float f) : _i(i), _b(b), _f(f) {}
    A(const A& a)
    {
        std::cout << "copy constructor" << std::endl;
    }
    A(A&& a)
    {
        std::cout << "move constructor" << std::endl;
    }
    int _i;
    bool _b; 
    float _f; 
};

struct B
{
    template <typename T>
    void Add(T&& t) // universal reference
    {
        _v.push_back(std::move(t));
    }

private: 
    std::vector<A> _v; 
};


int main() {

    A a(1, false, 2.f);
    B b; 
    std::cout << "using rValue" << std::endl;
    b.Add(A(1, true, 2.f));
    std::cout << "using lValue" << std::endl;
    b.Add(a);
    return 0;
}

由于某种原因,输出是:

using rValue
move constructor
using lValue
move constructor
copy constructor

为什么仍然调用复制构造函数?我的输出中不应该只有移动构造函数吗?

C++ Move 复制构造函数 move-semantics

评论

1赞 Yksisarvinen 7/21/2020
该问题的设置略有不同,但核心问题是在第二秒发生之前进行向量重新分配。push_back
2赞 Igor Tandetnik 7/21/2020
如果标记移动构造函数,则应看到两个移动,而不是一个移动和一个副本,因为矢量在重新分配时将能够将元素移动(而不是复制)到新的存储块中。noexcept
0赞 Evethir 7/22/2020
Ehi Guys,感谢您的评论,之所以调用复制构造函数,是因为在添加新对象(按预期使用 move 进行)时,向量必须调整自身大小,然后分配一个新的内存区域,其中复制了第一个对象,这导致了复制构造函数的调用:)

答: 暂无答案