-3
#include <memory>
#include <string>

int main()
{
    auto foo = std::make_unique<std::string>("hello");
    auto bar = foo;   // deleted copy !!
    return 0;
}

I understand why that code does not compile: I cannot copy a unique_ptr; this is the whole point of being unique.

Question: can I give a small name/reference/alias to foo ?

USE CASE

In my real live, I have a nested structure like std::vector<std::unique_ptr<MyClass>>.

Let X be such an object. I want to work with X[0] and call myMethod; I do

X[0]->myMethod;

Now for clarity, I want to give a (temporary) name to X[0], for example: first. This is why I want to do auto first = X[0].

Is there a way ? Maybe a weak pointer ? I'm not fluent in c++ ;)

EDIT: Not a duplication of this one. Even if the answer is the same, the spirit of the question differs. The linked question is a precise theoretical question while here I ask for a way to define a "shorthand" for a variable by whatever mean.

Laurent Claessens
  • 357
  • 1
  • 2
  • 15
  • 4
    if you want `bar` to be a reference then make it a reference `auto& bar = foo;` – 463035818_is_not_a_number May 23 '22 at 19:39
  • 5
    Use a reference? `auto& first = X[0];`? – NathanOliver May 23 '22 at 19:39
  • nice! What are the consequences on the live cycle ? If I do that in a function, `bar` is destroyed exiting the function while `foo` is still there and the data behind still available ? – Laurent Claessens May 23 '22 at 19:42
  • 4
    references is a rather basic concept in C++. It should be explained in any introduction, see eg here https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list. No, `bar` going out of scope has no effect on `foo` – 463035818_is_not_a_number May 23 '22 at 19:50
  • 2
    If you want multiple variables to control the life time of a pointer don't use `std::unique_ptr` use `std::shared_ptr`. – Richard Critten May 23 '22 at 19:59
  • Is your question "Does C++ have references / aliases?" I _think_ that is what you are asking. – Drew Dormann May 23 '22 at 20:09
  • *Question: can I give a small name/reference/alias to `foo`?* Yes. In C++, it's called a reference. `auto& bar = foo;` (a reference to the unique_ptr) or `auto& bar = *foo;` (a reference to the object held by the unique_ptr). – Eljay May 23 '22 at 20:42

0 Answers0