简体   繁体   中英

How to create unique pointers in a loop C++?

I am reading a double from the standard input and saving it into a variable d . I want to be able to do this an unspecified amount of times. I use the following code to create a pointer to d .

double *pd = new double;
pd = &d;

I then push this pointer into a constructed stack (list) class. But whenever I push more than one double it changes all of them (the pointer is the same).

Ex. push 2 and get an array [2]. push 3 and get array [3, 3] instead of [3, 2].

Why are you using pointers at all?

std::vector<double> v;

double d;
while (std::cin >> d)
    v.push_back(d);

Or as chris points out:

std::copy(std::istream_iterator<double>(std::cin),
          std::istream_iterator<double>(),
          std::back_inserter(v));
*pd = d

instead of

pd = &d;

What you do is:

  • you have double d variable on stack
  • you create double and save its pointer in pd variable
  • then you save address to d variable in pd
  • and then you save address from pd on list

This means you have list of addresses to variable d (every single object on list is pointer to d variable).

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