How can I propagate const when returning a std::vector from a const method?

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 … Read more

Idiomatic Way to declare C++ Immutable Classes

The way you proposed is perfectly fine, except if in your code you need to make assignment of RockSolid variables, like this: RockSolid a(0,1); RockSolid b(0,1); a = b; This would not work as the copy assignment operator would have been deleted by the compiler. So an alternative is to rewrite your struct as a … Read more

Sell me const-correctness

This is the definitive article on “const correctness”: https://isocpp.org/wiki/faq/const-correctness. In a nutshell, using const is good practice because… It protects you from accidentally changing variables that aren’t intended be changed, It protects you from making accidental variable assignments. For instance, you are protected from if( x = y ) // whoops, meant if( x == … Read more

What is the best smart pointer return type for a factory function?

I’ll answer in reverse order so to begin with the simple cases. Utility functions that accept objects from the factory functions, use them, but do not take ownership. (For example a function that counts the number of words in the document.) If you are calling a factory function, you are always taking ownership of the … Read more

Write-Only pointer type

I’d probably write a tiny wrapper class for each: template <class T> class read_only { T volatile *addr; public: read_only(int address) : addr((T *)address) {} operator T() volatile const { return *addr; } }; template <class T> class write_only { T volatile *addr; public: write_only(int address) : addr ((T *)address) {} // chaining not allowed … Read more

What are the use cases for having a function return by const value for non-builtin type?

Basically, there’s a slight language problem here. std::string func() { return “hai”; } func().push_back(‘c’); // Perfectly valid, yet non-sensical Returning const rvalues is an attempt to prevent such behaviour. However, in reality, it does way more harm than good, because now that rvalue references are here, you’re just going to prevent move semantics, which sucks, … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)