Is it possible to build in C ++ only const objects of a certain type?

I want to implement a class with the following properties:

class A { ... };

const A a;  // ok - should work.
A b;        // compilation error - shouldn't work!

In addition, it would be better if the value of the constobject depends on the signature of the constructors:

const A c(1);  // ok - should work.
A d("a");      // ok - should work.
A e(2);        // compilation error - shouldn't work!

If necessary, the use of C ++ 11 is allowed.


Update # 1

Since I do not know the answer, it does not need to strictly follow the code above - any C ++ template that provides similar semantics is welcome.

+4
source share
4 answers

1. You can only create a class with const methods and private members.

2. "normal", private. friend ( - )

class ConstClassProvider{
public:
    static const A* getA(/* you can have params here*/)
    {
        return new A();
    }
}

A a1;//error
const A a2;//error
A *a3 = ConstClassProvider::getA(); //error
const A *a4 = ConstClassProvider::getA(); //ok!
+5

. , , - .

:

class Immutable{
private:
  const int intField;
  const std::string textField;
public:
  Immutable(const std::string& ref, int copy) : intField{copy}, testField{ref} {}
  int getIntField(){return intField;}
  const std::string& getTextField(){ return textField; }
}

.

+2

, self, :

class X {
public:
    X(X const& self) {
        assert(this == &self);
    }

private:
    X(X&);
};

:

X const x(x); // works
X y(y); // fails to compile
X z(x); // fails at run-time
+1

, :

class AData {
public:
    AData() : intValue( 0 ), stringValue( 0 ) {}
    void SetInt( int arg ) { intValue = arg; }
    void SetString( const char* arg ) { stringValue = arg; }

private:
    int intValue;
    const char* stringValue;
};

class A {
public:
    A();
    void Init( int intValue ) const;
    void Init( const char* stringValue );

private:
    AData* p;
};

A::A() : p( new AData )
{
}

void A::Init( int intValue ) const
{
    p->SetInt( intValue );
}

void A::Init( const char* stringValue )
{
    p->SetString( stringValue );
}
0

Source: https://habr.com/ru/post/1527348/


All Articles