- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我最近看到一个类似这样的类,它用于“按需”构造对象,而不必出于各种原因使用动态内存分配。
#include <cassert>
template<typename T>
class StaticObject
{
public:
StaticObject() : constructed_(false)
{
}
~StaticObject()
{
if (constructed_)
((T*)object_)->~T();
}
void construct()
{
assert(!constructed_);
new ((T*)object_) T;
constructed_ = true;
}
T& operator*()
{
assert(constructed_);
return *((T*)object_);
}
const T& operator*() const
{
assert(constructed_);
return *((T*)object_);
}
private:
bool constructed_;
alignas(alignof(T)) char object_[sizeof(T)];
};
此代码(即将正确对齐的 char 数组转换为对象指针)是否被 C++14 标准视为未定义行为,还是完全没问题?
最佳答案
这个程序在技术上有未定义的行为,尽管它可能适用于大多数实现。问题是来自 char*
的类型转换至 T*
不保证产生指向 T
的有效指针由 placement new 创建的对象,即使 char*
指针表示用于存储 T
的第一个字节的地址对象。
Pointers to layout-compatible types shall have the same value representation and alignment requirements ([basic.align]).
一般来说,T
不会与 char
布局兼容或 alignas(T) char[sizeof(T)]
, 所以不需要指针 T*
与指针具有相同的值表示 char*
或 void*
.
Two objects a and b are pointer-interconvertible if:
they are the same object, or
one is a union object and the other is a non-static data member of that object ([class.union]), or
one is a standard-layout class object and the other is the first non-static data member of that object, or, if the object has no non-static data members, any base class subobject of that object ([class.mem]), or
there exists an object c such that a and c are pointer-interconvertible, and c and b are pointer-interconvertible.
If two objects are pointer-interconvertible, then they have the same address, and it is possible to obtain a pointer to one from a pointer to the other via a
reinterpret_cast
. [ Note: An array object and its first element are not pointer-interconvertible, even though they have the same address. — end note ]
[旁白:DR 2287在 C++17 发布后,在第二个项目符号中将“标准布局 union 体”更改为“union 体”。但这并不影响这个程序。]
T
放置 new 创建的对象不能与 object_
进行指针互换或 object_[0]
.注释暗示这可能是类型转换的问题......
对于 C 风格的转换 ((T*)object_)
, 我们需要看 [expr.cast]/4 :
The conversions performed by
a
const_cast
,a
static_cast
,a
static_cast
followed by aconst_cast
,a
reinterpret_cast
, ora
reinterpret_cast
followed by aconst_cast
can be performed using the cast notation of explicit type conversion....
If a conversion can be interpreted in more than one of the ways listed above, the interpretation that appears first in the list is used, even if a cast resulting from that interpretation is ill-formed.
除非T
是char
或简历合格 char
, 这实际上是一个 reinterpret_cast
,所以接下来我们看[expr.reinterpret.cast]/7 :
An object pointer can be explicitly converted to an object pointer of a different type. When a prvalue
v
of object pointer type is converted to the object pointer type "pointer to cvT
", the result isstatic_cast<
cvT*>(static_cast<
cvvoid*>(v))
.
所以首先我们有一个 static_cast
来自 char*
至 void*
,它执行 [conv.ptr]/2 中描述的标准转换:
A prvalue of type "pointer to cv
T
", whereT
is an object type, can be converted to a prvalue of type "pointer to cvvoid
". The pointer value ([basic.compound]) is unchanged by this conversion.
后面跟着一个 static_cast
来自 void*
至 T*
,描述于 [expr.static.cast]/13 :
A prvalue of type "pointer to cv1
void
" can be converted to a prvalue of type "pointer to cv2T
", whereT
is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. If the original pointer value represents the addressA
of a byte in memory andA
does not satisfy the alignment requirement ofT
, then the resulting pointer value is unspecified. Otherwise, if the original pointer value points to an object a, and there is an object b of typeT
(ignoring cv-qualification) that is pointer-interconvertible with a, the result is a pointer to b. Otherwise, the pointer value is unchanged by the conversion.
如前所述,T
类型的对象不能与 object_[0]
进行指针互换,所以这句话不适用,也不能保证结果 T*
指向 T
目的!我们剩下的句子是“指针值未更改”,但如果 char*
的值表示,这可能不是我们想要的结果。和 T*
指针差异太大。
可以使用 union
实现此类的符合标准的版本:
template<typename T>
class StaticObject
{
public:
StaticObject() : constructed_(false), dummy_(0) {}
~StaticObject()
{
if (constructed_)
object_.~T();
}
StaticObject(const StaticObject&) = delete; // or implement
StaticObject& operator=(const StaticObject&) = delete; // or implement
void construct()
{
assert(!constructed_);
new(&object_) T;
constructed_ = true;
}
T& operator*()
{
assert(constructed_);
return object_;
}
const T& operator*() const
{
assert(constructed_);
return object_;
}
private:
bool constructed_;
union {
unsigned char dummy_;
T object_;
}
};
或者更好,因为这个类本质上是在尝试实现 optional
, 只需使用 std::optional
如果你有它或 boost::optional
如果你不这样做。
关于c++ - 将 char 数组转换为对象指针 - 这是 UB 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51231757/
我的一位教授给了我们一些考试练习题,其中一个问题类似于下面(伪代码): a.setColor(blue); b.setColor(red); a = b; b.setColor(purple); b
我似乎经常使用这个测试 if( object && object !== "null" && object !== "undefined" ){ doSomething(); } 在对象上,我
C# Object/object 是值类型还是引用类型? 我检查过它们可以保留引用,但是这个引用不能用于更改对象。 using System; class MyClass { public s
我在通过 AJAX 发送 json 时遇到问题。 var data = [{"name": "Will", "surname": "Smith", "age": "40"},{"name": "Wil
当我尝试访问我的 View 中的对象 {{result}} 时(我从 Express js 服务器发送该对象),它只显示 [object][object]有谁知道如何获取 JSON 格式的值吗? 这是
我有不同类型的数据(可能是字符串、整数......)。这是一个简单的例子: public static void main(String[] args) { before("one"); }
嗨,我是 json 和 javascript 的新手。 我在这个网站找到了使用json数据作为表格的方法。 我很好奇为什么当我尝试使用 json 数据作为表时,我得到 [Object,Object]
已关闭。此问题需要 debugging details 。目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and the
我听别人说 null == object 比 object == null check 例如: void m1(Object obj ) { if(null == obj) // Is thi
Match 对象 提供了对正则表达式匹配的只读属性的访问。 说明 Match 对象只能通过 RegExp 对象的 Execute 方法来创建,该方法实际上返回了 Match 对象的集合。所有的
Class 对象 使用 Class 语句创建的对象。提供了对类的各种事件的访问。 说明 不允许显式地将一个变量声明为 Class 类型。在 VBScript 的上下文中,“类对象”一词指的是用
Folder 对象 提供对文件夹所有属性的访问。 说明 以下代码举例说明如何获得 Folder 对象并查看它的属性: Function ShowDateCreated(f
File 对象 提供对文件的所有属性的访问。 说明 以下代码举例说明如何获得一个 File 对象并查看它的属性: Function ShowDateCreated(fil
Drive 对象 提供对磁盘驱动器或网络共享的属性的访问。 说明 以下代码举例说明如何使用 Drive 对象访问驱动器的属性: Function ShowFreeSpac
FileSystemObject 对象 提供对计算机文件系统的访问。 说明 以下代码举例说明如何使用 FileSystemObject 对象返回一个 TextStream 对象,此对象可以被读
我是 javascript OOP 的新手,我认为这是一个相对基本的问题,但我无法通过搜索网络找到任何帮助。我是否遗漏了什么,或者我只是以错误的方式解决了这个问题? 这是我的示例代码: functio
我可以很容易地创造出很多不同的对象。例如像这样: var myObject = { myFunction: function () { return ""; } };
function Person(fname, lname) { this.fname = fname, this.lname = lname, this.getName = function()
任何人都可以向我解释为什么下面的代码给出 (object, Object) 吗? (console.log(dope) 给出了它应该的内容,但在 JSON.stringify 和 JSON.parse
我正在尝试完成散点图 exercise来自免费代码营。然而,我现在只自己学习了 d3 几个小时,在遵循 lynda.com 的教程后,我一直在尝试确定如何在工具提示中显示特定数据。 This code
我是一名优秀的程序员,十分优秀!