当询问C中常见的未定义行为时,灵魂比我提到的严格别名规则更加开明.
他们在说什么?
可能重复:
移动语义==自定义交换功能已过时?
这就是std::swapC++ 11中的样子:
template<typename T>
void swap(T& x, T& y)
{
T z = std::move(x);
x = std::move(y);
y = std::move(z);
}
Run Code Online (Sandbox Code Playgroud)
如果我的类定义了移动构造函数和移动赋值运算符,我还是必须专注std::swap于我自己的类型,或者它会std::swap尽可能高效吗?
我有一些使用类型惩罚的代码,以避免必须调用成员"对象"的构造函数和析构函数,除非/直到实际需要使用该对象.
它工作正常,但在g ++ 4.4.3下,我得到了这个可怕的编译器警告:
jaf@jeremy-desktop:~$ g++ -O3 -Wall puns.cpp
puns.cpp: In instantiation of ‘Lightweight<Heavyweight>’:
puns.cpp:68: instantiated from here
puns.cpp:12: warning: ignoring attributes applied to ‘Heavyweight’ after definition
puns.cpp: In destructor ‘Lightweight<T>::~Lightweight() [with T = Heavyweight]’:
puns.cpp:68: instantiated from here
puns.cpp:20: warning: dereferencing type-punned pointer will break strict-aliasing rules
puns.cpp: In member function ‘void Lightweight<T>::MethodThatGetsCalledRarely() [with T = Heavyweight]’:
puns.cpp:70: instantiated from here
puns.cpp:36: warning: dereferencing type-punned pointer will break strict-aliasing rules
Run Code Online (Sandbox Code Playgroud)
我的代码尝试使用gcc的__attribute((__ may_alias__))让gcc知道潜在的别名,但是gcc似乎并不理解我想告诉它的内容.我做错了什么,或者gcc 4.4.3只是在__may_alias__属性上遇到了一些问题?
重现编译器警告的玩具代码如下:
#include <stdio.h>
#include <memory> // …Run Code Online (Sandbox Code Playgroud)