源文件中,以vector为例,如何使用移动构造,以及快速清空vector:
#include
#include
#include
#include
#include
class DemoPrint
{
int data{0};
public:
DemoPrint(int init) : data(init)
{
std::cout << "DemoPrint constructor " << data << std::endl;
}
DemoPrint(DemoPrint &&demo) : data(demo.data + 10)
{
std::cout << "DemoPrint move-structor " << data << std::endl;
}
~DemoPrint()
{
std::cout << "DemoPrint destructor " << data << std::endl;
}
};
void vectorClearTest()
{
std::vector vec;
vec.push_back(DemoPrint(1));
std::cout << "after push back, size:" << vec.size() << ", capacity:" << vec.capacity() << std::endl;
vec = decltype(vec){};
std::cout << "after assigned, size:" << vec.size() << ", capacity:" << vec.capacity() << std::endl;
vec.push_back(DemoPrint(2));
std::cout << "after re-push back, size:" << vec.size() << ", capacity:" << vec.capacity() << std::endl;
(decltype(vec){}).swap(vec);
std::cout << "after swapped, size:" << vec.size() << ", capacity:" << vec.capacity() << std::endl;
vec.push_back(DemoPrint(3));
vec.clear();
}
void weakPtrTest()
{
std::weak_ptr wp{};
if (wp.expired())
{
std::cout << "Empty WP expired" << std::endl;
}
{
std::shared_ptr sp(new int(1));
wp = sp;
if (wp.expired())
{
std::cout << "Inscope WP expired" << std::endl;
}
if (sp)
{
}
}
if (wp.expired())
{
std::cout << "Outscope WP expired" << std::endl;
}
}
int main()
{
vectorClearTest();
std::optional oi;
if (!oi)
{
std::cout << "optional is empty" << std::endl;
}
oi = 12;
if (oi)
{
std::cout << "optional value: " << oi.value() << std::endl;
}
sleep(10);
std::cout << "main quit." << std::endl;
return 0;
}
VSCode启动运行时,只会调用最顶层的Makefile,为能编译子文件下的文件,需要在顶层Makefile中调用子文件夹下的Makefile。
顶层Makefile(调用子文件夹下Makefile):
subsystem:
cd learning && make
clean:
cd learning && make clean
运行make会自动编译,而运行make clean会做清理;
子文件夹Makefile(真正编译文件):
CFLAGS=-c -Wall -std=c++17
LFLAGS = -Wall -std=c++17
CXXFLAGS = -Wall -std=c++17
hello: hello.o
g++ -g -std=c++17 -o hello hello.o
hello.o: hello.cpp
g++ -g -std=c++17 -o hello.o -c hello.cpp
clean:
rm -rf hello
rm -rf *.o
为保证能支持C++17,必须设定标志CXXFLAGS
,否则即使g++中添加了-std=c++17
也无效。
为例使用make编译,需要修改.vscode
目录下的tasks.json文件
默认生成的task使用g++编译,需要修改为使用make:
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "make",
"type": "shell",
"group": {
"kind": "build",
"isDefault": true
}
},
{
"label": "clean",
"command": "make", // 在shell中使用命令,如需加参数,可再添加args属性
"args": [
"clean"
],
"type": "shell",
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
同时要保证launch.json中preLaunchTask
的值与此文件中label
的值相同。
为使vscode识别C++17,需要修改c_cpp_properties.json中cppStandard:
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [],
"compilerPath": "/usr/bin/gcc",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "linux-gcc-x64"
}
],
"version": 4
}