문제

class someClass
{
public:
    int* ptr2Int;
};

Is this a valid class (yes it compiles)? Provided one assigns a value to ptr2Int before dereferencing it, is the class guaranteed to work as one would expect?

도움이 되었습니까?

해결책

An uninitialized pointer inside a class is in no way different from a standalone uninitailized pointer. As long as you are not using the pointer in any dangerous way, you are fine.

Keep in mind though that "dangerous ways" of using an uninitialized pointer include a mere attempt to read its value (no dereference necessary). The implicit compiler-provided copy-constructor and copy-assignment operators present in your class might perform such an attempt if you use these implicit member functions before the pointer gets assigned a valid value.

Actually, if I'm not mistaken, this issue was a matter of some discussion at the level of the standardization committee. Are the implicitly generated member functions allowed to trip over trap representations possibly present in the non-initialized members of the class? I don't remember what was the verdict. (Or maybe I saw that discussion in the context of C99?)

다른 팁

Yes, it's fine. The pointer itself exists, just its value is just unknown, so dereferencing it is unsafe. Having an uninitialized variable is perfectly fine, and pointers aren't any different

Yes, this is exactly the same as a struct with a single uninitialized pointer, and both are guaranteed to work just fine (as long as you set the pointer before any use of it, of course).

Until you dereference the pointer it's all good, then it's undefined territory.

Some compilers will set pointers to default values (like null) depending if you compile in debug or release mode. So things could work in one mode and suddenly everything falls apart in another.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top