我可以隐式创建一个可复制的类型吗? [英] Can I implicitly create a trivially copiable type

查看:98
本文介绍了我可以隐式创建一个可复制的类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是这个

假设类型T是可复制的....可以在不调用构造函数的情况下创建"这种类型的实例....像这样:

Suppose type T is trivially copyable....can "create" an instance of this type without calling a constructor....like so:

#include <type_traits>
#include <cstring>

using T = int; // T can be any trivially copyable type


T create(const T& other)
{
    std::aligned_storage_t<sizeof(T),alignof(T)> my_T;

    std::memcpy(&my_T,&other,sizeof(T));

    return *reinterpret_cast<T*>(&my_T);
}

这是已定义的行为,还是只能复制到T类型的现有对象中?

Is this defined behavior, or can I only copy into an existing object of type T?

推荐答案

规则,来自 [对象] 是:

在隐式更改联合的活动成员([class.union])或创建临时对象([ conv.rval],[class.temporary]).

An object is created by a definition ([basic.def]), by a new-expression, when implicitly changing the active member of a union ([class.union]), or when a temporary object is created ([conv.rval], [class.temporary]).

这些都没有发生,因此您没有对象.存在隐式对象创建.从技术上讲,该类型转换为UB,因为在my_T处没有类型为T的对象.

None of those things is happening here, so you don't have an object. There is implicit object creation. That cast is technically UB because there is no object of type T at my_T.

简单可复制的意思是,如果您随后将字节从my_T复制到另一个T对象,则将得到与使用复制构造函数复制T相同的行为.但是您仍然需要对象已经存在.

What trivially copyable means is that if you then copied the bytes from my_T into another T object, then you would get the same behavior as if you'd just copied the T using the copy constructor. But you still need the objects to have already existed.

请注意,通过 P0593 .在很多地方,您实际上只需要说我在这里有一个T"即可完成工作,并且每个编译器都已允许这样做.只是这个概念远远超出了我们今天在C ++中拥有的对象模型.

Note that this is an area that is being actively worked on, via P0593. There are many, many places where you really just need to say "I have a T here" and have that work, and every compiler already allows for that. It's just that that concept exists far outside of the object model that we have in C++ today.

这篇关于我可以隐式创建一个可复制的类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆