我想创建一个包含迭代器类的列表数据结构。一切正常,但是当我声明移动赋值运算符时,如果程序使用 C++14 或 C++11 标准,则该程序不会编译,但在 C++17、C++2a 中运行良好。
列表.h:
#pragma once
#include <iostream>
template <typename T>
class list {
struct node {
node(T data, node* prev = nullptr, node* next = nullptr)
: data{ data }, prev{ prev }, next{ next } {}
T data;
node* prev;
node* next;
};
public:
struct iterator {
template <typename>
friend class list;
explicit iterator(node *_node = nullptr)
: _node(_node) {}
iterator& operator=(iterator const &it) {
_node = it._node;
return *this;
}
iterator& operator=(iterator &&it) …Run Code Online (Sandbox Code Playgroud) 有没有更好的解决方案来快速初始化 C 数组(在堆上创建)?就像我们对大括号所做的那样
double** matrix_multiply(const double **l_matrix, const double **r_matrix);
foo() {
double DCT_matrix[8][8] = {
{ 0.3536, 0.3536, 0.3536, 0.3536, 0.3536, 0.3536, 0.3536, 0.3536 },
{ 0.4904, 0.4157, 0.2778, 0.0975, -0.0975, -0.2778, -0.4157, -0.4904 },
{ 0.4619, 0.1913, -0.1913, -0.4619, -0.4619, -0.1913, 0.1913, 0.4619 },
{ 0.4157, -0.0975, -0.4904, -0.2778, 0.2778, 0.4904, 0.0975, -0.4157 },
{ 0.3536, -0.3536, -0.3536, 0.3536, 0.3536, -0.3536, -0.3536, 0.3536 },
{ 0.2778, -0.4904, 0.0975, 0.4157, -0.4157, -0.0975, 0.4904, -0.2778 },
{ 0.1913, -0.4619, 0.4619, …Run Code Online (Sandbox Code Playgroud) const char* ch = "text";
ch = "Long text";
Run Code Online (Sandbox Code Playgroud)
写这样的代码可以吗?是否可能有缓冲区溢出?或者它可以写入不允许的地址?
在 C++ 中,我们可以通过取消引用来将类的堆分配对象分配给堆栈分配的对象。看起来没有问题,它可以按预期工作,即使析构函数也能正常工作,但是这样编写代码是好是坏?
#include <iostream>
class cls {
public:
cls(int n) : pInt{new int{n}} {
std::cout << "Constructor\n";
}
int *pInt;
~cls() {
std::cout << "Destructor\n";
delete pInt;
}
};
int main() {
cls *hObj = new cls{100};
cls sObj = *hObj;
}
Run Code Online (Sandbox Code Playgroud) join()我想知道在启动线程后不立即放置是否有任何优势?
std::thread t(func);
// some code ...
t.join();
Run Code Online (Sandbox Code Playgroud)
它会给你带来任何优势吗?或者在线程启动后使用它总是更好?
std::thread t(func);
t.join();
// some code ...
Run Code Online (Sandbox Code Playgroud) #include <iostream>
#include <memory>
int main() {
int i = 0;
float f = 0.0f;
double d1 = 0.0, d2 = 0.0, d3 = 0.0, d4 = 0.0;
auto a = [i,f,d1,d2,d3,d4](){};
std::cout << sizeof(std::unique_ptr<decltype(a)>) << std::endl; // 8
std::cout << sizeof(std::unique_ptr<char, decltype(a)>) << std::endl; // 48
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我只添加一个字符时,为什么这个程序的输出是 48?
c++ ×4
c ×2
arrays ×1
c++11 ×1
c++17 ×1
constructor ×1
destructor ×1
heap-memory ×1
stack-memory ×1
std ×1
string ×1