I want to have a try in PIMPL in C++.
In my case, I am using operator()
to access private member.
The interface class A
and implement class AImpl
all have operator() const
and operator()
.
The code shown as follows:
#include <iostream>
class AImpl
{
public:
explicit AImpl()
{
x = 0;
}
const int &operator()() const
{
std::cout << "const access in AImpl" << std::endl;
return x;
}
int &operator()()
{
std::cout << "not const access in AImpl" << std::endl;
return x;
}
private:
int x;
};
class A
{
public:
A()
{
impl = new AImpl;
}
~A()
{
delete impl;
}
const int &operator()() const
{
std::cout << "const access in A" << std::endl;
return impl->operator()();
}
int &operator()()
{
std::cout << "not const access in A" << std::endl;
return impl->operator()();
}
private:
AImpl *impl;
};
int main()
{
A non_const_a;
std::cout << non_const_a() << std::endl;
const A const_a;
std::cout << const_a() << std::endl;
}
I compile the program with follow command
g++ Main.cpp
The result showns that:
# ./a.out
not const access in A
not const access in AImpl
0
const access in A
not const access in AImpl
0
It can be seen from the result that:
A
's const member function const int &A::operator()() const
call the int &AImpl::operator()()
, but not call the const int &AImpl::operator()() const
.
Why this happened?
In PIMPL case, I want the member function in A and and AImpl are one-to-one correspondence.
I want let const int &A::operator()() const
call const int &AImpl::operator()() const
.
How can I modify my code to achieve that? Does the modification will slow down any performance?
The mention above is a simple case. In real case, the A is a container and will widly used in my code, thus I do not want the modification slow down the performance.
I apologize if it is a stupid problem. Thanks for your time.