我在linux上使用c中的结构.我开始使用位字段和"打包"属性,我遇到了一个奇怪的行为:
struct t1
{
int a:12;
int b:32;
int c:4;
}__attribute__((packed));
struct t2
{
int a:12;
int b;
int c:4;
}__attribute__((packed));
void main()
{
printf("%d\n",sizeof(t1)); //output - 6
printf("%d\n",sizeof(t2)); //output - 7
}
Run Code Online (Sandbox Code Playgroud)
为什么两个结构 - 完全相同 - 采用不同的字节数?
我想编写一个通过移动或复制接收参数的模板函数。我使用的最有效的方法是:
void setA(A a)
{
m_a = std::move(a);
}
Run Code Online (Sandbox Code Playgroud)
在这里,当我们使用的是
A a;
setA(a); // <<---- one copy ctor & one move ctor
setA(std::move(a)); // <<---- two move ctors
Run Code Online (Sandbox Code Playgroud)
我最近发现以这种方式定义它,有两个功能:
void setA(A&& a)
{
m_a = std::move(a);
}
void setA(const A& a)
{
m_a = a; // of course we can so "m_a = std::move(a);" too, since it will do nothing
}
Run Code Online (Sandbox Code Playgroud)
会省很多!
A a;
setA(a); // <<---- one copy ctor
setA(std::move(a)); // <<---- one move ctor
Run Code Online (Sandbox Code Playgroud)
这很棒!对于一个参数...创建具有 10 个参数的函数的最佳方法是什么?!
void …Run Code Online (Sandbox Code Playgroud)