【发布时间】:2016-11-16 18:07:00
【问题描述】:
试图更好地掌握围绕 const 重载的规则。考虑以下代码 -
MyClass.h
class MyClass
{
public:
MyClass();
~MyClass();
};
MyClass.cpp
#include "MyClass.h"
MyClass::MyClass()
{
}
MyClass::~MyClass()
{
}
main.cpp
#include <iostream>
#include "MyClass.h"
#include <memory>
using namespace std;
/*
void test_function(MyClass& test)
{
cout << "ref to non const" << endl;
}
*/
void test_function(const MyClass& test)
{
cout << "ref to const" << endl;
}
/*
void test_shared_ptr( shared_ptr<MyClass>& test)
{
cout << "ref to non const shared ptr to non const" << endl;
}
void test_shared_ptr ( const shared_ptr<MyClass>& test)
{
cout << "ref to const shared ptr to non const" << endl;
}
*/
void test_shared_ptr (const shared_ptr<const MyClass>& test)
{
cout << "ref to const shared ptr to const" << endl;
}
int main()
{
MyClass non_const_my_class;
test_function(non_const_my_class);
const MyClass const_my_class;
test_function(const_my_class);
shared_ptr<MyClass> non_const_ptr_to_non_const = make_shared<MyClass> (MyClass());
test_shared_ptr(non_const_ptr_to_non_const);
const shared_ptr<MyClass> const_ptr_to_non_const = make_shared<MyClass>(MyClass());
test_shared_ptr(const_ptr_to_non_const);
const shared_ptr< const MyClass> const_ptr_to_const = make_shared< const MyClass>(MyClass());
test_shared_ptr(const_ptr_to_const);
int pause;
cin >> pause;
return 0;
}
注释掉方法后的输出是:
ref to const
ref to const
ref to const shared ptr to const
ref to const shared ptr to const
ref to const shared ptr to const
这个输出是我所期望的,但是我在一些围绕这种类型的 const 重载的代码上遇到了一个潜在的错误。真的只是想对以下陈述进行一些验证:
- 始终可以将非常量数据作为对 const 的引用传递给函数,只要该函数不试图违反其参数的 const 性。这会导致编译错误。
- 永远不行,因为它会导致编译错误,将 const 数据作为对非 const 的引用传递给函数。这将违反数据的常量性。
最后一个问题——
在什么情况下您可能需要如下代码?在我上面的测试代码中,将非 const 数据作为 const 引用传递给函数是非常好的,那么我为什么需要像这样执行 const_cast 呢?
void test_const_cast(const MyClass & test)
{
//Do something
}
void test_const_cast( MyClass & test)
{
test_const_cast(const_cast<MyClass const &>(test));
}
【问题讨论】: