27

Lets show it in an example where we have a Data class with primary data, some kind of index that points to the primary data, and we also need to expose a const version the index.

class Data
{
public:
  const std::vector<int>& getPrimaryData() const { return this->primaryData; }
  const std::vector<int*>& getIndex() const { return this->index; }
private:
  std::vector<int> primaryData;
  std::vector<int*> index;
};

This is wrong, as the user can easily modify the data:

const Data& data = something.getData();
const std::vector<int*>& index = data.getIndex();
*index[0] = 5; // oups we are modifying data of const object, this is wrong

The reason of this is, that the proper type the Data::getIndex should be returning is:

const std::vector<const int*>&

But you can guess what happens when you try to write the method that way to "just convert the non-const variant to const variant":

// compiler error, can't convert std::vector<int*> to std::vector<const int*> these are unrelated types.
const std::vector<const int*>& getIndex() const { return this->index; }

As far as I know, C++ doesn't have any good solution to this problem. Obviously, I could just create new vector, copy the values from the index and return it, but that doesn't make any sense from the performance perspective.

Please, note that this is just simplified example of real problems in bigger programs. int could be a bigger object (Book lets say), and index could be index of books of some sort. And the Data might need to use the index to modify the book, but at the same time, provide the index to read the books in a const way.

16
  • 1
    "oups we are modifing data of const object" you are not modifying data of a const object. index[0] is unchanged 2 days ago
  • 1
    "Why would it be unchanged?" because *some_ptr = 42 does not modify some_ptr 2 days ago
  • 3
    std::experimental::propagate_const might help: std::vector<std::experimental::propagate_const<int*>> indexes;
    – Jarod42
    2 days ago
  • 7
    @kovarex The design itself is flawed so you won't find a good solution with plain c++. The dirty way is to use const int* internally and const_cast it away when write access is needed. A better solution would be to not pass a const std::vector<int*>& but instead give out the const_iterators on the data as read only access.
    – mkaes
    2 days ago
  • 2
    I disagree with design flow in general, const std::vector<std::vector<int>> would be fine for op. It is just that pointer indirection don't propagate constness.
    – Jarod42
    2 days ago

9 Answers 9

Help us improve our answers.

Are the answers below sorted in a way that puts the best answer at or near the top?

40

In C++20, you can just return a std::span with elements of type const int*

#include <vector>
#include <span>

class Data
{
public:
  std::span<const int* const> getIndex() const { return this->index; }
private:
  std::vector<int*> index;
};

int main() {
  const Data data;
  const auto index = data.getIndex();
  *index[0] = 5;  // error: assignment of read-only location
}

Demo

4
  • 2
    Huh. I didn't think this would work. Nice.
    – eerorika
    2 days ago
  • This is very specialised solution based on the simplified nature of the example using just std::vector. Once the index becomes anything more custom, this wouldn't work.
    – kovarex
    2 days ago
  • 7
    This method works for any continuous range. If you don't use a continuous range to store the index, the other answers based on pointers won't work either (like the one you accepted).
    – 康桓瑋
    2 days ago
  • @康桓瑋: Accepted propagate_const might works for std::list<propagate_const<int*>>.
    – Jarod42
    2 days ago
15

Each language has its rules and usages... std::vector<T> and std::vector<const T> are different types in C++, with no possibility to const_cast one into the other, full stop. That does not mean that constness is broken, it just means it is not the way it works.

For the usage part, returning a full container is generally seen as a poor encapsulation practice, because it makes the implementation visible and ties it to the interface. It would be better to have a method taking an index and returning a pointer to const (or a reference to a pointer to const if you need it):

const int* getIndex(int i) const { return this->index[i]; }

This works, because a T* can be const_casted to a const T *.

3
  • 2
    I beg to differ about the bad practice. I think the opposite, as bad practice is to unpack functionality of internal containers into the API, making class interfaces fat. In other words, imagine, that the index isn't just a std::vector<int*>, but a 3 layer structure of some complex indexing system. would you copy all the ways it can be accessed in to the surface layer of the Data class? For example, I couldn't use std::find_if and similar on the index anymore, and if I wanted to do it, I would have to implement iterators, begin/end methods in the Data class all for just allow proper ...
    – kovarex
    2 days ago
  • 3
    @kovarex: You are right on one point: adding unnecessary complexity is always bad. In the real world, it is even the strength of experienced analysts and devs: find the correct balance between the complexity of the interface, the complexity of the implementation and the strict respect of best practices. Rules are not to be blindly obeyed, but ignoring them without a strong reason is bad... 2 days ago
  • 5
    @kovarex ... Here you gave a simple example and I only answered about that example. IMHO, if you have a full example with all of its use cases and want to know how to improve it, you could try to post it to Code Review to get an exhaustive review. 2 days ago
9

The top answer, using ranges or spans, is a great solution, if you can use C++20 or later (or a library such as the GSL). If not, here are some other approaches.

Unsafe Cast

#include <vector>

class Data
{
public:
  const std::vector<const int>& getPrimaryData() const
  {
    return *reinterpret_cast<const std::vector<const int>*>(&primaryData);
  }

  const std::vector<const int* const>& getIndex()
  {
    return *reinterpret_cast<const std::vector<const int* const>*>(&index);
  }

private:
  std::vector<int> primaryData;
  std::vector<int*> index;
};

This is living dangerously. It is undefined behavior. At minimum, you cannot count on it being portable. Nothing prevents an implementation from creating different template overloads for const std::vector<int> and const std::vector<const int> that would break your program. For example, a library might add some extra private data member to a vector of non-const elements that it doesn’t for a vector of const elements (which are discouraged anyway).

While I haven’t tested this extensively, it appears to work in GCC, Clang, ICX, ICC and MSVC.

Smart Array Pointers

The array specialization of the smart pointers allows casting from std::shared_ptr<T[]> to std::shared_ptr<const T[]> or std::weak_ptr<const T[]>. You might be able to use std::shared_ptr as an alternative to std::vector and std::weak_ptr as an alternative to a view of the vector.

#include <memory>

class Data
{
public:
  std::weak_ptr<const int[]> getPrimaryData() const
  {
    return primaryData;
  }

  std::weak_ptr<const int* const[]> getIndex()
  {
    return index;
  }

private:
  std::shared_ptr<int[]> primaryData;
  std::shared_ptr<int*[]> index;
};

Unlike the first approach, this is safe. Unlike a range or span, this has been available since C++11.

Subranges

A good alternative to std::span is a std::ranges::subrange, which you can specialize on the const_iterator member type of your data. This is defined in terms of a begin and end iterator, rather than an iterator and size, and could even be used (with modification) for a container with non-contiguous storage.

This works in GCC 11, and with clang 14 with -std=c++20 -stdlib=libc++, but not all other compilers (as of 2022):

#include <ranges>
#include <vector>

class Data
{
private:
   using DataType = std::vector<int>;
   DataType primaryData;
   using IndexType = std::vector<DataType::pointer>;
   IndexType index;

public:
  /* The types of views of primaryData and index, which cannot modify their contents.
   * This is a borrowed range. It MUST NOT OUTLIVE the Data, or it will become a dangling reference.
   */
  using DataView = std::ranges::subrange<DataType::const_iterator>;
  // This disallows modifying either the pointers in the index or the data they reference.
  using IndexView = std::ranges::subrange<const int* const *>;

  /* According to the C++20 standard, this is legal.  However, not all
   * implementations of the STL that I tested conform to the requirement that
   * std::vector::cbegin is contstexpr.
   */    
  constexpr DataView getPrimaryData() const noexcept
  {
    return DataView( primaryData.cbegin(), primaryData.cend() );
  }

  constexpr IndexView getIndex() const noexcept
  {
    return IndexView( index.data(), index.data() + index.size() );
  }
};

You could define DataView as any type implementing the range interface, such as a std::span or std::string_view, and client code should still work.

7
  • @康桓瑋 I’ve now fixed the type of IndexView so that data,getIndex()[0] - 5; fails with the error returns a const value, and *data.getIndex()[0] = 5; fails with read-only variable is not assignable.`
    – Davislor
    yesterday
  • "This is living dangerously." Are you the kind of person who considers accepting the Terms and Conditions without reading them to be living dangerously? Because it's not really any more dangerous.
    – user541686
    16 hours ago
  • @user541686: Some people program not for fun, but in their jobs for important products or services. And in that environment the legal departments read contracts accurately. For good reason.
    – Sebastian
    15 hours ago
  • @user541686 There are things that are formally “undefined behavior” in C++ that I think are completely safe to use in practice, like fflush(stdin) or type-punning on a union of Plain Old Data. Every time a compiler has broken all the existing code that depends on something like those, it’s the language Standard that has changed to conform to what programs do in the real world. This time, I’m not as sure I have safety in numbers.
    – Davislor
    12 hours ago
  • 2
    @user541686 And, to be clear, the “danger” is not that you would get into some kind of trouble for not being a good little programmer. It’s that your code could break on a different version of the compiler or library. In theory, the language standards exist to prevent that from happening.
    – Davislor
    8 hours ago
8

You're asking for std::experimental::propagate_const. But since it is an experimental feature, there is no guarantee that any specific toolchain is shipped with an implementation. You may consider implementing your own. There is an MIT licensed implementation, however. After including the header:

using namespace xpr=std::experimental;
///...
std::vector<xpr::propagate_const<int*>> my_ptr_vec;

Note however that raw pointer is considered evil so you may need to use std::unique_ptr or std::shared_ptr. propagate_const is supposed to accept smart pointers as well as raw pointer types.

8
  • 8
    Note however that raw pointer is considered evil No it isn't. you may need to use std::unique_ptr or std::shared_ptr They shouldn't use those unless the pointers are owning.
    – eerorika
    2 days ago
  • 1
    @eerorika there is no information about the context, where the op is using pointers. There's even a std::experimental::observer_ptr for use cases that you intend. So, that evil is a tad darker than I mentioned.
    – Red.Wave
    2 days ago
  • 2
    @kovarex auto& index = data.getIndex(); 2 days ago
  • 2
    @kovarex using index_t = std::experimental:::propagate_const<int*> and const std::vector<Data::index_t>& index = data.getIndex()
    – Artyer
    2 days ago
  • 4
    @kovarex typedef, using, decl_type. std::vector::reference. A lot of ways to make life easier. I did alias the namespace to an abbreviation for very same reason.
    – Red.Wave
    2 days ago
8

You could return a transforming view to the vector. Example:

auto getIndex() const {
    auto to_const = [](int* ptr) -> const int* {
        return ptr;
    };
    return this->index | std::views::transform(to_const);
}

Edit: std::span is simpler option.


If index contains pointers to elements of primaryData, then you could solve the problem by instead storing integers representing the indices of the currently pointed objects. Anyone with access to non-const primaryData can easily turn those indices to pointers to non-const, others cannot.

primaryData isn't stable,

If primaryData isn't stable, and index contains pointers to primaryData, then the current design is broken because those pointers would be invalidated. The integer index alternative fixes this as long as the indices remain stable (i.e. you only insert to back). If even the indices aren't stable, then you are using a wrong data structure. Linked list and a vector of iterators to the linked list could work.

1
  • You are fixating too much on the technical part of the example, yes technically, the pointer to data would be invalidated, but this can be easily fixed if the data was just something different than a vector. That is not the core of the problem.
    – kovarex
    2 days ago
3

As mentioned in a comment, you can do this:

class Data
{
public:
  const std::vector<int>& getPrimaryData() const { return this->primaryData; }
  const std::vector<const int*>& getIndex() const { return this->index; }
private:
  std::vector<int> primaryData;
  std::vector<const int*> index;
  int* read_index_for_writing(std::size_t i) { return const_cast<int*>(index[i]); }
};

Good things about this solution: it works, and is safe, in every version of the standard and every compliant implementation. And it returns a vector reference with no funny wrapper classes – which probably doesn't matter to the caller, but it might.

Bad: you have to use the helper method internally, though only when reading the index for the purpose of writing the data. And the commenter described it as "dirty", but it seems clean enough to me.

3
  • How is that safe? vector<const int*> will construct a bunch of const int* objects. Modifying a const object though a non-const pointer is undefined behavior in the standard.
    – yeputons
    6 hours ago
  • I believe the last one is undefined: *read_index_for_writing(k) = v;
    – yeputons
    6 hours ago
  • Ah, never mind, I missed the part where index always points to primaryData. I'm sorry, perfectly safe in this case and no undefined behavior here (unless primaryData reallocates, but that's another story).
    – yeputons
    5 hours ago
2

Prepare the type like following, and use as return type of Data::getIndex().

class ConstIndex
{
private:
  const std::vector<int*> &index;
public:
  ConstIndex( const std::vector<int*> &index ) : index(index) {}

public:
  //Implement methods/types needed to emulate "const std::vector<const int*>"
  const int *operator[]( size_t i ) const { return index[i];    }
  const int *at( size_t i ) const { return index.at(i); }
  ...
};
2
  • std::span<const int* const> is very similar. 19 hours ago
  • This answer is just for the performance problem of "copy" written in this question. For the case of the sample written in this question, I will not employ this. I think that, the data structure inside the Data should be known only inside the Data, and it is not good that the user(outside) has to know it. Internal circumstances such as "How do you get the access to the data you want?" should be hidden (should be solved automatically/unknowingly).
    – fana
    25 mins ago
0

When you have the vector<int*> you have a constant container of pointers to ints. When you change the *index[0], you change the value to which the pointer points, not the value of the pointer as an element of the container (the address it holds).

Thus, the vector itself, as a container of elements with some values, remained unchanged.

To guard against it you'll need to make the pointers in the container const themselves (note the difference between pointers to const and const pointers)

8
  • This can't be used as solution, as changing the the index in the Data to: std::vector<const int*> index; wouldn't allow the Data class to use index to modify its own data anymore.
    – kovarex
    2 days ago
  • @kovarex that's well may be a sign to reconsider the design.
    – rawrex
    2 days ago
  • Why? What is wrong with the design?
    – kovarex
    2 days ago
  • @kovarex is index storing indices to primaryData ? If thats the case and if primaryData is "stable" (ie no insertions / removals take place once index is populated) you can store const_iterators isntead of bare int* 2 days ago
  • @kovarex you can't convert vector<foo*> to vector<const foo*> trivially as the C++ considers these different types. You have to copy each element separately.
    – Öö Tiib
    2 days ago
0

Here is an ugly solution that works with versions before C++20 using reinterpret_cast:

const std::vector<const int*>& getIndex() const{ 
    return reinterpret_cast<const std::vector<const int*>&>(data); 
}

Note this does actually return a reference bound to an lvalue, not a const& bound to an rvalue:

std::vector<const int*>& getIndex() const{ 
    return reinterpret_cast<std::vector<const int*>&>(data); 
}
2
  • 1
    Why doesn't the first cast cause UB? I don't think there's any guarantee that the memory layout must be the same for a container for T and const T.
    – Voo
    yesterday
  • It is UB. There's no reason to unsafely use reinterpret_cast when you can safely use const_cast – see my answer.
    – benrg
    6 hours ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.