这是一种伪代码,但它应该清楚我想知道的内容。我在不同的代码中看到了所有 3 个变体。
我的问题是这样做的正确方法是什么,为什么?(另见代码片段中的注释)
test.h 第一种方式:
class Test {
public:
Test()
:_buffer(NULL)
{
_buffer = new char[1024];
}
~Test() {
delete _buffer;
}
int Function() {
//use some function like inet_ntop doesn't work _buffer is not filled
inet_ntop(p->ai_family, addr, _buffer, sizeof(_buffer)-1);
//here sizeof(_buffer) returns 4, WHY ?
cout << sizeof(_buffer) << endl;
}
private:
char *_buffer;
};
test.h 第二种方式:
class Test {
public:
Test() {
//_buffer is never initialized WHY ?
}
~Test() {
//_buffer is never deleted WHY ?
}
int Function() {
//use some function like inet_ntop works correctly here _buffer is filled
inet_ntop(p->ai_family, addr, _buffer, sizeof(_buffer)-1);
//here sizeof(_buffer) returns 1024, WHY ?
cout << sizeof(_buffer) << endl;
}
private:
char _buffer[1024];
};
test.h 第三种方式:
class Test {
public:
Test() {
}
~Test() {
}
int Function() {
char buffer[1024];
//use some function like inet_ntop works correctly here _buffer is filled
inet_ntop(p->ai_family, addr, _buffer, sizeof(_buffer)-1);
//here sizeof(_buffer) returns 1024
cout << sizeof(_buffer) << endl;
}
private:
};