0

I am aware of the following post:

Does C++11 allow vector<const T>?

however I am not able to solve my problem. I am trying to define a vector with a list of const shared_ptr of my class "Example", because these class instances should not be changed.

std::vector<const std::shared_ptr<Example>> myVector;

But when I try to add a const value to the vector, it does not compile:

const std::shared_ptr<Example> example = createMyObject();
myVector.append(example); // compiler error

I am also aware of this post: Non-copyable elements in vector however there is no real answer to my issue. Since my class Example offers several setters, I need to make them const so they cannot be changed.

malajedala
  • 867
  • 2
  • 8
  • 22
  • 4
    `const std::shared_ptr` the const applies to the `std::shared_ptr` not `Example`. Try `std::vector< std::shared_ptr< const Example >> myVector;` – Richard Critten Oct 08 '21 at 09:20
  • 3
    `std::vector` does not have a `append` function – UnholySheep Oct 08 '21 at 09:21
  • 1
    `const std::shared_ptr` is not `std::shared_ptr` (as well as `Example*const` is not `const Example*`). Notice how the location of `const`s is "reverted" between smart pointers and raw pointers... – Scheff's Cat Oct 08 '21 at 09:22
  • In the first question you linked, substitute `T` with `shared_ptr` and it exactly explains why your code can not work. – Ulrich Eckhardt Oct 08 '21 at 09:23
  • Did you want a `std::vector>` maybe? Then just replace the non-existent `append` with `push_back` and everything should work. – Lukas-T Oct 08 '21 at 09:39
  • Ok yes sorry about `append`, it is a remainder of the framework I use but wanted to keep out of the question. I have tried it with `std::vector>` and you are right, the instances cannot be changed, but however I can still change the shared_ptr stored on a index in the vector... – malajedala Oct 08 '21 at 09:42
  • 1
    @malajedala then only make `const std::vector< std::shared_ptr< const Example >> myVector;` available to client code that is not allowed to change the vector. Have a think about your full requirements and perhaps update the post. – Richard Critten Oct 08 '21 at 10:39
  • Did you read [this answer](https://stackoverflow.com/a/39926929) to the question you said you are aware of? It specifically covers `shared_ptr` syntax. – JaMiT Oct 09 '21 at 03:55

0 Answers0