本文为对不同场景下的构造函数调用进行跟踪。
构造函数
默认情况下,在 C++ 之后至少存在六个函数 默认构造/析构函数,复制构造/复制赋值,移动构造/移动赋值。以下代码观测发生调用的场景
#include <iostream>
struct Foo {
Foo() : fd(0) { std::cout << "Foo::Foo() this=" << this << " fd=" << fd << std::endl; }
Foo(int d) : fd(d) { std::cout << "Foo::Foo(int) this=" << this << " fd=" << d << std::endl; }
~Foo() { std::cout << "Foo::~Foo() this=" << this << " fd=" << fd << std::endl; }
Foo(const Foo &other) {
fd = other.fd;
std::cout << "Foo::Foo(const Foo &) this=" << this << " fd=" << fd << std::endl;
}
Foo &operator=(const Foo &other) {
fd = other.fd;
std::cout << "Foo::Foo &operator=(const Foo &) this=" << this << " fd=" << fd << std::endl;
return *this;
}
#if __cplusplus >= 201103L
Foo(Foo &&other) {
fd = other.fd;
other.fd = -1;
std::cout << "Foo::Foo(Foo &&) this=" << this << " fd=" << fd << std::endl;
}
Foo &operator=(Foo &&other) {
fd = other.fd;
other.fd = -1;
std::cout << "Foo::Foo &operator=(Foo &&) this=" << this << " fd=" << fd << std::endl;
return *this;
}
#endif
int fd;
};
void test_constructor() {
std::cout << std::endl << "// Foo f1(1);" << std::endl;
Foo f1(1);
std::cout << std::endl << "// Foo f2(f1);" << std::endl;
Foo f2(f1);
std::cout << std::endl << "// Foo f3 = f1;" << std::endl;
Foo f3 = f1;
std::cout << std::endl << "// f3 = f1;" << std::endl;
f3 = f1;
#if __cplusplus >= 201103L
std::cout << std::endl << "// Foo f4(std::move(f1));" << std::endl;
Foo f4(std::move(f1));
std::cout << std::endl << "// f4 = std::move(f1);" << std::endl;
f4 = std::move(f1);
#endif
std::cout << "\n";
}
int main() {
std::cout << "TEST Constructor\n";
test_constructor();
std::cout << "\n";
}
输出如下:移动构造/移动赋值 函数为 C++11 增加特性,需要使用 std::move
来调用移动构造函数。
// Foo f1(1);
Foo::Foo(int) this=0x7ffd3fc2420c fd=1
// Foo f2(f1);
Foo::Foo(const Foo &) this=0x7ffd3fc24208 fd=1
// Foo f3 = f1;
Foo::Foo(const Foo &) this=0x7ffd3fc24204 fd=1
// f3 = f1;
Foo::Foo &operator=(const Foo &) this=0x7ffd3fc24204 fd=1
// Foo f4(std::move(f1));
Foo::Foo(Foo &&) this=0x7ffd3fc24200 fd=1
// f4 = std::move(f1);
Foo::Foo &operator=(Foo &&) this=0x7ffd3fc24200 fd=-1
Foo::~Foo() this=0x7ffd3fc24200 fd=-1
Foo::~Foo() this=0x7ffd3fc24204 fd=1
Foo::~Foo() this=0x7ffd3fc24208 fd=1
Foo::~Foo() this=0x7ffd3fc2420c fd=-1
布置 new
基于 布置new
表达式可以实现STL中各种容器的 emplace 操作,借助 clangd 看到其默认实现为 operator new
标签:__,std,场景,构造,fd,函数调用,Foo,type,构造函数 From: https://www.cnblogs.com/shuqin/p/18204068