开发者

Question on object lifetime : N3242 Draft

A point from C++11 n3242 "Duration of subobjects, object lifetime", 3.8/1:

The lifetime of an object is a runtime property of the object. An object is said to have non-trivial initialization if it is of a class or aggregate type and it or one of its members is initialized by a constructor other than a trivial default constructor [ Note: initialization by a trivial copy/move constructor is non-trivial initialization. — end note ]

The lifetime of an object of type T begins when:

  • storage with the proper alignment and size for type T is obtained, and
  • if the object has non-trivial initialization, its initialization is complete.

The lifetime of an object of type T ends when:

  • if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or
  • the storage which the object occupies is reused or released.

Here they said about trivial or nontrivial copy/move constructor with object lifetime. Can any one explain this wi开发者_StackOverflowth some example program?

And the change of an point describes when the lifetime of an object of type T begins, but they didn't mention when T ends. Why?


Here they said about trivial or nontrivial copy/move constructor with object lifetime. Can any one explain this with some example program?

It's just semantics. In all cases, this can be translated to "the object's lifetime begins when the constructor has finished running". The quote is just being thorough because trivial construction doesn't really involve any such execution.

It's not easy to give an "example" of this point; I could show you trivial and non-trivial constructors, but it wouldn't really tell you anything so I'm not going to.

And the change of an point describes when the lifetime of an object of type T begins, but they didn't mention when T ends. Why?

Yes they did. It should be clearer now that I reformatted the quote in your question.


In general an object is alive when its constructor has run to completion and lives until the start of its destructor.

An exception is types that are so trivial that there is no constructor run for them, for example after the code

int* p = (int*)malloc(1024);

you have a bunch of ints that are alive, even though they are not initialized in any way and no constructors have been executed. Still, they are there and you can assign them values.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜