在学习多线程编程时,我编写了以下代码。
#include <thread>
#include <iostream>
#include <cassert>
void check() {
int a = 0;
int b = 0;
{
std::jthread t2([&](){
int i = 0;
while (a >= b) {
++i;
}
std::cout << "failed at iteration " << i << "\n"
// I know at this point a and b may have changed
<< a << " >= " << b << "\n";
std::exit(0);
});
std::jthread t1([&](){
while (true) {
++a;
++b;
}
});
}
}
int main() { …Run Code Online (Sandbox Code Playgroud) 为什么编译器在不需要副本构造函数时会关心它?
#include <iostream>
template<typename T>
void print(T);
class Foo {
Foo(const Foo&);
public:
Foo(){}
};
template<>
void print(const Foo& f) {
std::cout << "Foo\n";
}
int main(){
Foo foo;
print(foo);
}
Run Code Online (Sandbox Code Playgroud)
函数print已重载以接受,const Foo&但编译器会产生以下编译错误:
main.cpp: In function ‘int main()’:
main.cpp:21:14: error: ‘Foo::Foo(const Foo&)’ is private within this context
21 | print(foo);
| ^
main.cpp:7:5: note: declared private here
7 | Foo(const Foo&);
| ^~~
main.cpp:4:12: note: initializing argument 1 of ‘void print(T) [with T = Foo]’
4 …Run Code Online (Sandbox Code Playgroud)