c++ - Using a pointer in the same statement of its declaration -
i came across code pointer used on same line of declaration. essential sscce it:
#include "stdafx.h" #include <iostream> struct c { uint32_t a; }; int main() { c* pc = (c*) malloc(sizeof(*pc)); // <---- ??? pc->a = 42; std::cout << pc << std::endl; std::cout << pc->a << std::endl; free(pc); } when try similar uint32 (insert before free()):
uint32_t = + pc->a; std::cout << << std::endl; then either nothing printed statement, or while debugging random value stored in a , vs2015 gives me runtime warning. errorlevel after execution 3. know can't work.
why can use pointer? legal? why isn't compiler complaining such statements? statement split multiple statements behind scenes?
uint32_t = + pc->a; gives bad results because using value of a before initialized undefined behavior. more on see why 'int = i;' legal?
c* pc = (c*) malloc(sizeof(*pc)); on other hand not using value of pc in initialization. sizeof, when applied named variable, gives size of type. unevaluated operand means not evaluated. not using value of *pc instead getting size of pointer points c.
one reason want if changed type of pc not have change sizeof part. if had
c* pc = (c*) malloc(sizeof(c)); then need remember change sizeof(c) part when changing type of pc.
of course of can avoided using std::unique_ptr like
auto pc = std::make_unique<c>(); ^ here place have specify type
Comments
Post a Comment