【发布时间】:2019-06-27 12:06:54
【问题描述】:
我正在做一个项目并且得到一个我不理解的“奇怪行为”,它是关于传递 const ptr 来分配 const ref(或 const ptr 作为 const ref 参数)确实编译但为什么/如何? (我只是想明白) 我为测试做了一个较小的示例代码。 PS:如果有错误/误解,对不起,我不是英语母语人士
我用 -Wextra -Wall 编译
class dummy
{
public:
dummy(const bool &run): _dummy_run(run){}
void printRun()
{ std::cout << "RUN: " << _dummy_run << std::endl; }
private:
const bool &_dummy_run;
};
int main(int ac, char **av)
{
const bool *nullboolean = nullptr;
const bool *booleanptr = new bool(true);
/// Question 1
/// How / why passing a const ptr to a const reference is valid ?
dummy dummy_null(nullboolean);
dummy dummy_new(booleanptr);
/// Question 2
/// Why passing const ptr to const ref is allowed but not ptr to ref ?
const bool &cboolean = booleanptr;
// bool &boolean = booleanptr;
// => error: cannot bind non-const lvalue reference of type ‘bool&’ to an rvalue of type ‘bool’
/// Question 3
/// What happened here (print 191) ? There isn't any error on valgrind
dummy_null.printRun(); // Print 191
dummy_new.printRun(); // Print 1
return 0;
}
我的问题是为什么它在将 const ptr 传递给 const 引用时编译成功? 为什么它使用 const 参考编译而不是普通参考? 为什么在打印布尔值时我有一个像“191”这样的打印值(见代码)? (期望 0、1 或 valgrind 上的错误) 如果有人可以向我解释或有一个链接来了解这里发生了什么,我会很高兴? 谢谢!
【问题讨论】:
-
这可能与指向 bool (en.cppreference.com/w/cpp/language/implicit_conversion) 和临时指针的隐式转换有关。
标签: c++