Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

memory - In C++, why is `new` needed to dynamically create an object rather just allocation?

I've got this trivial class hierarchy:

class Base {
public:
    virtual int x( ) const = 0;
};

class Derived : public Base {
    int _x;
public:
    Derived( int x ) : _x(x) { }
    int x( ) const { return _x; }
};

If I use malloc to allocate an instance of Derived, and then try to access the polymorphic function x, program crashes (I get a segmentation fault):

int main( ) {
    Derived *d;
    d = (Derived*) malloc( sizeof(Derived) );
    *d = Derived( 123 );

    std::cout << d->x() << std::endl; // crash

    return 0;
}

Of course my actual application is a lot more complex (it's a sort of memory pool).


I'm pretty sure it's because of the way I allocate d: I didn't use new.

I know of placement new operator, which must be what I need, but I've never used it and have got some questions:

  • why is my application crashing, if I don't use new?

    What does new actually do?

    Why can't I just use the assignment operator to assign the value of Derived( 123 ); to the memory area pointed by d?

  • Would I need to use new also for non-polymorphic types?

    How about POD ones?

  • On the C++Faq I linked above it says that the memory region passed to placement new must be aligned for the object I'm creating.

    I know what alignment is, but I don't know how to check the alignment needed for my class.

    malloc manual says:

    The malloc() and calloc() functions return a pointer to the allocated memory that is suitably aligned for any kind of variable.

    And I hope that the alignment needed for my class is the class size as returned by sizeof, so that any address in the form address_returned_by_malloc + i * sizeof(my_class) is suitable to allocate my objects.

    Are my hopes right?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because malloc doesn't call the class's constructor, and doesn't know anything about any particular alignment requirements it might have. If you need to use malloc (not recommended), take a look at placement new (assuming you don't want to overload the regular new for some reason).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...