gpt4 book ai didi

c++ - 复制和移动构造函数

转载 作者:行者123 更新时间:2023-12-02 10:10:40 26 4
gpt4 key购买 nike

具有以下代码:

#include <iostream>
#include <vector>
using namespace std;

class CIntPtr {
public:
int* ptr;
public:
CIntPtr() {
// Default constructor
cout << "Calling Default constructor\n";
ptr = new int;
}

CIntPtr(const CIntPtr& obj) {
// Copy Constructor
// copy of object is created
this->ptr = new int;
// Deep copying
cout << "Calling Copy constructor\n";
}

CIntPtr(CIntPtr&& obj) {
// Move constructor
// It will simply shift the resources,
// without creating a copy.
cout << "Calling Move constructor\n";
this->ptr = obj.ptr;
obj.ptr = NULL;
}

~CIntPtr() {
// Destructor
cout << "Calling Destructor\n";
delete ptr;
}

};

CIntPtr returnCIntPtr(CIntPtr a) {
*a.ptr += 2;
return a;
}

int main() {

CIntPtr foo;
returnCIntPtr(foo);

return 0;
}
同时存在 复制移动构造函数。为什么还要调用move ctor?因为我们将左值作为函数参数传递了,难道不是仅调用了复制ctor吗?何时可以在此代码中调用move ctor?

最佳答案

return a;函数的return statement(即returnCIntPtr)中调用了移动构造器。

Automatic move from local variables and parameters

If expression is a (possibly parenthesized) id-expression that names avariable whose type is either

  • a non-volatile object type or
  • a non-volatile rvalue reference to object type (since C++20)

and that variable is declared

  • in the body or
  • as a parameter of

the innermost enclosing function or lambda expression,

then overload resolution to select the constructor to use for initialization of the returned value or, for co_return, to select the overload of promise.return_value() (since C++20) is performed twice:

  • first as if expression were an rvalue expression (thus it may select the move constructor), and
    • if the first overload resolution failed or
  • then overload resolution is performed as usual, with expression considered as an lvalue (so it may select the copy constructor).

首先尝试将 a复制为返回值作为rvalue-expression,然后选择move构造函数。

关于c++ - 复制和移动构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63667928/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com