所以根据https://en.cppreference.com/w/cpp/thread/thread/thread:复制构造函数std::thread被删除,这是我不能做的原因(导致编译错误):
std::thread t1;
std::thread t2 = t1;
Run Code Online (Sandbox Code Playgroud)
但是我不知何故能够做到:
std::thread t1;
t1 = std::thread();
Run Code Online (Sandbox Code Playgroud)
我的印象是,上面的代码创建了一个临时std::thread对象并将其复制到其中,t1但复制构造函数不存在(如未编译的顶部代码段所示)。
那么在第二个片段中到底发生了什么?
我正在尝试学习C++的新功能,即移动构造函数和赋值X::operator=(X&&),我发现了一些有趣的例子, 但我唯一不理解但更不同意的是移动ctor和赋值运算符中的一行(在下面的代码中标记):
MemoryBlock(MemoryBlock&& other)
: _data(NULL)
, _length(0)
{
std::cout << "In MemoryBlock(MemoryBlock&&). length = "
<< other._length << ". Moving resource." << std::endl;
// Copy the data pointer and its length from the
// source object.
_data = other._data;
_length = other._length;
// Release the data pointer from the source object so that
// the destructor does not free the memory multiple times.
other._data = NULL;
other._length = 0;//WHY WOULD I EVEN BOTHER TO SET IT …Run Code Online (Sandbox Code Playgroud) 我不知道如何将某些类分为.hpp和.cpp文件。您能告诉我如何划分以下示例类吗?
class Foo {
public:
int x;
int getX() {
return x;
}
Foo(int x) : x(x) {}
};
Run Code Online (Sandbox Code Playgroud)
以及如何在main函数中包含此类?
如题。
下面是我的代码,这是最小可重现示例
啊
class B {
public:
string n;
B(string name) {
this->n = name;
cout << this->n<< " create" << endl;
}
~B() {
cout << this->n << " destory" << endl;
}
};
class A {
public:
vector<B> m_B;
A():m_B(vector<B>{}) {
cout << "class A create" << endl;
};
~A() {
cout << "class A destory" << endl;
};
};
Run Code Online (Sandbox Code Playgroud)
主程序
#include "a.h"
void addItem(A& _a,string n) {
_a.m_B.emplace_back(n);
};
int main()
{
A a;
addItem(a, "a"); …Run Code Online (Sandbox Code Playgroud) 我正在阅读 C++ 中的智能指针,我很惊讶超过 99% 的给定示例实际上是相当糟糕的示例,因为在这些情况下可以避免动态分配。我同意仅在 STL 容器不起作用的上下文中使用智能指针。例如,在动态数组 ( std::vector) 中,性能很重要,因此最好拥有经过良好测试的代码而不使用任何智能指针。
这里我认为是一个不好的例子,因为在这种情况下unique_ptr不是解决方案,但堆栈分配将是正确的方法。
MyObject* ptr = new MyObject();
ptr->DoSomething();
delete ptr;
Run Code Online (Sandbox Code Playgroud)
那么什么是 C++ 中智能指针的好例子或用途呢?
换种说法是什么设计模式需要将指针的所有权转移到另一个对象?