在GCC 4.7.3(QNX QCC编译器)下如何正确传递std::shared_ptr给构造函数?
核心错误修正
你的代码出现未定义引用的直接原因是类外定义构造函数时错误地添加了explicit关键字。explicit只能用于类内部的构造函数声明,类外定义时必须移除,否则编译器无法正确生成构造函数的符号,导致链接失败。GCC 9+会直接报错指出这个问题,而GCC 4.7.3虽无明确提示,但会因语法错误导致符号缺失。
修正后的foo.cpp代码:
#include "foo.hpp" #include <iostream> // 补充std::cout所需的头文件 foo::foo(std::shared_ptr<int> stuff) : mstuff(std::move(stuff)) { std::cout << "done" << std::endl; }
GCC 4.7.3下传递std::shared_ptr的恰当方式
GCC 4.7.3已支持C++11的移动语义和std::shared_ptr,根据需求选择以下两种传递方式:
1. 转移所有权(推荐用于需要接管指针的场景)
直接传递std::shared_ptr值,在构造函数初始化列表中用std::move转移所有权,避免额外的引用计数操作:
- 类内声明(保持
explicit):explicit foo(std::shared_ptr<int> stuff); - 类外定义(移除
explicit):foo::foo(std::shared_ptr<int> stuff) : mstuff(std::move(stuff)) {}
2. 共享所有权(仅需使用指针,不接管)
传递const std::shared_ptr<int>&常量引用,避免不必要的引用计数增减:
- 类内声明:
explicit foo(const std::shared_ptr<int>& stuff); - 类外定义:
foo::foo(const std::shared_ptr<int>& stuff) : mstuff(stuff) // 直接拷贝共享指针,共享所有权 {}
编译注意事项
GCC 4.7.3默认不开启C++11支持,编译时需显式指定标准:
qcc -std=c++11 main.cpp foo.cpp -o your_program
内容的提问来源于stack exchange,提问作者zombieanfuehrer
相关产品推荐
相关产品推荐

