对这个数据结构:
struct MemoryBlockRef
{
void * data; // the start address
size_t size; // the size
// MemoryBlockRef(){}; //Constructor1
MemoryBlockRef() : data(), size() { } //Constructor2
MemoryBlockRef(void * d, size_t s) : data(d), size(s) { } //Constructor3
};
----------------------------------------------------------------
//Construct1
MemoryBlockRef ref1;
ref1.data 与 ref1.size 分别是0xcccccccc;
----------------------------------------------------------------
//Construct2
MemoryBlockRef ref2;
ref2.data 与 ref2.size 分别是0;
-----------------------------------------------------------------
验证代码:
#include "stdafx.h"
#include <iostream>
using namespace std;
struct MemoryBlockRef
{
void * data; // the start address
size_t size; // the size
// MemoryBlockRef(){}; //Constructor1
MemoryBlockRef() : data(), size() { } //Constructor2
MemoryBlockRef(void * d, size_t s) : data(d), size(s) { } //Constructor3
};
int main()
{
char arr[10];
MemoryBlockRef ref1;
// MemoryBlockRef ref2;
MemoryBlockRef ref3((void*) arr,10);
cout<<"ref1: data=" << ref1.data <<" size ="<<ref1.size <<endl;
cout<<"ref1 *data=" << &(ref1.data) <<" *size =" << &ref1.size <<endl;
// cout << "ref2.data=" << ref2.data << " ref2.size = " << ref2.size << endl;
// cout << "ref2.*data=" << &ref2.data << "&ref2.size = " << &ref2.size << endl;
cout << "ref3.data=" << ref3.data << " ref3.size = " << ref3.size << endl;
cout << "ref3.*data=" << &ref3.data << "&ref3.size = " << &ref3.size << endl;
return 0;
}
验证结果:
1.
ref1.data 与 ref1.size 分别是0xcccccccc;

2.
ref2.data 与 ref2.size 分别是0;

本文深入探讨了C++中MemoryBlockRef结构体的三种构造函数的使用与区别,通过实例验证了不同构造函数对成员变量data和size的初始化效果,为理解C++内存管理和初始化提供了实践案例。
1721

被折叠的 条评论
为什么被折叠?



