在C++11其中std::atomic_flag,对于线程循环很有用:
static std::atomic_flag s_done(ATOMIC_FLAG_INIT);
void ThreadMain() {
while (s_done.test_and_set()) { // returns current value of s_done and sets to true
// do some stuff in a thread
}
}
// Later:
s_done.clear(); // Sets s_done to false so the thread loop will drop out
Run Code Online (Sandbox Code Playgroud)
该ATOMIC_FLAG_INIT组的标志false,这意味着该线程永远不会在循环。一个(不好的)解决方案可能是这样做的:
void ThreadMain() {
// Sets the flag to true but erases a possible false
// which is bad as we may get into a deadlock
s_done.test_and_set();
while …Run Code Online (Sandbox Code Playgroud) 分配给的内存是多少char *ptr:
#include <iostream>
using namespace std;
class A
{
private:
int count;
char *ptr;
public :
void print()
{
cout << "Addr " << &ptr << endl;
cout << "Addr " << *ptr << endl;
}
};
int main()
{
A obj;
obj.print();
A *obj1 = new A(obj);
obj1->print();
cin.get();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我正在使用编译器提供的复制构造函数.我有兴趣了解我将分配多少内存*ptr.
我是Maven的新手.
如何创建maven-archetype-nar-exec项目类型?
如果我跑,mvn -archetype=generate我没有选择的选项maven-archetype-nar-exec?
我是否必须将某些内容下载到Maven存储库中?
我正在使用 Maven 3.0.3
为什么不在此代码中调用析构函数:
#include <iostream>
#include <thread>
#include <memory>
class base {
public:
base() {
std::cout << "base()" << std::endl;
}
virtual ~base() {
std::cout << "~base()" << std::endl;
}
base(const base&) = delete;
base(base&&) = delete;
base& operator=(const base&) = delete;
base& operator=(base&&) = delete;
};
class derived final : public base {
public:
derived() {
std::cout << "derived()" << std::endl;
}
virtual ~derived() {
std::cout << "~derived()" << std::endl;
}
};
void foo() {
static thread_local std::unique_ptr<base> ptr; …Run Code Online (Sandbox Code Playgroud)