简体   繁体   中英

What is the difference between initializing with implicitly and explicitly?

What is the difference in initializing variables i and j using the operator new and k and l using the std::auto_ptr in the following:

void foo() {
    // some code ...
    int* i(new int);
    int* j = new(int);
    // ... more code

    std::auto_ptr<int> k(returnsIntPtr());
    std::auto_ptr<int> l = returnsIntPtr();
    // ... some more code

    //delete i and j
}

Edit: To be clear I am interested in the difference in the initialize between i and j and difference between k and l . I know the difference using new and auto_ptr .

new(int)

Is equivalent to

new int

After a look at the grammar in [expr.new],

new-expression :
:: opt new new-placement opt new-type-id new-initializer opt
:: opt new new-placement opt ( type-id ) new-initializer opt

the intention is clear: There are types that are not parse-able in the traditional new type(..) way.
For instance,

auto i = new int(*)(); // Doesn't compile

auto j = new (int(*)()); // ... you guessed it


The second difference in your declarations, that is, direct-initialization vs copy-initialization, doesn't make a difference for scalars. So those statements are completely equivalent:

 int* i(0); int* i = 0; 

The second one is generally more prefered.

a std::auto_ptr (or unique or shared pointer) is a smart pointer. Its a feature of c++ which makes it possible, that you dont have to care about the destruction of the allocated memory in heap.

at example if you create something with new and dont delete it, you can get huge problems and even cause a crash, the smart pointers take care of this evidence.

If you only wanted to know whats the difference between creating them explicitly or implicitly... there pretty much isn´ta real difference as far as i know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM