我可以安全地memset一个具有用户定义构造函数的非平凡C++结构吗



我知道POD类可以安全地被memset。在c++17(?(中,std::is_pod被std::is标准布局和std::s私有替换如果一个非平凡但标准的布局结构只包含char[]数据和用户定义的构造函数,那么它可以安全地被memset吗

具有数十个char[]成员变量的遗留类。

#include <cstring>
#include <memory>
#include <iostream>
#include <type_traits>
struct A
{
// dozens of fields all char[] which need to initialized to '0'
char foo[10]; // example char[] field
// dozens of other fields all char[] which need to be initialized to non '0'
struct AA
{
char bar[10];
// dozens of other fields
} sub[7];
};
// What I want to turn struct A into
struct B
{
B()
{
// My question: Is this permissible?
std::memset(this, '0', sizeof(*this));
// Initialize all the other member variables that need different values
std::memset(foo, ' ', sizeof(foo));
}
// dozens of fields all char[] which need to initialized to '0'
char foo[10]; // example char[] field
// dozens of other fields all char[] which need to be initialized to other values in constructor
struct BB
{
char bar[10];
// dozens of other fields
} sub[7];
};
int main(int argc, char* argv[])
{
bool isTrivialA = std::is_trivial<A>::value;
bool isStandardLayoutA = std::is_standard_layout<A>::value;
bool isTrivialCopyA = std::is_trivially_copyable<A>::value;
std::cout << "Is A trivial: " << isTrivialA << std::endl;
std::cout << "Is A standard layout: " << isStandardLayoutA << std::endl;;
std::cout << "Is A trivial copy: " << isTrivialCopyA << std::endl << std::endl;
bool isTrivialB = std::is_trivial<B>::value;
bool isStandardLayoutB = std::is_standard_layout<B>::value;
bool isTrivialCopyB = std::is_trivially_copyable<B>::value;
std::cout << "Is B trivial: " << isTrivialB << std::endl;
std::cout << "Is B standard layout: " << isStandardLayoutB << std::endl;
std::cout << "Is B trivial copy: " << isTrivialCopyB << std::endl;
}

现有代码只是在使用对象时对其执行memset。

A legacy;
memset(&legacy, '0', sizeof(legacy));

我想在更新的结构B上调用用户定义的构造函数,因为除了"0"之外,还有几十个字段实际上需要初始化为不同的值。我知道我可以用一个非成员函数来初始化值,但这似乎很笨拙。

B newer; // Call user defined constructor

是否允许在B中使用'this'指针的memset((定义构造函数

没有任何机制允许"memset"成为对象上的有效操作。这包括"POD";标准中从来没有任何内容表明可以直接将数据任意写入POD类型的对象表示中。

简单的可复制性可以将对象表示复制到存储中,也可以将从该类型的有效实例中获取的数据直接复制到该类型的另一个实例中。但是,即使是这种指定,也无法将值直接任意设置到对象的表示中。

实际上,只使用(){}对对象进行值初始化会更容易,这(如果它没有构造函数,因此符合旧的POD定义(将对成员进行值初始化。

最新更新