gpt4 book ai didi

c++ - 移动构造函数调用

转载 作者:搜寻专家 更新时间:2023-10-31 00:35:36 24 4
gpt4 key购买 nike

<分区>

我试图理解 C++11 中的移动语义,我编写了一小段代码来检查在创建对象时调用了哪些构造函数。

这是代码:

#include <iostream>

using namespace std;

class Bar
{
public:
int b;
Bar();
Bar(const Bar&);
~Bar();
};

class Foo
{
public:
int d;
Bar* b;
Foo();
Foo(const Foo&);
Foo(Foo&& other);
~Foo();
Foo& operator = (Foo);
};

Foo test();

Foo::Foo()
{
cout << "Default ctr of foo called\n";
b = new Bar();
}

Foo::~Foo()
{
delete b;
}

Foo::Foo(const Foo& other)
{
cout << "Copy ctr of foo called\n";
d = other.d;
b = new Bar();
b->b = other.b->b;

}

Foo::Foo(Foo&& other)
{
cout << "Move ctr of foo called\n";
d = other.d;
b = other.b;
other.d = 0;
other.b = NULL;
}

Foo& Foo::operator = (Foo other)
{
cout << "Copy assignment of foo called\n";
d = other.d;
b = new Bar();
b->b = other.b->b;
return *this;
}

Bar::Bar()
{
b = 1;
}

Bar::~Bar()
{
}

Bar::Bar(const Bar& other)
{
b = other.b;
}

int main()
{
Bar b;
Foo f1;
Foo f = test();
Foo f3 = move(test());
// cout << f1.b->b << "\n";
// Foo f2(test());


return 0;
}

Foo test()
{
Foo f;
return f;
}

这是我得到的输出:

Default ctr of foo called
Default ctr of foo called
Default ctr of foo called
Move ctr of foo called

我不太明白为什么不为 Foo f 调用移动构造函数。 test() 不是右值吗?在这种情况下调用了哪个构造函数?

任何帮助将不胜感激。

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