“最令人头痛的语法解析”(C++’s most vexing parse)

如果你传递了一个临时变量,而不是一个命名的变量;

C++编译器会将其解析为函数声明,而不是类型对象的定义。
例如:

std::thread my_thread(background_task());


这里相当与声明了一个名为my_thread的函数,这个函数带有一个参数(函数指针指向没有参数并返回background_task对象的函数),返回一个 std::thread 对象的函数,而非启动了一个线程;


写成下边这样可能更好理解一些:

class background_task
{
public:
    background_task operator()()
    {
        std::cout << "hello concurrency world!" << std::endl;
        return *this;
    }
    void doSomeWork() { std::cout << "hello do some work!" << std::endl; }
};

C++ std::thread my_thread(background_task (*)())
background_task a;
std::thread th(&background_task::doSomeWork, &a);

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Content Containers...................................................................................................................1 Item 1. Choose your containers with care...........................................................1 Item 2. Beware the illusion of container-independent code................................4 Item 3. Make copying cheap and correct for objects in containers.....................9 Item 4. Call empty instead of checking size() against zero..............................11 Item 5. Prefer range member functions to their single-element counterparts...12 Item 6. Be alert for C++'s most vexing parse...................................................20 Item 7. When using containers of newed pointers, remember to delete the pointers before the container is destroyed............................................................22 Item 8. Never create containers of auto_ptrs....................................................27 Item 9. Choose carefully among erasing options..............................................29 Item 10. Be aware of allocator conventions and restrictions..........................34 Item 11. Understand the legitimate uses of custom allocators........................40 Item 12. Have realistic expectations about the thread safety of STL containers. 43 容器 条款1: 仔细选择你要的容器 条款2: 小心对“容器无关代码”的幻想 条款3: 使容器里对象的拷贝操作轻量而正确 条款4: 用empty来代替检查size是否为0 条款5: 尽量使用范围成员函数代替他们的单元素兄弟 条款6: 警惕C++的及其令人恼怒的分析 条款7: 当使用new得指针的容器时,切记在容器销毁前delete那些指针 条款8: 千万不要把auto_ptr放入容器中 条款9: 小心选择删除选项 条款10: 当心allocator的协定和约束 条款11: 了解自定义allocator的正统使用法 条款12: 对STL容器的线程安全性的期待现实一些

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值