64,654
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <new>
const int chunk = 16;
class Foo
{
public:
int val() { return _val; }
Foo() { _val = 0; }
private:
int _val;
};
char *buf = new char[ sizeof(Foo) * chunk ];
int main()
{
Foo *pb = new (buf) Foo;
if ( pb->val() == 0 )
std::cout << "new expression worked!" << std::endl;
delete[] buf;
return 0;
}
//感觉定位new用的比较少,平常都用在哪些地方呢。明天回家了,送一下分..
"二斗墨汁"
m_name[size - 1] = '\0';
#include <cstring>
#include <iostream>
using namespace std;
struct Name
{
Name(char * name = "")
{
int size = strlen(name) + 1;
if (size > 20) {
size = 20;
}
strncpy(m_name, name, size);
}
char m_name[20];
};
int main()
{
Name a;
cout << a.m_name << endl;
new (&a) Name("Adward Ink");
cout << a.m_name << endl;
new (&a) Name("二斗墨之");
cout << a.m_name << endl;
return 0;
}