我读过thisarticleaboutC/C++strictaliasing.我认为这同样适用于C++。据我了解,严格别名用于重新排列代码以实现性能优化。这就是为什么两个不同(在C++情况下不相关)类型的指针不能引用相同的内存位置。这是否意味着只有修改内存才会出现问题?除了可能的问题withmemoryalignment.例如,处理网络协议(protocol),或反序列化。我有一个字节数组,动态分配并且数据包结构正确对齐。我可以reinterpret_cast它到我的数据包结构吗?charconst*buf=...;//dynamicallyallocatedunsignedinti=
我可以创建以下内容:usingFoo=struct{/*Implementation*/};templateusingBar=Foo;但是以下是不允许的:templateusingBar=struct{/*Implementation*/};Clang的错误比GCC更有用,它指出:error:'(anonymousstructatfile:line:column)'cannotbedefinedinatypealiastemplate不允许第二个代码示例的任何原因?注意:请说明第二个代码示例(如果允许)可能导致语言问题的任何示例。标准中的任何引用也很有帮助。
在g++中启用严格别名警告的正确方法是什么?VC++10是否实现了这些规则? 最佳答案 对g++使用-fstrict-aliasing。我还使用-Wstrict-aliasing=2查看与可能违反严格别名规则的行为相关的警告。 关于c++-在g++中启用严格的别名警告,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8552802/
我最近遇到了一个问题。我实际上认为它不能像我希望的那样解决,但如果可以的话会很方便。无论如何,这是问题所在:我将给你一个我几天前在这个论坛上看到的例子,因为用它来解释会更容易。假设我正在尝试通过这种方式创建张量结构:templatestructTensor{Tensorx;Tensory;Tensorz;};为了避免无限递归,我必须为N=1编写模板特化。templatestructTensor{doublex;doubley;doublez;};其实,当N=1时,这个Tensor其实就是一个Vector(物理的)。假设我已经有一个这样定义的Vector结构:structVector{d
假设我有一个函数可以操作字符串,并且可以完美处理所有字符类型。templatestd::basic_stringfoo_basic_string(){returnstd::basic_string,allocator>();}我想要函数foo_string和foo_wstring成为foo_basic_string的一个版本并返回std::string和std::wstring,分别。一种方式是std::stringfoo_string(){returnfoo_basic_string();}std::wstringfoo_wstring(){returnfoo_basic_strin
这个问题在这里已经有了答案:WhereandwhydoIhavetoputthe"template"and"typename"keywords?(8个答案)关闭7年前。我对c++11中的“using”关键字有一些疑问。这段代码应该为指向另一种类型的指针创建别名。templateclassSomeClass{typedeftypenamestd::add_pointer::typepointer;templateusingrebind_pointer=typenamestd::pointer_traits::rebind;}SomeClassobj;但是在gcc4.7中我遇到了编译错误:
我有一个函数需要一个unsignedlong*并且需要将它传递给一个外部库,这个外部库需要一个unsignedint*并且在这个平台上unsignedint/long是相同的大小。voidUpdateVar(unsignedlong*var){//thisfunctionwillchangethevalueattheaddressofvarExternalLibAtomicUpdateVar((unsignedint*)var);//libatomicallyupdatesvariable}这会生成一条警告,说明它违反了严格的别名规则。有什么变通办法吗?谢谢编辑:我很抱歉没有说清楚。该
我编写了一个模板函数,它接受任意数量的类型并针对底层架构和操作系统显示它们的大小。但是,该函数无法区分别名和实型,因此它被评估为就好像它是实型一样。但我希望能够在编译时区分别名和内置类型,并根据它交替输出。func();输出:Unsignedintis4bytes.Unsignedintis4bytes.但是,我希望输出是这样的Unsignedintis4bytes.size_tisanaliasforunsignedint.当然,这要求编译器能够在编译时区分别名和内置类型。那么,在任何C++版本中,有没有办法在编译时区分真实类型和别名? 最佳答案
我有一个头文件,我希望在其中定义类时使用namespace别名。但是,我不想将此别名暴露给包含头文件的任何内容。//foo.hnamespacequx=boost::std::bar::baz::qux;//!exposedtotheworldclassfoo{//can'tputanamespacealiashere//stuffusingqux::};我如何才能为类声明命名空间而不会泄露到任何地方? 最佳答案 namespaceMyClassSpace{namespacequx=boost::std::bar::baz::qux
在ISO/IEC9899:TC2中,标准说明如下6.3.2.3PointersApointertoanobjectorincompletetypemaybeconvertedtoapointertoadifferentobjectorincompletetype.Iftheresultingpointerisnotcorrectlyalignedforthepointed-totype,thebehaviorisundefined.Otherwise,whenconvertedbackagain,theresultshallcompareequaltotheoriginalpointer